Skip to content

Write HTML. Render video. Built for agents.

feat(studio): mirror canvas z-order actions into timeline lanes (track order = default paint order) (#2380)

Ular Kimsanov89db7188994b
diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc
index 52dc3e3adf..a79e4dfdba 100644
--- a/.fallowrc.jsonc
+++ b/.fallowrc.jsonc
@@ -499,6 +499,31 @@
// scopeRootSelectors handling shifts lines and re-flags both.
"packages/core/src/compiler/inlineSubCompositions.ts",
"packages/core/src/compiler/compositionScoping.test.ts",
+ // useCanvasZOrderTimelineMirror.test.tsx: independent gesture cases repeat
+ // the minimal hook/store harness so rapid and rejected z writes cannot
+ // leak state through a shared fixture.
+ "packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.test.tsx",
+ // timelineTimingSync.test.ts: ownership, rollback, transport, and preview
+ // convergence cases deliberately keep their server stubs and assertions
+ // local; extracting the repeated arrange/act/assert shape would couple
+ // otherwise independent failure-domain regressions.
+ "packages/studio/src/hooks/timelineTimingSync.test.ts",
+ // useElementLifecycleOps.test.tsx: the reveal and atomic multi-file cases
+ // repeat a small render/persist harness to keep each transaction's setup,
+ // durable outcome, and rollback assertions visible together.
+ "packages/studio/src/hooks/useElementLifecycleOps.test.tsx",
+ // timelineClipDragCommit.test.ts: drag permutations are self-contained
+ // arrange/act/assert scenarios; the repeated clip/file fixture makes each
+ // lane and timing outcome readable without shared mutable setup.
+ "packages/studio/src/player/components/timelineClipDragCommit.test.ts",
+ // timelineZMirror.test.ts: mirror acceptance/refusal cases repeat their
+ // compact lane fixture so each z-to-lane decision remains independently
+ // understandable and cannot inherit state from another case.
+ "packages/studio/src/player/components/timelineZMirror.test.ts",
+ // gsapUndoRestore.test.ts: soft/full restore cases keep the serialized and
+ // live DOM snapshots beside their assertions; sharing those short fixtures
+ // would obscure the exact script/identity difference under test.
+ "packages/studio/src/utils/gsapUndoRestore.test.ts",
],
},
"health": {
diff --git a/packages/core/package.json b/packages/core/package.json
index c75f42d2ca..cdcba15561 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -113,6 +113,12 @@
"import": "./src/runtime/protocol.ts",
"types": "./src/runtime/protocol.ts"
},
+ "./runtime/stacking-context": {
+ "bun": "./src/runtime/stackingContext.ts",
+ "node": "./dist/runtime/stackingContext.js",
+ "import": "./src/runtime/stackingContext.ts",
+ "types": "./src/runtime/stackingContext.ts"
+ },
"./compiler/html-document": {
"bun": "./src/compiler/htmlDocument.ts",
"node": "./dist/compiler/htmlDocument.js",
@@ -317,6 +323,10 @@
"import": "./dist/runtime/protocol.js",
"types": "./dist/runtime/protocol.d.ts"
},
+ "./runtime/stacking-context": {
+ "import": "./dist/runtime/stackingContext.js",
+ "types": "./dist/runtime/stackingContext.d.ts"
+ },
"./compiler/html-document": {
"import": "./dist/compiler/htmlDocument.js",
"types": "./dist/compiler/htmlDocument.d.ts"
diff --git a/packages/core/src/runtime/stackingContext.ts b/packages/core/src/runtime/stackingContext.ts
new file mode 100644
index 0000000000..e27f77c751
--- /dev/null
+++ b/packages/core/src/runtime/stackingContext.ts
@@ -0,0 +1,108 @@
+export const ROOT_CSS_STACKING_CONTEXT_ID = "css:root";
+
+const NON_NONE_STACKING_CONTEXT_PROPERTIES = [
+ "backdrop-filter",
+ "clip-path",
+ "filter",
+ "mask",
+ "mask-border-source",
+ "mask-image",
+ "perspective",
+ "rotate",
+ "scale",
+ "transform",
+ "translate",
+ "-webkit-mask-image",
+] as const;
+const STACKING_CONTEXT_WILL_CHANGE_PROPERTIES = new Set([
+ ...NON_NONE_STACKING_CONTEXT_PROPERTIES,
+ "contain",
+ "isolation",
+ "mask-border",
+ "mix-blend-mode",
+ "opacity",
+]);
+const Z_INDEXED_POSITIONS = new Set(["absolute", "relative"]);
+const Z_INDEXED_PARENT_DISPLAYS = new Set(["flex", "inline-flex", "grid", "inline-grid"]);
+const CONTAINMENT_VALUES = new Set(["layout", "paint", "strict", "content"]);
+const STACKING_CONTAINER_TYPES = new Set(["size", "inline-size"]);
+
+function createsPositionedStackingContext(style: CSSStyleDeclaration): boolean {
+ return style.position === "fixed" || style.position === "sticky";
+}
+
+function createsZIndexedStackingContext(element: HTMLElement, style: CSSStyleDeclaration): boolean {
+ if (style.zIndex === "auto" || style.zIndex === "") return false;
+ if (Z_INDEXED_POSITIONS.has(style.position)) return true;
+ const parentDisplay = element.parentElement
+ ? element.ownerDocument.defaultView?.getComputedStyle(element.parentElement).display
+ : null;
+ return parentDisplay != null && Z_INDEXED_PARENT_DISPLAYS.has(parentDisplay);
+}
+
+function createsVisualEffectStackingContext(style: CSSStyleDeclaration): boolean {
+ const opacity = Number.parseFloat(style.opacity);
+ if (Number.isFinite(opacity) && opacity < 1) return true;
+ if (style.getPropertyValue("isolation") === "isolate") return true;
+ const mixBlendMode = style.getPropertyValue("mix-blend-mode");
+ if (mixBlendMode && mixBlendMode !== "normal") return true;
+ return NON_NONE_STACKING_CONTEXT_PROPERTIES.some((property) => {
+ const value = style.getPropertyValue(property);
+ return value !== "" && value !== "none";
+ });
+}
+
+function createsContainmentStackingContext(style: CSSStyleDeclaration): boolean {
+ const contain = style.getPropertyValue("contain").split(/\s+/);
+ if (contain.some((value) => CONTAINMENT_VALUES.has(value))) return true;
+ return STACKING_CONTAINER_TYPES.has(style.getPropertyValue("container-type"));
+}
+
+function createsWillChangeStackingContext(style: CSSStyleDeclaration): boolean {
+ return style
+ .getPropertyValue("will-change")
+ .split(",")
+ .map((property) => property.trim())
+ .some((property) => STACKING_CONTEXT_WILL_CHANGE_PROPERTIES.has(property));
+}
+
+function createsCssStackingContext(element: HTMLElement, style: CSSStyleDeclaration): boolean {
+ if (createsPositionedStackingContext(style)) return true;
+ if (createsZIndexedStackingContext(element, style)) return true;
+ if (createsVisualEffectStackingContext(style)) return true;
+ if (createsContainmentStackingContext(style)) return true;
+ return createsWillChangeStackingContext(style);
+}
+
+/** Stable within one DOM revision and unique even when authors duplicate ids. */
+function cssStackingContextPath(element: Element): string {
+ const indexes: number[] = [];
+ let cursor: Element | null = element;
+ while (cursor?.parentElement) {
+ indexes.push(Array.prototype.indexOf.call(cursor.parentElement.children, cursor));
+ cursor = cursor.parentElement;
+ }
+ return `css:${indexes.reverse().join(".")}`;
+}
+
+/**
+ * Leaf z-index participates in the nearest ANCESTOR stacking context. Exclude
+ * the leaf itself: an element that establishes a context still compares its own
+ * z-index with siblings in its parent's context.
+ */
+export function resolveCssStackingContextId(node: Element): string {
+ const win = node.ownerDocument.defaultView;
+ if (!win) return ROOT_CSS_STACKING_CONTEXT_ID;
+ let cursor = node.parentElement;
+ while (cursor && cursor !== node.ownerDocument.documentElement) {
+ try {
+ if (createsCssStackingContext(cursor, win.getComputedStyle(cursor))) {
+ return cssStackingContextPath(cursor);
+ }
+ } catch {
+ return ROOT_CSS_STACKING_CONTEXT_ID;
+ }
+ cursor = cursor.parentElement;
+ }
+ return ROOT_CSS_STACKING_CONTEXT_ID;
+}
diff --git a/packages/core/src/runtime/timeline.test.ts b/packages/core/src/runtime/timeline.test.ts
index e22c78a49f..680906d2a0 100644
--- a/packages/core/src/runtime/timeline.test.ts
+++ b/packages/core/src/runtime/timeline.test.ts
@@ -132,37 +132,119 @@ describe("collectRuntimeTimelinePayload", () => {
expect(result.clips[0].zIndex).toBe(0);
});
- it("assigns stacking context ids from root and nearest sub-composition", () => {
+ it("partitions clips by their nearest real CSS stacking context", () => {
const root = document.createElement("div");
root.setAttribute("data-composition-id", "main");
root.setAttribute("data-duration", "10");
document.body.appendChild(root);
- const rootClip = document.createElement("div");
- rootClip.id = "root-layer";
- rootClip.setAttribute("data-start", "0");
- rootClip.setAttribute("data-duration", "5");
- root.appendChild(rootClip);
+ const contextA = document.createElement("div");
+ contextA.style.transform = "translateX(0px)";
+ const contextB = document.createElement("div");
+ contextB.style.opacity = "0.9";
+ root.append(contextA, contextB);
+
+ const addClip = (parent: Element, id: string) => {
+ const clip = document.createElement("div");
+ clip.id = id;
+ clip.setAttribute("data-start", "0");
+ clip.setAttribute("data-duration", "2");
+ parent.appendChild(clip);
+ };
+ addClip(contextA, "a-1");
+ addClip(contextA, "a-2");
+ addClip(contextB, "b-1");
- const scene = document.createElement("div");
- scene.id = "scene-host";
- scene.setAttribute("data-composition-id", "scene");
- scene.setAttribute("data-start", "0");
- scene.setAttribute("data-duration", "5");
- root.appendChild(scene);
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ const contextOf = (id: string) =>
+ result.clips.find((clip) => clip.id === id)?.stackingContextId;
+
+ expect(contextOf("a-1")).toBe(contextOf("a-2"));
+ expect(contextOf("a-1")).not.toBe(contextOf("b-1"));
+ expect(contextOf("a-1")).not.toBe("css:root");
+ });
- const nestedClip = document.createElement("div");
- nestedClip.id = "nested-layer";
- nestedClip.setAttribute("data-start", "0");
- nestedClip.setAttribute("data-duration", "2");
- scene.appendChild(nestedClip);
+ it("keeps clips without a stacking-context ancestor in the shared root scope", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-duration", "10");
+ document.body.appendChild(root);
+
+ const plainWrapper = document.createElement("div");
+ root.appendChild(plainWrapper);
+ for (const [parent, id] of [
+ [root, "root-layer"],
+ [plainWrapper, "wrapped-layer"],
+ ] as const) {
+ const clip = document.createElement("div");
+ clip.id = id;
+ clip.setAttribute("data-start", "0");
+ clip.setAttribute("data-duration", "2");
+ parent.appendChild(clip);
+ }
const result = collectRuntimeTimelinePayload(defaultParams);
- const rootLayer = result.clips.find((clip) => clip.id === "root-layer");
- const nestedLayer = result.clips.find((clip) => clip.id === "nested-layer");
+ const contextOf = (id: string) =>
+ result.clips.find((clip) => clip.id === id)?.stackingContextId;
+ expect(contextOf("root-layer")).toBe("css:root");
+ expect(contextOf("wrapped-layer")).toBe("css:root");
+ });
- expect(rootLayer?.stackingContextId).toBe("main");
- expect(nestedLayer?.stackingContextId).toBe("scene");
+ it("scopes an element's own z-index in its parent context, not a context it creates", () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-duration", "10");
+ document.body.appendChild(root);
+
+ for (const id of ["layer-a", "layer-b"]) {
+ const clip = document.createElement("div");
+ clip.id = id;
+ clip.style.cssText = "position: relative; z-index: 1";
+ clip.setAttribute("data-start", "0");
+ clip.setAttribute("data-duration", "2");
+ root.appendChild(clip);
+ }
+
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ const contexts = result.clips.map((clip) => clip.stackingContextId);
+ expect(contexts).toEqual(["css:root", "css:root"]);
+ });
+
+ it.each([
+ ["positioned z-index", "", "position: relative; z-index: 1"],
+ ["fixed position", "", "position: fixed"],
+ ["sticky position", "", "position: sticky"],
+ ["transform", "", "transform: translateX(0px)"],
+ ["opacity", "", "opacity: 0.9"],
+ ["isolation", "", "isolation: isolate"],
+ ["filter", "", "filter: blur(1px)"],
+ ["perspective", "", "perspective: 100px"],
+ ["mix blend mode", "", "mix-blend-mode: multiply"],
+ ["contain", "", "contain: paint"],
+ ["container type", "", "container-type: inline-size"],
+ ["will change", "", "will-change: transform"],
+ ["z-indexed flex item", "display: flex", "z-index: 1"],
+ ["z-indexed grid item", "display: grid", "z-index: 1"],
+ ])("recognizes a %s stacking-context ancestor", (_label, rootCssText, contextCssText) => {
+ const root = document.createElement("div");
+ root.style.cssText = rootCssText;
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-duration", "10");
+ document.body.appendChild(root);
+
+ const context = document.createElement("div");
+ context.style.cssText = contextCssText;
+ root.appendChild(context);
+ const clip = document.createElement("div");
+ clip.id = "nested-layer";
+ clip.setAttribute("data-start", "0");
+ clip.setAttribute("data-duration", "2");
+ context.appendChild(clip);
+
+ const result = collectRuntimeTimelinePayload(defaultParams);
+ expect(result.clips.find((item) => item.id === clip.id)?.stackingContextId).not.toBe(
+ "css:root",
+ );
});
it("identifies video clips by tag", () => {
diff --git a/packages/core/src/runtime/timeline.ts b/packages/core/src/runtime/timeline.ts
index 23e76d4b72..6e1fa2bedc 100644
--- a/packages/core/src/runtime/timeline.ts
+++ b/packages/core/src/runtime/timeline.ts
@@ -7,6 +7,7 @@ import type {
import { stableClipId } from "./clipTree";
import { swallow } from "./diagnostics";
import { readElementPlaybackRate } from "./media";
+import { resolveCssStackingContextId } from "./stackingContext";
import { createRuntimeStartTimeResolver } from "./startResolver";
import { isSceneLikeCompositionId } from "../slideshow/index.js";
@@ -401,7 +402,7 @@ export function collectRuntimeTimelinePayload(params: {
duration,
track: parseAuthoredTrack(node, i),
zIndex: readInlineZIndex(node),
- stackingContextId: compositionContext.parentCompositionId ?? rootCompositionId,
+ stackingContextId: resolveCssStackingContextId(node),
kind,
tagName: tag,
compositionId: node.getAttribute("data-composition-id"),
@@ -510,7 +511,7 @@ export function collectRuntimeTimelinePayload(params: {
duration: clampedDuration,
track: parseAuthoredTrack(el, gsapTrack),
zIndex: readInlineZIndex(el),
- stackingContextId: rootCompositionIdForGsap,
+ stackingContextId: resolveCssStackingContextId(el),
kind: "element",
tagName: el.tagName.toLowerCase(),
compositionId: el.getAttribute("data-composition-id"),
@@ -565,7 +566,7 @@ export function collectRuntimeTimelinePayload(params: {
duration: clampedDuration,
track: parseAuthoredTrack(el, overlayTrack),
zIndex: readInlineZIndex(el),
- stackingContextId: rootCompositionIdForGsap,
+ stackingContextId: resolveCssStackingContextId(el),
kind: "element",
tagName: tag,
compositionId: el.getAttribute("data-composition-id"),
diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json
index 1e4146234b..7cb20a06c7 100644
--- a/packages/core/tsconfig.json
+++ b/packages/core/tsconfig.json
@@ -17,7 +17,8 @@
"src/runtime/clipTree.ts",
"src/runtime/mediaVolumeEnvelope.ts",
"src/runtime/positionEdits.ts",
- "src/runtime/protocol.ts"
+ "src/runtime/protocol.ts",
+ "src/runtime/stackingContext.ts"
],
"include": ["src/**/*"],
"exclude": [
diff --git a/packages/studio-server/src/routes/files.test.ts b/packages/studio-server/src/routes/files.test.ts
index 6df7cf3672..928b850809 100644
--- a/packages/studio-server/src/routes/files.test.ts
+++ b/packages/studio-server/src/routes/files.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { Hono } from "hono";
import {
existsSync,
@@ -11,12 +11,25 @@ import {
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { registerFileRoutes } from "./files";
+import { commitElementPatchBatches, registerFileRoutes } from "./files";
import type { StudioApiAdapter } from "../types";
+const recastImportGate = vi.hoisted<{
+ wait: Promise<void> | null;
+ onEnter: (() => void) | null;
+}>(() => ({ wait: null, onEnter: null }));
+
+vi.mock("@hyperframes/parsers/gsap-parser-recast", async (importOriginal) => {
+ recastImportGate.onEnter?.();
+ if (recastImportGate.wait) await recastImportGate.wait;
+ return importOriginal();
+});
+
const tempDirs: string[] = [];
afterEach(() => {
+ recastImportGate.wait = null;
+ recastImportGate.onEnter = null;
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
@@ -54,6 +67,17 @@ function postElementPatchBatch(app: Hono, file: string, patches: unknown[]): Pro
});
}
+function postElementPatchBatches(
+ app: Hono,
+ batches: Array<{ sourceFile: string; patches: unknown[] }>,
+): Promise<Response> {
+ return app.request("http://localhost/projects/demo/file-mutations/patch-element-batches", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ batches }),
+ });
+}
+
describe("registerFileRoutes", () => {
it("returns empty content for missing files when caller marks the read optional", async () => {
const projectDir = createProjectDir();
@@ -212,6 +236,148 @@ describe("registerFileRoutes", () => {
expect(existsSync(join(projectDir, ".hyperframes", "backup"))).toBe(false);
});
+ it("refuses the whole element batch when any target is unmatched", async () => {
+ const projectDir = createProjectDir();
+ const original = '<div id="present" style="z-index: 1">Present</div>';
+ writeFileSync(join(projectDir, "index.html"), original);
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+
+ const response = await postElementPatchBatch(app, "index.html", [
+ {
+ target: { id: "present" },
+ operations: [{ type: "inline-style", property: "z-index", value: "2" }],
+ },
+ {
+ target: { id: "missing" },
+ operations: [{ type: "inline-style", property: "z-index", value: "3" }],
+ },
+ ]);
+ const payload = (await response.json()) as {
+ changed?: boolean;
+ matched?: boolean[];
+ content?: string;
+ backupPath?: string;
+ };
+
+ expect(payload).toMatchObject({ changed: false, matched: [true, false], content: original });
+ expect(payload.backupPath).toBeUndefined();
+ expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toBe(original);
+ expect(existsSync(join(projectDir, ".hyperframes", "backup"))).toBe(false);
+ });
+
+ it("refuses every file when one batch contains an unmatched target", async () => {
+ const projectDir = createProjectDir();
+ const indexOriginal = '<div id="present" style="z-index: 1">Present</div>';
+ const sceneOriginal = '<div id="scene" style="z-index: 1">Scene</div>';
+ writeFileSync(join(projectDir, "index.html"), indexOriginal);
+ writeFileSync(join(projectDir, "scene.html"), sceneOriginal);
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+
+ const response = await postElementPatchBatches(app, [
+ {
+ sourceFile: "index.html",
+ patches: [
+ {
+ target: { id: "present" },
+ operations: [{ type: "inline-style", property: "z-index", value: "2" }],
+ },
+ ],
+ },
+ {
+ sourceFile: "scene.html",
+ patches: [
+ {
+ target: { id: "missing" },
+ operations: [{ type: "inline-style", property: "z-index", value: "3" }],
+ },
+ ],
+ },
+ ]);
+ const payload = (await response.json()) as {
+ durable?: boolean;
+ files?: Array<{
+ sourceFile?: string;
+ changed?: boolean;
+ matched?: boolean[];
+ before?: string;
+ after?: string;
+ }>;
+ };
+
+ expect(response.status).toBe(200);
+ expect(payload).toEqual({
+ durable: false,
+ files: [
+ {
+ sourceFile: "index.html",
+ changed: false,
+ matched: [true],
+ before: indexOriginal,
+ after: indexOriginal,
+ },
+ {
+ sourceFile: "scene.html",
+ changed: false,
+ matched: [false],
+ before: sceneOriginal,
+ after: sceneOriginal,
+ },
+ ],
+ });
+ expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toBe(indexOriginal);
+ expect(readFileSync(join(projectDir, "scene.html"), "utf-8")).toBe(sceneOriginal);
+ expect(existsSync(join(projectDir, ".hyperframes", "backup"))).toBe(false);
+ });
+
+ it("restores earlier files when a later atomic batch write fails", () => {
+ const projectDir = createProjectDir();
+ const indexOriginal = '<div id="index" style="z-index: 1">Index</div>';
+ const sceneOriginal = '<div id="scene" style="z-index: 1">Scene</div>';
+ const indexPath = join(projectDir, "index.html");
+ const scenePath = join(projectDir, "scene.html");
+ writeFileSync(indexPath, indexOriginal);
+ writeFileSync(scenePath, sceneOriginal);
+ let remainingFailures = 1;
+ const writeFile = (path: string, content: string, encoding: "utf-8") => {
+ if (path === scenePath && remainingFailures > 0) {
+ remainingFailures -= 1;
+ throw new Error("forced write failure");
+ }
+ writeFileSync(path, content, encoding);
+ };
+
+ expect(() =>
+ commitElementPatchBatches(
+ projectDir,
+ [
+ {
+ sourceFile: "index.html",
+ patches: [
+ {
+ target: { id: "index" },
+ operations: [{ type: "inline-style", property: "z-index", value: "2" }],
+ },
+ ],
+ },
+ {
+ sourceFile: "scene.html",
+ patches: [
+ {
+ target: { id: "scene" },
+ operations: [{ type: "inline-style", property: "z-index", value: "3" }],
+ },
+ ],
+ },
+ ],
+ writeFile,
+ ),
+ ).toThrow("forced write failure");
+ expect(readFileSync(indexPath, "utf-8")).toBe(indexOriginal);
+ expect(readFileSync(scenePath, "utf-8")).toBe(sceneOriginal);
+ });
+
it("rejects an unsafe value anywhere in an element patch batch without writing", async () => {
const projectDir = createProjectDir();
const original = '<div id="first">First</div><div id="second">Second</div>';
@@ -319,6 +485,57 @@ tl.fromTo("#box", { opacity: 0, x: -50 }, { opacity: 1, x: 0, duration: 1.5, eas
});
}
+ function postGsapRollback(
+ app: Hono,
+ file: string,
+ expected: string,
+ restore: string,
+ ): Promise<Response> {
+ return app.request(`http://localhost/projects/demo/gsap-mutation-rollback/${file}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ expected, restore }),
+ });
+ }
+
+ it("advertises atomic GSAP ownership before clients mutate", async () => {
+ const projectDir = createProjectDir();
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+
+ const response = await app.request("http://localhost/projects/demo/gsap-mutation-capabilities");
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ atomicOwnershipPairs: true });
+ });
+
+ it("rejects a stale semantic no-op after a concurrent file write", async () => {
+ const projectDir = createProjectDir();
+ writeHtml(projectDir, "comp.html", FROMTO_COMP);
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+ const successor = FROMTO_COMP.replace('data-duration="3"', 'data-duration="9"');
+ let releaseImport = () => {};
+ recastImportGate.wait = new Promise<void>((resolve) => {
+ releaseImport = resolve;
+ });
+ const parserEntered = new Promise<void>((resolve) => {
+ recastImportGate.onEnter = resolve;
+ });
+
+ const pending = postGsapMutationBatch(app, "comp.html", {
+ mutations: [{ type: "shift-positions", targetSelector: "#missing", delta: 1 }],
+ });
+ await parserEntered;
+ writeHtml(projectDir, "comp.html", successor);
+ releaseImport();
+ const response = await pending;
+
+ expect(response.status).toBe(409);
+ expect(await response.json()).toMatchObject({ conflict: true });
+ expect(readFileSync(join(projectDir, "comp.html"), "utf-8")).toBe(successor);
+ });
+
it("applies an ordered GSAP mutation batch with one before/after write result", async () => {
const projectDir = createProjectDir();
writeHtml(projectDir, "comp.html", FROMTO_COMP);
@@ -360,6 +577,34 @@ tl.fromTo("#box", { opacity: 0, x: -50 }, { opacity: 1, x: 0, duration: 1.5, eas
expect(result.parsed.animations[0].fromProperties).toMatchObject({ opacity: 0.2, x: -25 });
});
+ it("conditionally restores the exact GSAP mutation output", async () => {
+ const projectDir = createProjectDir();
+ writeHtml(projectDir, "comp.html", "MUTATED");
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+
+ const response = await postGsapRollback(app, "comp.html", "MUTATED", "BEFORE");
+ const result = (await response.json()) as { restored: boolean; conflict: boolean };
+
+ expect(response.status).toBe(200);
+ expect(result).toMatchObject({ restored: true, conflict: false });
+ expect(readFileSync(join(projectDir, "comp.html"), "utf-8")).toBe("BEFORE");
+ });
+
+ it("reports a rollback conflict and preserves a successor write", async () => {
+ const projectDir = createProjectDir();
+ writeHtml(projectDir, "comp.html", "SUCCESSOR");
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+
+ const response = await postGsapRollback(app, "comp.html", "MUTATED", "BEFORE");
+ const result = (await response.json()) as { restored: boolean; conflict: boolean };
+
+ expect(response.status).toBe(200);
+ expect(result).toMatchObject({ restored: false, conflict: true });
+ expect(readFileSync(join(projectDir, "comp.html"), "utf-8")).toBe("SUCCESSOR");
+ });
+
it.each(["first", "middle", "last"] as const)(
"rejects an invalid %s mutation without writing any part of the batch",
async (position) => {
diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts
index 8aceab9aa7..9098891dcb 100644
--- a/packages/studio-server/src/routes/files.ts
+++ b/packages/studio-server/src/routes/files.ts
@@ -166,6 +166,50 @@ interface ElementPatchRequest {
operations: PatchOperation[];
}
+interface ElementPatchBatchRequest {
+ sourceFile: string;
+ patches: ElementPatchRequest[];
+}
+
+interface ElementPatchBatchFileResult {
+ sourceFile: string;
+ changed: boolean;
+ matched: boolean[];
+ before: string;
+ after: string;
+ backupPath?: string | null;
+}
+
+function isElementPatchRequest(value: unknown): value is ElementPatchRequest {
+ if (typeof value !== "object" || value === null) return false;
+ if (!("target" in value) || typeof value.target !== "object" || value.target === null) {
+ return false;
+ }
+ return "operations" in value && Array.isArray(value.operations) && value.operations.length > 0;
+}
+
+function isElementPatchBatchRequest(value: unknown): value is ElementPatchBatchRequest {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ "sourceFile" in value &&
+ typeof value.sourceFile === "string" &&
+ value.sourceFile.length > 0 &&
+ "patches" in value &&
+ Array.isArray(value.patches) &&
+ value.patches.length > 0 &&
+ value.patches.every(isElementPatchRequest)
+ );
+}
+
+function findUnsafeElementPatchBatchValues(
+ batches: readonly ElementPatchBatchRequest[],
+): UnsafeMutationValue[] {
+ return batches.flatMap((batch) =>
+ batch.patches.flatMap((patch) => findUnsafeDomPatchValues(patch)),
+ );
+}
+
function foldElementPatches(
originalContent: string,
patches: ElementPatchRequest[],
@@ -180,6 +224,113 @@ function foldElementPatches(
return { content, matched };
}
+/**
+ * The single commit owner for element patch batches. All files are resolved,
+ * read, and folded before the first write; any unmatched target refuses the
+ * whole request. The final snapshots/writes are synchronous, so another route
+ * cannot interleave once the commit section begins.
+ */
+export function commitElementPatchBatches(
+ projectDir: string,
+ batches: ElementPatchBatchRequest[],
+ writeFile: (path: string, content: string, encoding: "utf-8") => void = writeFileSync,
+):
+ | { error: "duplicate" | "forbidden" | "not-found"; sourceFile: string }
+ | { durable: boolean; files: ElementPatchBatchFileResult[] } {
+ const resolvedPaths = new Set<string>();
+ const prepared: Array<{
+ sourceFile: string;
+ absPath: string;
+ before: string;
+ matched: boolean[];
+ after: string;
+ }> = [];
+
+ for (const batch of batches) {
+ const absPath = resolveWithinProject(projectDir, batch.sourceFile);
+ if (!absPath) return { error: "forbidden", sourceFile: batch.sourceFile };
+ if (resolvedPaths.has(absPath)) return { error: "duplicate", sourceFile: batch.sourceFile };
+ resolvedPaths.add(absPath);
+
+ let before: string;
+ try {
+ before = readFileSync(absPath, "utf-8");
+ } catch {
+ return { error: "not-found", sourceFile: batch.sourceFile };
+ }
+ const folded = foldElementPatches(before, batch.patches);
+ prepared.push({
+ sourceFile: batch.sourceFile,
+ absPath,
+ before,
+ matched: folded.matched,
+ after: folded.content,
+ });
+ }
+
+ const durable = prepared.every((file) => file.matched.every(Boolean));
+ if (!durable) {
+ return {
+ durable: false,
+ files: prepared.map((file) => ({
+ sourceFile: file.sourceFile,
+ changed: false,
+ matched: file.matched,
+ before: file.before,
+ after: file.before,
+ })),
+ };
+ }
+
+ const files: ElementPatchBatchFileResult[] = [];
+ const attemptedWrites: typeof prepared = [];
+ try {
+ for (const file of prepared) {
+ if (file.after === file.before) {
+ files.push({
+ sourceFile: file.sourceFile,
+ changed: false,
+ matched: file.matched,
+ before: file.before,
+ after: file.before,
+ });
+ continue;
+ }
+ const backup = snapshotBeforeWrite(projectDir, file.absPath);
+ if (backup.error) {
+ throw new Error(`Failed to create backup for ${file.sourceFile}: ${backup.error}`);
+ }
+ attemptedWrites.push(file);
+ writeFile(file.absPath, file.after, "utf-8");
+ files.push({
+ sourceFile: file.sourceFile,
+ changed: true,
+ matched: file.matched,
+ before: file.before,
+ after: file.after,
+ backupPath: backupPathForResponse(projectDir, backup.backupPath),
+ });
+ }
+ } catch (error) {
+ const rollbackErrors: unknown[] = [];
+ for (const file of attemptedWrites.reverse()) {
+ try {
+ writeFile(file.absPath, file.before, "utf-8");
+ } catch (rollbackError) {
+ rollbackErrors.push(rollbackError);
+ }
+ }
+ if (rollbackErrors.length > 0) {
+ throw new AggregateError(
+ [error, ...rollbackErrors],
+ "Element patch batch failed and rollback did not complete",
+ );
+ }
+ throw error;
+ }
+ return { durable: true, files };
+}
+
/** Write `next` to `absPath` only if it differs from `original`, returning a standardized change response. */
function writeIfChanged(
c: RouteContext,
@@ -218,6 +369,16 @@ function rejectUnsafeMutationValues(
);
}
+function elementPatchBatchCommitErrorResponse(
+ c: RouteContext,
+ error: "duplicate" | "forbidden" | "not-found",
+ sourceFile: string,
+): Response {
+ if (error === "not-found") return c.json({ error, sourceFile }, 404);
+ if (error === "forbidden") return c.json({ error, sourceFile }, 403);
+ return c.json({ error: "duplicate source file", sourceFile }, 400);
+}
+
/**
* Parse the request body and validate that `target` is present.
* Returns `{ error }` if missing, or `{ target, body }` for the full parsed body.
@@ -895,10 +1056,12 @@ async function prepareGsapMutationScript(
| Response
| {
html: string;
+ beforeHtml: string;
block: NonNullable<ReturnType<typeof extractGsapScriptBlock>>;
}
> {
- let html = readFileSync(res.absPath, "utf-8");
+ const beforeHtml = readFileSync(res.absPath, "utf-8");
+ let html = beforeHtml;
let block = extractGsapScriptBlock(html);
if (!block && (firstMutation.type === "add" || firstMutation.type === "add-with-keyframes")) {
const compId = html.match(/data-composition-id="([^"]+)"/)?.[1] ?? "main";
@@ -935,7 +1098,7 @@ async function prepareGsapMutationScript(
});
}
if (!block) return c.json({ error: "no GSAP script found in file" }, 400);
- return { html, block };
+ return { html, beforeHtml, block };
}
async function applyGsapMutations(
@@ -947,7 +1110,7 @@ async function applyGsapMutations(
if (!firstMutation) return c.json({ error: "mutations array required" }, 400);
const prepared = await prepareGsapMutationScript(c, res, firstMutation);
if (prepared instanceof Response) return prepared;
- const { html, block } = prepared;
+ const { html, beforeHtml, block } = prepared;
const initialScript = block.scriptText;
const skippedSelectors = new Set<string>();
@@ -971,6 +1134,12 @@ async function applyGsapMutations(
const changed = block.scriptText !== initialScript;
const newHtml = changed ? block.replaceScript(block.scriptText) : html;
let backupPath: string | null = null;
+ // Parsing can await lazy imports. Revalidate before EVERY successful response,
+ // including semantic no-ops: a stale no-op response would otherwise claim
+ // the old bytes and let the client keep a preview that missed a successor.
+ if (readFileSync(res.absPath, "utf-8") !== beforeHtml) {
+ return c.json({ error: "file changed during GSAP mutation", conflict: true }, 409);
+ }
if (changed) {
const backup = snapshotBeforeWrite(res.project.dir, res.absPath);
if (backup.error) console.warn(`Failed to create backup for ${res.filePath}: ${backup.error}`);
@@ -983,7 +1152,7 @@ async function applyGsapMutations(
changed,
mutated: changed,
parsed: parseGsapScriptAcorn(block.scriptText),
- before: html,
+ before: beforeHtml,
after: newHtml,
scriptText: block.scriptText,
path: res.filePath,
@@ -1950,6 +2119,31 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
});
});
+ api.post("/projects/:id/file-mutations/patch-element-batches", async (c) => {
+ const project = await adapter.resolveProject(c.req.param("id"));
+ if (!project) return c.json({ error: "not found" }, 404);
+
+ const body: unknown = await c.req.json().catch(() => null);
+ if (
+ typeof body !== "object" ||
+ body === null ||
+ !("batches" in body) ||
+ !Array.isArray(body.batches) ||
+ body.batches.length === 0 ||
+ !body.batches.every(isElementPatchBatchRequest)
+ ) {
+ return c.json({ error: "batches with sourceFile and patches required" }, 400);
+ }
+ const unsafeFields = findUnsafeElementPatchBatchValues(body.batches);
+ if (unsafeFields.length > 0) return rejectUnsafeMutationValues(c, unsafeFields);
+
+ const result = commitElementPatchBatches(project.dir, body.batches);
+ if ("error" in result) {
+ return elementPatchBatchCommitErrorResponse(c, result.error, result.sourceFile);
+ }
+ return c.json(result);
+ });
+
api.post("/projects/:id/file-mutations/patch-elements-batch/*", async (c) => {
const ctx = await resolveFileMutationContext(c, adapter, "patch-elements-batch");
if ("error" in ctx) return ctx.error;
@@ -1961,44 +2155,29 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
!body ||
!Array.isArray(body.patches) ||
body.patches.length === 0 ||
- body.patches.some(
- (patch) =>
- !patch?.target || !Array.isArray(patch.operations) || patch.operations.length === 0,
- )
+ !body.patches.every(isElementPatchRequest)
) {
return c.json({ error: "patches with target and operations required" }, 400);
}
- const unsafeFields = body.patches.flatMap((patch) => findUnsafeDomPatchValues(patch));
+ const batch = { sourceFile: ctx.filePath, patches: body.patches };
+ const unsafeFields = findUnsafeElementPatchBatchValues([batch]);
if (unsafeFields.length > 0) {
return rejectUnsafeMutationValues(c, unsafeFields);
}
- let originalContent: string;
- try {
- originalContent = readFileSync(ctx.absPath, "utf-8");
- } catch {
- return c.json({ error: "not found" }, 404);
+ const result = commitElementPatchBatches(ctx.project.dir, [batch]);
+ if ("error" in result) {
+ return elementPatchBatchCommitErrorResponse(c, result.error, result.sourceFile);
}
- const result = foldElementPatches(originalContent, body.patches);
- if (result.content === originalContent) {
- return c.json({
- ok: true,
- changed: false,
- matched: result.matched,
- content: originalContent,
- path: ctx.filePath,
- });
- }
- const backup = snapshotBeforeWrite(ctx.project.dir, ctx.absPath);
- if (backup.error) console.warn(`Failed to create backup for ${ctx.filePath}: ${backup.error}`);
- writeFileSync(ctx.absPath, result.content, "utf-8");
+ const file = result.files[0];
+ if (!file) return c.json({ error: "empty element patch result" }, 500);
return c.json({
ok: true,
- changed: true,
- matched: result.matched,
- content: result.content,
- path: ctx.filePath,
- backupPath: backupPathForResponse(ctx.project.dir, backup.backupPath),
+ changed: file.changed,
+ matched: file.matched,
+ content: file.after,
+ path: file.sourceFile,
+ backupPath: file.backupPath,
});
});
@@ -2236,6 +2415,12 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
// ── GSAP Mutations ──
+ api.get("/projects/:id/gsap-mutation-capabilities", async (c) => {
+ const project = await adapter.resolveProject(c.req.param("id"));
+ if (!project) return c.json({ error: "not found" }, 404);
+ return c.json({ atomicOwnershipPairs: true });
+ });
+
api.post("/projects/:id/gsap-mutations/*", async (c) => {
const res = await resolveProjectPath(c, adapter, (id) => `/projects/${id}/gsap-mutations/`, {
mustExist: true,
@@ -2270,4 +2455,32 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
}
return applyGsapMutations(c, res, body.mutations);
});
+
+ // A failed multi-step GSAP transaction may restore only the exact bytes its
+ // mutation wrote. Keep compare + write in this synchronous server section so
+ // another request cannot land between a client-side check and the restore.
+ api.post("/projects/:id/gsap-mutation-rollback/*", async (c) => {
+ const res = await resolveProjectPath(
+ c,
+ adapter,
+ (id) => `/projects/${id}/gsap-mutation-rollback/`,
+ { mustExist: true },
+ );
+ if ("error" in res) return res.error;
+
+ const body = (await c.req.json().catch(() => null)) as {
+ expected?: unknown;
+ restore?: unknown;
+ } | null;
+ if (!body || typeof body.expected !== "string" || typeof body.restore !== "string") {
+ return c.json({ error: "expected and restore contents required" }, 400);
+ }
+
+ const current = readFileSync(res.absPath, "utf-8");
+ if (current !== body.expected) {
+ return c.json({ ok: true, restored: false, conflict: true });
+ }
+ writeFileSync(res.absPath, body.restore, "utf-8");
+ return c.json({ ok: true, restored: true, conflict: false });
+ });
}
diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsx
index 4cb09db319..52048298fb 100644
--- a/packages/studio/src/App.tsx
+++ b/packages/studio/src/App.tsx
@@ -189,10 +189,10 @@ export function StudioApp() {
}>,
coalesceKey?: string,
operation: TimelineMoveOperation = "timing",
+ coalesceMs?: number,
) => {
- await persistTimelineMoveEditsAtomically(edits, coalesceKey, operation, {
- handleTimelineGroupMove: timelineEditing.handleTimelineGroupMove,
- });
+ const deps = { handleTimelineGroupMove: timelineEditing.handleTimelineGroupMove };
+ await persistTimelineMoveEditsAtomically(edits, coalesceKey, operation, deps, coalesceMs);
},
[timelineEditing.handleTimelineGroupMove],
);
diff --git a/packages/studio/src/components/editor/CanvasContextMenu.test.tsx b/packages/studio/src/components/editor/CanvasContextMenu.test.tsx
index 57a093e81b..0fd9b6d21b 100644
--- a/packages/studio/src/components/editor/CanvasContextMenu.test.tsx
+++ b/packages/studio/src/components/editor/CanvasContextMenu.test.tsx
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { installReactActEnvironment, makeSelection } from "../../hooks/domSelectionTestHarness";
import { resolveZIndexEntries } from "../nle/PreviewOverlays";
import { useElementLifecycleOps } from "../../hooks/useElementLifecycleOps";
+import { makeLifecycleOpsParams } from "../../hooks/elementLifecycleOpsTestUtils";
import type { DomEditPatchBatch } from "../../hooks/domEditCommitTypes";
import { CanvasContextMenu } from "./CanvasContextMenu";
import type { ZOrderAction, ZOrderPatch } from "./canvasContextMenuZOrder";
@@ -102,9 +103,26 @@ describe("CanvasContextMenu — handler gating", () => {
renderMenu({ selection: makeSelection("Target", el), onApplyZIndex: vi.fn() });
- expect(zOrderButtons()).toHaveLength(4);
+ const buttons = zOrderButtons();
+ expect(buttons).toHaveLength(4);
expect(hasDeleteItem()).toBe(false);
expect(document.body.querySelector(".border-t")).toBeNull();
+
+ // Labels stay the exact industry-standard names (the icons add no text)...
+ expect(buttons.map((b) => b.textContent)).toEqual([
+ "Bring to front",
+ "Bring forward",
+ "Send backward",
+ "Send to back",
+ ]);
+ // ...and each item leads with a stroke icon that inherits the item's text
+ // color (currentColor), so the disabled muted tone applies to it too.
+ for (const button of buttons) {
+ const svg = button.firstElementChild;
+ expect(svg?.tagName.toLowerCase()).toBe("svg");
+ expect(svg?.getAttribute("stroke")).toBe("currentColor");
+ expect(svg?.getAttribute("aria-hidden")).toBe("true");
+ }
});
it("shows only Delete (no z-order items, no divider) when onApplyZIndex is absent", () => {
@@ -158,19 +176,14 @@ function renderCommitHook(captured: CapturedBatchCall[]) {
type Commit = ReturnType<typeof useElementLifecycleOps>["handleDomZIndexReorderCommit"];
let commit: Commit | undefined;
function Harness() {
- ({ handleDomZIndexReorderCommit: commit } = useElementLifecycleOps({
- activeCompPath: "index.html",
- showToast: vi.fn(),
- writeProjectFile: vi.fn(async () => {}),
- domEditSaveTimestampRef: { current: 0 },
- editHistory: { recordEdit: vi.fn(async () => {}) },
- projectIdRef: { current: null },
- reloadPreview: vi.fn(),
- clearDomSelection: vi.fn(),
- commitDomEditPatchBatches: async (batches, options) => {
- captured.push({ batches, options });
- },
- }));
+ ({ handleDomZIndexReorderCommit: commit } = useElementLifecycleOps(
+ makeLifecycleOpsParams({
+ commitDomEditPatchBatches: async (batches, options) => {
+ captured.push({ batches, options });
+ return { durable: true, allMatched: true, changed: true };
+ },
+ }),
+ ));
return null;
}
const hookHost = document.createElement("div");
diff --git a/packages/studio/src/components/editor/CanvasContextMenu.tsx b/packages/studio/src/components/editor/CanvasContextMenu.tsx
index cf06d95487..0fae550544 100644
--- a/packages/studio/src/components/editor/CanvasContextMenu.tsx
+++ b/packages/studio/src/components/editor/CanvasContextMenu.tsx
@@ -50,8 +50,17 @@ interface CanvasContextMenuProps {
* affected siblings). The menu does NOT touch the live DOM — wire to
* handleDomZIndexReorderCommit, which applies the live styles itself
* (see module-level wiring comment).
+ *
+ * `crossed` is the sibling a forward/backward step moved past, resolved from
+ * the SAME pre-mutation render order as the patches (null for front/back or
+ * when there is no neighbor). The host uses it to mirror the z action into a
+ * timeline lane move (resolveZMirrorLaneMove's crossedKey).
*/
- onApplyZIndex?: (patches: ZOrderPatch[], action: ZOrderAction) => void;
+ onApplyZIndex?: (
+ patches: ZOrderPatch[],
+ action: ZOrderAction,
+ crossed: HTMLElement | null,
+ ) => void;
/**
* Called after a successful bring-forward / send-backward with the sibling
* the target stepped over (resolved from the SAME pre-mutation state as the
@@ -70,10 +79,61 @@ interface CanvasContextMenuProps {
type ZAction = "bring-forward" | "send-backward" | "bring-to-front" | "send-to-back";
+// Stacked-layer + arrow glyphs, one per z action (16px, stroke, currentColor —
+// matches the studio's inline-SVG conventions: fill="none", 1.2 stroke, round
+// caps/joins). Single actions show ONE layer diamond with the arrow stepping
+// one way; front/back show a TWO-diamond stack with the arrow piercing through
+// and beyond it. `paths` are the d attributes, drawn in order.
+const Z_ACTION_ICONS: Record<ZAction, string[]> = {
+ "bring-forward": [
+ "M3 11 L8 8.5 L13 11 L8 13.5 Z", // layer diamond (bottom)
+ "M8 8.5 L8 2", // arrow shaft up
+ "M5.5 4.5 L8 2 L10.5 4.5", // arrow head
+ ],
+ "send-backward": [
+ "M3 5 L8 2.5 L13 5 L8 7.5 Z", // layer diamond (top)
+ "M8 7.5 L8 14", // arrow shaft down
+ "M5.5 11.5 L8 14 L10.5 11.5", // arrow head
+ ],
+ "bring-to-front": [
+ "M3 9.5 L8 7 L13 9.5 L8 12 Z", // upper layer of the stack
+ "M3 12.5 L8 10 L13 12.5 L8 15 Z", // lower layer of the stack
+ "M8 12.5 L8 2", // arrow piercing up through/above the stack
+ "M5.5 4.5 L8 2 L10.5 4.5", // arrow head
+ ],
+ "send-to-back": [
+ "M3 4 L8 1.5 L13 4 L8 6.5 Z", // upper layer of the stack
+ "M3 7 L8 4.5 L13 7 L8 9.5 Z", // lower layer of the stack
+ "M8 3.5 L8 14", // arrow piercing down through/below the stack
+ "M5.5 11.5 L8 14 L10.5 11.5", // arrow head
+ ],
+};
+
+function ZActionIcon({ action }: { action: ZAction }) {
+ return (
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 16 16"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="mr-2 shrink-0"
+ aria-hidden="true"
+ >
+ {Z_ACTION_ICONS[action].map((d) => (
+ <path key={d} d={d} />
+ ))}
+ </svg>
+ );
+}
+
const Z_ACTIONS: Array<{ action: ZAction; label: string }> = [
+ { action: "bring-to-front", label: "Bring to front" },
{ action: "bring-forward", label: "Bring forward" },
{ action: "send-backward", label: "Send backward" },
- { action: "bring-to-front", label: "Bring to front" },
{ action: "send-to-back", label: "Send to back" },
];
@@ -113,14 +173,16 @@ export const CanvasContextMenu = memo(function CanvasContextMenu({
const patches = resolveZOrderChange(el, action);
if (patches === null) return;
// Resolve the crossed neighbor BEFORE the commit path mutates live styles —
- // both resolvers must read the same pre-change render order.
- const crossed = onZOrderCrossed ? resolveCrossedNeighbor(el, action) : null;
+ // both resolvers must read the same pre-change render order. Always resolved
+ // (not only for the flash): onApplyZIndex forwards it so the host can mirror
+ // the z step into a timeline lane move.
+ const crossed = resolveCrossedNeighbor(el, action);
// Do NOT pre-apply styles here: handleDomZIndexReorderCommit writes the
// live z-index (and injects position:relative for static elements) in the
// same synchronous flow, so feedback is still instant — and it must read
// the PRE-change styles itself, both to capture true rollback values and
// to detect a static position that needs persisting.
- onApplyZIndex(patches, action);
+ onApplyZIndex(patches, action, crossed);
if (crossed && onZOrderCrossed) onZOrderCrossed(crossed, action);
onClose();
}
@@ -185,7 +247,10 @@ export const CanvasContextMenu = memo(function CanvasContextMenu({
if (enabled) handleZAction(action);
}}
>
- {label}
+ {/* Icon inherits the item's text color via currentColor, so the
+ disabled muted tone applies to both icon and label. */}
+ <ZActionIcon action={action} />
+ <span>{label}</span>
</button>
);
})}
diff --git a/packages/studio/src/components/editor/DomEditOverlay.tsx b/packages/studio/src/components/editor/DomEditOverlay.tsx
index 18bfe32c17..2c6d6add3c 100644
--- a/packages/studio/src/components/editor/DomEditOverlay.tsx
+++ b/packages/studio/src/components/editor/DomEditOverlay.tsx
@@ -103,6 +103,9 @@ interface DomEditOverlayProps {
selection: DomEditSelection,
patches: ZOrderPatch[],
action: ZOrderAction,
+ /** Sibling a forward/backward step moved past (pre-mutation render order);
+ * null for front/back. Feeds the timeline z-mirror's crossedKey. */
+ crossed: HTMLElement | null,
) => void;
}
@@ -529,8 +532,8 @@ export const DomEditOverlay = memo(function DomEditOverlay({
}
onApplyZIndex={
onApplyZIndex
- ? (patches, action) => {
- onApplyZIndex(contextMenu.sel, patches, action);
+ ? (patches, action, crossed) => {
+ onApplyZIndex(contextMenu.sel, patches, action, crossed);
}
: undefined
}
diff --git a/packages/studio/src/components/editor/LayersPanel.tsx b/packages/studio/src/components/editor/LayersPanel.tsx
index 2c2ae25cd3..ca215d1d75 100644
--- a/packages/studio/src/components/editor/LayersPanel.tsx
+++ b/packages/studio/src/components/editor/LayersPanel.tsx
@@ -14,8 +14,14 @@ import {
} from "../../utils/studioHelpers";
import { Layers } from "../../icons/SystemIcons";
import { useLayerDrag, isLayerDraggable, type LayerReorderEvent } from "./useLayerDrag";
-import { computeReorderZValues, getElementZIndex } from "../../player/lib/layerOrdering";
+import { getVisibleLayers, sortLayersByZIndex } from "./layersPanelSort";
import { deriveTimelineStoreKey } from "../../player/lib/timelineElementHelpers";
+import { resolveZOrderReposition } from "./canvasContextMenuZOrder";
+import { buildStableSelector } from "./domEditingDom";
+import { zReorderCoalesceKey } from "../../hooks/useElementLifecycleOps";
+import { useLayerReorderTimelineMirror } from "../nle/useCanvasZOrderTimelineMirror";
+import { runZLaneGesture } from "../nle/zLaneGesture";
+import { useLayerRevealOverride } from "./useLayerRevealOverride";
const TAG_ICONS: Record<string, string> = {
video: "Vi",
@@ -85,8 +91,13 @@ interface CollapsedState {
// fallow-ignore-next-line complexity
export const LayersPanel = memo(function LayersPanel() {
const { previewIframeRef, activeCompPath, showToast } = useStudioShellContext();
- const { refreshKey, compositionLoading, timelineElements } = useStudioPlaybackContext();
+ const { refreshKey, compositionLoading, timelineElements, isPlaying } =
+ useStudioPlaybackContext();
const currentTime = usePlayerStore((s) => s.currentTime);
+ // Flashless z commits (canvas menu, timeline lane-drag z-sync) mutate iframe
+ // z-indexes with no reload and no refreshKey bump — while paused, nothing
+ // else re-collects, so the panel's z-sorted order would go stale.
+ const zEditVersion = usePlayerStore((s) => s.zEditVersion);
const {
domEditSelection,
activeGroupElement,
@@ -100,6 +111,11 @@ export const LayersPanel = memo(function LayersPanel() {
const [collapsed, setCollapsed] = useState<CollapsedState>({});
const prevDocVersionRef = useRef(0);
const scrollContainerRef = useRef<HTMLDivElement>(null);
+ const mirrorLayerReorderToTimeline = useLayerReorderTimelineMirror();
+ const { scheduleReveal } = useLayerRevealOverride({
+ isPlaying,
+ selectedElement: domEditSelection?.element ?? null,
+ });
const isMasterView = !activeCompPath || activeCompPath === "index.html";
@@ -131,7 +147,7 @@ export const LayersPanel = memo(function LayersPanel() {
useEffect(() => {
collectLayers();
- }, [collectLayers, refreshKey]);
+ }, [collectLayers, refreshKey, zEditVersion]);
useEffect(() => {
const iframe = previewIframeRef.current;
@@ -230,8 +246,13 @@ export const LayersPanel = memo(function LayersPanel() {
if (!selection) return;
applyDomSelection(selection);
await seekToLayer(layer);
+ // Force-reveal AFTER the seek's runtime visibility sync has had a beat:
+ // a clip made active by the seek shows naturally and needs no override,
+ // so the reveal only touches nodes that REMAIN hidden (animation-parked
+ // opacity, non-clip display/visibility hides, hidden ancestors).
+ scheduleReveal(selection.element, 150);
},
- [resolveSelection, applyDomSelection, seekToLayer],
+ [resolveSelection, applyDomSelection, seekToLayer, scheduleReveal],
);
// Double-click a group row → drill into it; any other row → select it.
@@ -264,6 +285,7 @@ export const LayersPanel = memo(function LayersPanel() {
setCollapsed((prev) => ({ ...prev, [key]: !prev[key] }));
}, []);
+ // fallow-ignore-next-line complexity
const handleReorder = useCallback(
(event: LayerReorderEvent) => {
const { siblingLayers, fromIndex, toIndex } = event;
@@ -271,29 +293,88 @@ export const LayersPanel = memo(function LayersPanel() {
const [moved] = reordered.splice(fromIndex, 1);
reordered.splice(toIndex, 0, moved);
- const existingValues = siblingLayers.map((l) => getElementZIndex(l.element));
- const zValues = computeReorderZValues(existingValues, fromIndex, toIndex);
-
- const entries = reordered.map((layer, i) => ({
- element: layer.element,
- zIndex: zValues[i],
- id: layer.id,
- selector: layer.selector,
- selectorIndex: layer.selectorIndex,
- sourceFile: layer.sourceFile,
- key: deriveTimelineStoreKey({
- domId: layer.id,
- selector: layer.selector,
- selectorIndex: layer.selectorIndex,
- sourceFile: layer.sourceFile,
- }),
- }));
-
- // "layer-drag" keeps consecutive drops of the same sibling set coalescing
- // into one undo step, without merging with a context-menu z action.
- handleDomZIndexReorderCommit(entries, undefined, "layer-drag");
+ // Panel order is top-first (sortLayersByZIndex: z desc, later-DOM-first),
+ // so the desired RENDER order (bottom→top) is the reverse. The minimal
+ // resolver (shared with the canvas z-menu) then writes one between-z
+ // value when a strict gap exists, band-safe renumber otherwise — instead
+ // of the old computeReorderZValues stamp of every sibling.
+ const desiredBottomToTop = [...reordered].reverse();
+ const patches = resolveZOrderReposition(
+ moved.element,
+ desiredBottomToTop.map((l) => l.element),
+ );
+ if (!patches || patches.length === 0) return; // paint order unchanged
+
+ const layerByElement = new Map(siblingLayers.map((l) => [l.element, l]));
+ const entries: Array<{
+ element: HTMLElement;
+ zIndex: number;
+ id?: string;
+ selector?: string;
+ selectorIndex?: number;
+ sourceFile: string;
+ key?: string;
+ }> = [];
+ for (const patch of patches) {
+ // The renumber fallback can patch a painting sibling the panel didn't
+ // list (non-collected family member): derive its identity from the DOM
+ // node, exactly like the canvas menu's siblingZIndexEntry. Un-targetable
+ // nodes get a live-only style write (reverts on reload).
+ const layer = layerByElement.get(patch.element);
+ const id = layer?.id ?? (patch.element.id || undefined);
+ const selector = layer?.selector ?? buildStableSelector(patch.element);
+ if (!id && !selector) {
+ patch.element.style.zIndex = String(patch.zIndex);
+ continue;
+ }
+ const sourceFile = layer?.sourceFile ?? moved.sourceFile;
+ entries.push({
+ element: patch.element,
+ zIndex: patch.zIndex,
+ id,
+ selector,
+ selectorIndex: layer?.selectorIndex,
+ sourceFile,
+ key: deriveTimelineStoreKey({
+ domId: id,
+ selector,
+ selectorIndex: layer?.selectorIndex,
+ sourceFile,
+ }),
+ });
+ }
+ if (entries.length === 0) return;
+
+ // ONE undo entry for the whole gesture: the z persist and the timeline
+ // lane mirror below share this per-gesture-unique key (same contract as
+ // the canvas menu's wiring in PreviewOverlays).
+ const coalesceKey = zReorderCoalesceKey(entries, "layer-drag");
+ const desiredOrderKeys = desiredBottomToTop.map(
+ (l) =>
+ deriveTimelineStoreKey({
+ domId: l.id,
+ selector: l.selector,
+ selectorIndex: l.selectorIndex,
+ sourceFile: l.sourceFile,
+ }) ?? null,
+ );
+ const movedKey = deriveTimelineStoreKey({
+ domId: moved.id,
+ selector: moved.selector,
+ selectorIndex: moved.selectorIndex,
+ sourceFile: moved.sourceFile,
+ });
+ // One serialized z→lane transaction (shared queue with the canvas
+ // z-order menu): the mirror runs only after a DURABLE z persist, and
+ // rapid successive gestures cannot interleave phases — see
+ // runZLaneGesture.
+ runZLaneGesture({
+ commitZ: () => handleDomZIndexReorderCommit(entries, coalesceKey, "layer-drag"),
+ mirror: () =>
+ mirrorLayerReorderToTimeline({ selectionKey: movedKey, desiredOrderKeys, coalesceKey }),
+ }).catch(() => undefined);
},
- [handleDomZIndexReorderCommit],
+ [handleDomZIndexReorderCommit, mirrorLayerReorderToTimeline],
);
const selectedKey = domEditSelection ? getDomEditLayerKey(domEditSelection) : null;
@@ -436,76 +517,6 @@ export const LayersPanel = memo(function LayersPanel() {
);
});
-// ── Pure helpers ──────────────────────────────────────────────────────
-
-// fallow-ignore-next-line complexity
-export function sortLayersByZIndex(layers: DomEditLayerItem[]): DomEditLayerItem[] {
- if (layers.length <= 1) return layers;
-
- const minDepth = layers[0].depth;
- for (let i = 1; i < layers.length; i++) {
- if (layers[i].depth < minDepth) return layers;
- }
-
- const chunks: Array<{ root: DomEditLayerItem; children: DomEditLayerItem[]; domIndex: number }> =
- [];
-
- for (let i = 0; i < layers.length; i++) {
- if (layers[i].depth === minDepth) {
- const children: DomEditLayerItem[] = [];
- let j = i + 1;
- while (j < layers.length && layers[j].depth > minDepth) {
- children.push(layers[j]);
- j++;
- }
- chunks.push({ root: layers[i], children, domIndex: chunks.length });
- }
- }
-
- if (chunks.length <= 1) {
- if (chunks.length === 1 && chunks[0].children.length > 0) {
- const sorted = sortLayersByZIndex(chunks[0].children);
- return [chunks[0].root, ...sorted];
- }
- return layers;
- }
-
- chunks.sort((a, b) => {
- const zA = getElementZIndex(a.root.element);
- const zB = getElementZIndex(b.root.element);
- if (zA !== zB) return zB - zA;
- return b.domIndex - a.domIndex;
- });
-
- const result: DomEditLayerItem[] = [];
- for (const chunk of chunks) {
- result.push(chunk.root);
- if (chunk.children.length > 0) {
- result.push(...sortLayersByZIndex(chunk.children));
- }
- }
- return result;
-}
-
-function getVisibleLayers(
- layers: DomEditLayerItem[],
- collapsed: CollapsedState,
-): DomEditLayerItem[] {
- if (Object.keys(collapsed).length === 0) return layers;
-
- const result: DomEditLayerItem[] = [];
- let skipDepth = -1;
-
- for (const layer of layers) {
- if (skipDepth >= 0 && layer.depth > skipDepth) continue;
- skipDepth = -1;
-
- result.push(layer);
-
- if (collapsed[layer.key] && layer.childCount > 0) {
- skipDepth = layer.depth;
- }
- }
-
- return result;
-}
+// The sort helper lives in layersPanelSort.ts (600-line studio cap);
+// re-exported so existing imports from "./LayersPanel" still resolve.
+export { sortLayersByZIndex } from "./layersPanelSort";
diff --git a/packages/studio/src/components/editor/canvasContextMenuZOrder.test.ts b/packages/studio/src/components/editor/canvasContextMenuZOrder.test.ts
index b663192cdd..a01a803269 100644
--- a/packages/studio/src/components/editor/canvasContextMenuZOrder.test.ts
+++ b/packages/studio/src/components/editor/canvasContextMenuZOrder.test.ts
@@ -6,6 +6,7 @@ import {
parseZIndex,
resolveCrossedNeighbor,
resolveZOrderChange,
+ resolveZOrderReposition,
type ZOrderAction,
type ZOrderPatch,
} from "./canvasContextMenuZOrder";
@@ -617,3 +618,59 @@ describe("isZOrderActionEnabled", () => {
}
});
});
+
+describe("resolveZOrderReposition (Layers-panel arbitrary drop)", () => {
+ it("multi-position jump with distinct z resolves to ONE between-z write", () => {
+ // Render order bottom→top today: target(1), a(3), b(5). Drop target between
+ // a and b → single write: z strictly between 3 and 5.
+ const { target, byId } = makeFamily("1", [
+ ["a", "3"],
+ ["b", "5"],
+ ]);
+ const patches = resolveZOrderReposition(target, [byId.a, target, byId.b]);
+ expect(patches).toEqual([{ element: target, zIndex: 4 }]);
+ });
+
+ it("jump to the very top writes one z above the previous top", () => {
+ const { target, byId } = makeFamily("1", [
+ ["a", "3"],
+ ["b", "5"],
+ ]);
+ const patches = resolveZOrderReposition(target, [byId.a, byId.b, target]);
+ expect(patches).toEqual([{ element: target, zIndex: 6 }]);
+ });
+
+ it("no-op drop (unchanged order) returns null", () => {
+ const { target, byId } = makeFamily("1", [
+ ["a", "3"],
+ ["b", "5"],
+ ]);
+ expect(resolveZOrderReposition(target, [target, byId.a, byId.b])).toBeNull();
+ });
+
+ it("tied z values renumber the scoped set minimally (band-safe)", () => {
+ const { target, byId } = makeFamily("2", [
+ ["a", "2"],
+ ["b", "2"],
+ ]);
+ // All tied at 2; DOM order target,a,b → render bottom→top target,a,b.
+ // Move target to the top: scoped renumber within the band.
+ const patches = resolveZOrderReposition(target, [byId.a, byId.b, target]);
+ expect(patches).not.toBeNull();
+ const z = new Map(patches!.map((p) => [(p.element as HTMLElement).id, p.zIndex]));
+ const zOf = (id: string) => z.get(id) ?? 2;
+ expect(zOf("a")).toBeLessThan(zOf("b"));
+ expect(zOf("b")).toBeLessThan(zOf("target"));
+ });
+
+ it("rejects elements that are not painting siblings of the target", () => {
+ const { target, byId } = makeFamily("1", [["a", "3"]]);
+ const stranger = makeEl("stranger", "2");
+ expect(resolveZOrderReposition(target, [stranger, target, byId.a])).toBeNull();
+ });
+
+ it("returns null for sets too small to reorder", () => {
+ const { target } = makeFamily("1", []);
+ expect(resolveZOrderReposition(target, [target])).toBeNull();
+ });
+});
diff --git a/packages/studio/src/components/editor/canvasContextMenuZOrder.ts b/packages/studio/src/components/editor/canvasContextMenuZOrder.ts
index 52b2005628..6e5be92c2f 100644
--- a/packages/studio/src/components/editor/canvasContextMenuZOrder.ts
+++ b/packages/studio/src/components/editor/canvasContextMenuZOrder.ts
@@ -42,6 +42,7 @@
*/
import { COLOR_GRADING_SOURCE_HIDDEN_ATTR } from "@hyperframes/core/color-grading";
+import { readLayerRevealPriorZ } from "../../player/lib/timelineElementHelpers";
export type ZOrderAction = "bring-forward" | "send-backward" | "bring-to-front" | "send-to-back";
@@ -107,8 +108,11 @@ export function parseZIndex(value: string | null | undefined): number {
return Number.isFinite(n) ? n : 0;
}
-/** Read the effective z-index for an element (inline style preferred). */
+/** Read the effective z-index for an element (inline style preferred).
+ * Reveal-lift transparent: an active Layers-panel lift reports the TRUE z. */
export function readEffectiveZIndex(el: HTMLElement): number {
+ const prior = readLayerRevealPriorZ(el);
+ if (prior != null) return prior;
const inline = el.style.zIndex;
if (inline && inline !== "auto") return parseZIndex(inline);
try {
@@ -439,6 +443,41 @@ export function resolveZOrderChange(
return realizeOrder(order, desired, target, entries);
}
+/**
+ * Realize an ARBITRARY repositioning of `target` within a scoped sibling set —
+ * the Layers-panel drag, which can jump several siblings in one drop, unlike
+ * the menu's four fixed actions. `desiredOrderBottomToTop` is the scoped set
+ * (target included at its new slot) in the intended render order. Reuses the
+ * menu's minimal-write realization (realizeOrder): one between-z write when a
+ * strict gap exists, band-safe scoped renumber otherwise — replacing the old
+ * LayersPanel computeReorderZValues path that stamped EVERY sibling.
+ *
+ * Null when nothing changes, the set is too small, or an element in the
+ * desired order is not actually a painting sibling of `target`.
+ */
+export function resolveZOrderReposition(
+ target: HTMLElement,
+ desiredOrderBottomToTop: readonly HTMLElement[],
+): ZOrderPatch[] | null {
+ const { entries } = getFamily(target);
+ if (entries.length < 2) return null;
+ const byElement = new Map(entries.map((entry) => [entry.element, entry]));
+ const desired: RenderEntry[] = [];
+ for (const el of desiredOrderBottomToTop) {
+ const entry = byElement.get(el);
+ if (!entry) return null;
+ desired.push(entry);
+ }
+ if (desired.length < 2 || !desired.some((entry) => entry.element === target)) return null;
+ const currentOrder = toRenderOrder(desired);
+ // A drop back into the same slot is a no-op. The menu actions guard this via
+ // their position checks before realizeOrder; an arbitrary reposition must
+ // compare the orders itself — realizeOrder would otherwise "normalize" an
+ // end-of-set target to a fresh z value it doesn't need.
+ if (currentOrder.every((entry, i) => entry.element === desired[i].element)) return null;
+ return realizeOrder(currentOrder, desired, target, entries);
+}
+
/**
* The sibling a forward/backward step crosses: the visible overlapping
* neighbor directly above (bring-forward) or below (send-backward) the target
diff --git a/packages/studio/src/components/editor/domEditingDom.ts b/packages/studio/src/components/editor/domEditingDom.ts
index e01eb476bf..b498f3cae8 100644
--- a/packages/studio/src/components/editor/domEditingDom.ts
+++ b/packages/studio/src/components/editor/domEditingDom.ts
@@ -4,6 +4,7 @@
* No imports from other domEditing* modules — safe to import from anywhere.
*/
import { COLOR_GRADING_SOURCE_HIDDEN_ATTR } from "@hyperframes/core/color-grading";
+import { getSourceScopedSelectorIndex } from "../../utils/sourceScopedSelectorIndex";
import { CURATED_STYLE_PROPERTIES } from "./domEditingTypes";
// ─── Type guard ───────────────────────────────────────────────────────────────
@@ -296,11 +297,9 @@ export function getSelectorIndex(
): number | undefined {
if (!selector?.startsWith(".")) return undefined;
- const candidates = querySelectorAllSafely(doc, selector).filter(
- (candidate): candidate is HTMLElement =>
- isHtmlElement(candidate) &&
- getSourceFileForElement(candidate, activeCompositionPath).sourceFile === sourceFile,
+ return getSourceScopedSelectorIndex(doc, el, selector, sourceFile, (candidate) =>
+ isHtmlElement(candidate)
+ ? getSourceFileForElement(candidate, activeCompositionPath).sourceFile
+ : undefined,
);
- const index = candidates.indexOf(el);
- return index >= 0 ? index : undefined;
}
diff --git a/packages/studio/src/components/editor/domEditingElement.ts b/packages/studio/src/components/editor/domEditingElement.ts
index 1d7e3fab29..916f9f9779 100644
--- a/packages/studio/src/components/editor/domEditingElement.ts
+++ b/packages/studio/src/components/editor/domEditingElement.ts
@@ -246,45 +246,28 @@ export function findElementForSelection(
selection: FindElementSelection,
activeCompositionPath: string | null = null,
): HTMLElement | null {
+ const sourceMatches = (candidate: Element): candidate is HTMLElement =>
+ isHtmlElement(candidate) &&
+ (!selection.sourceFile ||
+ getSourceFileForElement(candidate, activeCompositionPath).sourceFile ===
+ selection.sourceFile);
+ const findAll = (selector: string): HTMLElement[] =>
+ querySelectorAllSafely(doc, selector).filter(sourceMatches);
+
if (selection.hfId) {
- const byHfId = doc.querySelector(`[data-hf-id="${CSS.escape(selection.hfId)}"]`);
- if (isHtmlElement(byHfId)) return byHfId;
+ const byHfId = findAll(`[data-hf-id="${escapeCssString(selection.hfId)}"]`)[0];
+ if (byHfId) return byHfId;
}
if (selection.id) {
- const byId = doc.getElementById(selection.id);
- if (
- isHtmlElement(byId) &&
- (!selection.sourceFile ||
- getSourceFileForElement(byId, activeCompositionPath).sourceFile === selection.sourceFile)
- ) {
- return byId;
- }
+ // Flattened sub-compositions can repeat authored ids. getElementById returns
+ // only the first document match, so filter every id match by source first.
+ const byId = findAll(`[id="${escapeCssString(selection.id)}"]`)[0];
+ if (byId) return byId;
}
if (!selection.selector) return null;
-
- // fallow-ignore-next-line code-duplication
- if (selection.selector.startsWith(".") && selection.selectorIndex != null) {
- const matches = querySelectorAllSafely(doc, selection.selector).filter(
- (candidate): candidate is HTMLElement =>
- isHtmlElement(candidate) &&
- (!selection.sourceFile ||
- getSourceFileForElement(candidate, activeCompositionPath).sourceFile ===
- selection.sourceFile),
- );
- return matches[selection.selectorIndex] ?? null;
- }
-
- // fallow-ignore-next-line code-duplication
- const matches = querySelectorAllSafely(doc, selection.selector).filter(
- (candidate): candidate is HTMLElement =>
- isHtmlElement(candidate) &&
- (!selection.sourceFile ||
- getSourceFileForElement(candidate, activeCompositionPath).sourceFile ===
- selection.sourceFile),
- );
- return matches[0] ?? null;
+ return findAll(selection.selector)[selection.selectorIndex ?? 0] ?? null;
}
// fallow-ignore-next-line complexity
diff --git a/packages/studio/src/components/editor/layersPanelSort.ts b/packages/studio/src/components/editor/layersPanelSort.ts
new file mode 100644
index 0000000000..29105f4f30
--- /dev/null
+++ b/packages/studio/src/components/editor/layersPanelSort.ts
@@ -0,0 +1,80 @@
+import type { DomEditLayerItem } from "./domEditingTypes";
+import { getElementZIndex } from "../../player/lib/layerOrdering";
+
+interface CollapsedState {
+ [key: string]: boolean;
+}
+
+// ── Pure helpers ──────────────────────────────────────────────────────
+
+// fallow-ignore-next-line complexity
+export function sortLayersByZIndex(layers: DomEditLayerItem[]): DomEditLayerItem[] {
+ if (layers.length <= 1) return layers;
+
+ const minDepth = layers[0].depth;
+ for (let i = 1; i < layers.length; i++) {
+ if (layers[i].depth < minDepth) return layers;
+ }
+
+ const chunks: Array<{ root: DomEditLayerItem; children: DomEditLayerItem[]; domIndex: number }> =
+ [];
+
+ for (let i = 0; i < layers.length; i++) {
+ if (layers[i].depth === minDepth) {
+ const children: DomEditLayerItem[] = [];
+ let j = i + 1;
+ while (j < layers.length && layers[j].depth > minDepth) {
+ children.push(layers[j]);
+ j++;
+ }
+ chunks.push({ root: layers[i], children, domIndex: chunks.length });
+ }
+ }
+
+ if (chunks.length <= 1) {
+ if (chunks.length === 1 && chunks[0].children.length > 0) {
+ const sorted = sortLayersByZIndex(chunks[0].children);
+ return [chunks[0].root, ...sorted];
+ }
+ return layers;
+ }
+
+ chunks.sort((a, b) => {
+ const zA = getElementZIndex(a.root.element);
+ const zB = getElementZIndex(b.root.element);
+ if (zA !== zB) return zB - zA;
+ return b.domIndex - a.domIndex;
+ });
+
+ const result: DomEditLayerItem[] = [];
+ for (const chunk of chunks) {
+ result.push(chunk.root);
+ if (chunk.children.length > 0) {
+ result.push(...sortLayersByZIndex(chunk.children));
+ }
+ }
+ return result;
+}
+
+export function getVisibleLayers(
+ layers: DomEditLayerItem[],
+ collapsed: CollapsedState,
+): DomEditLayerItem[] {
+ if (Object.keys(collapsed).length === 0) return layers;
+
+ const result: DomEditLayerItem[] = [];
+ let skipDepth = -1;
+
+ for (const layer of layers) {
+ if (skipDepth >= 0 && layer.depth > skipDepth) continue;
+ skipDepth = -1;
+
+ result.push(layer);
+
+ if (collapsed[layer.key] && layer.childCount > 0) {
+ skipDepth = layer.depth;
+ }
+ }
+
+ return result;
+}
diff --git a/packages/studio/src/components/editor/useLayerRevealOverride.test.ts b/packages/studio/src/components/editor/useLayerRevealOverride.test.ts
new file mode 100644
index 0000000000..b761211bd7
--- /dev/null
+++ b/packages/studio/src/components/editor/useLayerRevealOverride.test.ts
@@ -0,0 +1,169 @@
+// @vitest-environment jsdom
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ LAYER_REVEAL_LIFT_Z,
+ LAYER_REVEAL_PENDING_COMMIT_ATTR,
+ beginLayerRevealCommit,
+ completeLayerRevealCommit,
+ liftElementToTop,
+ restoreLiftedElement,
+ useLayerRevealOverride,
+} from "./useLayerRevealOverride";
+import { readEffectiveZIndex } from "./canvasContextMenuZOrder";
+import { getElementZIndex } from "../../player/lib/layerOrdering";
+import {
+ LAYER_REVEAL_PRIOR_Z_ATTR,
+ readTimelineElementZIndex,
+} from "../../player/lib/timelineElementHelpers";
+import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness";
+
+installReactActEnvironment();
+
+function makeEl(zIndex?: string, position?: string): HTMLElement {
+ const el = document.createElement("div");
+ if (zIndex != null) el.style.zIndex = zIndex;
+ if (position != null) el.style.position = position;
+ document.body.appendChild(el);
+ return el;
+}
+
+describe("liftElementToTop / restoreLiftedElement", () => {
+ it("paints on top but every z reader keeps reporting the TRUE z", () => {
+ const el = makeEl("6", "absolute");
+ const lift = liftElementToTop(el);
+ expect(lift).not.toBeNull();
+ // The renderer sees the lifted value…
+ expect(el.style.zIndex).toBe(LAYER_REVEAL_LIFT_Z);
+ // …every studio reader sees the true z.
+ expect(readEffectiveZIndex(el)).toBe(6);
+ expect(getElementZIndex(el)).toBe(6);
+ expect(readTimelineElementZIndex(el)).toBe(6);
+
+ restoreLiftedElement(el, lift!);
+ expect(el.style.zIndex).toBe("6");
+ expect(el.hasAttribute(LAYER_REVEAL_PRIOR_Z_ATTR)).toBe(false);
+ });
+
+ it("gives a static element a temporary position:relative and restores it", () => {
+ const el = makeEl();
+ const lift = liftElementToTop(el)!;
+ expect(el.style.position).toBe("relative");
+ expect(lift.positionLifted).toBe(true);
+ restoreLiftedElement(el, lift);
+ expect(el.style.position).toBe("");
+ expect(el.style.zIndex).toBe("");
+ });
+
+ it("a z-reorder commit consumes the lift: restore becomes a no-op", () => {
+ const el = makeEl("3", "absolute");
+ const lift = liftElementToTop(el)!;
+ // Simulate handleDomZIndexReorderCommit: real z written, attrs removed.
+ el.removeAttribute(LAYER_REVEAL_PRIOR_Z_ATTR);
+ el.style.zIndex = "8";
+ restoreLiftedElement(el, lift);
+ expect(el.style.zIndex).toBe("8"); // the commit's value survives
+ expect(readEffectiveZIndex(el)).toBe(8);
+ });
+
+ it("durable z persistence consumes its pending reveal ownership", () => {
+ const el = makeEl("3", "absolute");
+ const lift = liftElementToTop(el)!;
+ const ownership = beginLayerRevealCommit(el)!;
+ el.style.zIndex = "8";
+
+ expect(el.hasAttribute(LAYER_REVEAL_PENDING_COMMIT_ATTR)).toBe(true);
+ completeLayerRevealCommit(el, ownership);
+ restoreLiftedElement(el, lift);
+
+ expect(el.style.zIndex).toBe("8");
+ expect(el.hasAttribute(LAYER_REVEAL_PENDING_COMMIT_ATTR)).toBe(false);
+ expect(el.hasAttribute(LAYER_REVEAL_PRIOR_Z_ATTR)).toBe(false);
+ });
+
+ it("does not clobber a z someone else wrote while lifted", () => {
+ const el = makeEl("3", "absolute");
+ const lift = liftElementToTop(el)!;
+ el.style.zIndex = "42"; // e.g. a GSAP seek or manual edit
+ restoreLiftedElement(el, lift);
+ expect(el.style.zIndex).toBe("42");
+ });
+});
+
+describe("useLayerRevealOverride — delayed reveal ownership", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ document.body.innerHTML = "";
+ });
+
+ it("cancels a pending reveal when selection changes or playback begins", () => {
+ const host = document.createElement("div");
+ const selected = makeEl("2", "absolute");
+ const other = makeEl("3", "absolute");
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ let scheduleReveal: ((element: HTMLElement, delayMs: number) => void) | undefined;
+
+ function Harness({ element, isPlaying }: { element: HTMLElement; isPlaying: boolean }) {
+ ({ scheduleReveal } = useLayerRevealOverride({
+ isPlaying,
+ selectedElement: element,
+ }));
+ return null;
+ }
+
+ act(() => {
+ root.render(React.createElement(Harness, { element: selected, isPlaying: false }));
+ });
+ act(() => scheduleReveal!(selected, 150));
+ expect(vi.getTimerCount()).toBe(1);
+
+ act(() => {
+ root.render(React.createElement(Harness, { element: other, isPlaying: false }));
+ });
+ expect(vi.getTimerCount()).toBe(0);
+
+ act(() => scheduleReveal!(other, 150));
+ expect(vi.getTimerCount()).toBe(1);
+ act(() => {
+ root.render(React.createElement(Harness, { element: other, isPlaying: true }));
+ });
+ expect(vi.getTimerCount()).toBe(0);
+
+ act(() => vi.advanceTimersByTime(150));
+ expect(selected.style.zIndex).toBe("2");
+ expect(other.style.zIndex).toBe("3");
+ act(() => root.unmount());
+ });
+
+ it("revalidates the current selection before a delayed reveal runs", () => {
+ const host = document.createElement("div");
+ const selected = makeEl("2", "absolute");
+ const stale = makeEl("3", "absolute");
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ let scheduleReveal: ((element: HTMLElement, delayMs: number) => void) | undefined;
+
+ function Harness() {
+ ({ scheduleReveal } = useLayerRevealOverride({
+ isPlaying: false,
+ selectedElement: selected,
+ }));
+ return null;
+ }
+
+ act(() => root.render(React.createElement(Harness)));
+ act(() => scheduleReveal!(stale, 150));
+ expect(vi.getTimerCount()).toBe(1);
+ act(() => vi.advanceTimersByTime(150));
+
+ expect(stale.style.zIndex).toBe("3");
+ expect(stale.hasAttribute(LAYER_REVEAL_PRIOR_Z_ATTR)).toBe(false);
+ act(() => root.unmount());
+ });
+});
diff --git a/packages/studio/src/components/editor/useLayerRevealOverride.ts b/packages/studio/src/components/editor/useLayerRevealOverride.ts
new file mode 100644
index 0000000000..2dd481f3a4
--- /dev/null
+++ b/packages/studio/src/components/editor/useLayerRevealOverride.ts
@@ -0,0 +1,389 @@
+import { useCallback, useEffect, useRef } from "react";
+import {
+ LAYER_REVEAL_PRIOR_POSITION_ATTR,
+ LAYER_REVEAL_PRIOR_Z_ATTR,
+} from "../../player/lib/timelineElementHelpers";
+import { readEffectiveZIndex } from "./canvasContextMenuZOrder";
+
+/** The lifted paint order — far above any authored z. Only the RENDERER sees
+ * it: every studio z reader is reveal-transparent (readLayerRevealPriorZ). */
+export const LAYER_REVEAL_LIFT_Z = "2147483000";
+export const LAYER_REVEAL_PENDING_COMMIT_ATTR = "data-hf-studio-reveal-pending-commit";
+
+interface RevealedNode {
+ element: HTMLElement;
+ priors: { display: string; visibility: string; opacity: string };
+ /** Values THIS override wrote — restore only while they are still in place. */
+ applied: { display?: string; visibility?: string; opacity?: string };
+}
+
+interface RevealLift {
+ priors: { zIndex: string; position: string };
+ positionLifted: boolean;
+}
+
+type PendingRevealCommit = {
+ token: string;
+ releasedPriors?: RevealLift["priors"];
+};
+
+export type LayerRevealCommitOwnership = {
+ token: string;
+ priorZ: string;
+ priorPosition: string | null;
+ activeLiftStyles: RevealLift["priors"];
+};
+
+let revealCommitSequence = 0;
+const zPersistCounts = new WeakMap<HTMLElement, number>();
+const REVEAL_RETRY_MS = 16;
+
+/** Prevent delayed reveals from capturing an optimistic z as authored state. */
+export function beginLayerZPersist(element: HTMLElement): () => void {
+ zPersistCounts.set(element, (zPersistCounts.get(element) ?? 0) + 1);
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ const remaining = (zPersistCounts.get(element) ?? 1) - 1;
+ if (remaining > 0) zPersistCounts.set(element, remaining);
+ else zPersistCounts.delete(element);
+ };
+}
+
+interface RevealState {
+ /** The layer element the reveal was applied for (deselect detection). */
+ base: HTMLElement;
+ nodes: RevealedNode[];
+ lift: RevealLift | null;
+}
+
+function restoreInline(el: HTMLElement, property: string, prior: string): void {
+ if (prior) el.style.setProperty(property, prior);
+ else el.style.removeProperty(property);
+}
+
+// This decoder owns the complete serialized reveal-commit schema. Splitting
+// field checks across helpers would create multiple authorities for validity.
+// fallow-ignore-next-line complexity
+function readPendingRevealCommit(element: HTMLElement): PendingRevealCommit | null {
+ const raw = element.getAttribute(LAYER_REVEAL_PENDING_COMMIT_ATTR);
+ if (!raw) return null;
+ try {
+ const value: unknown = JSON.parse(raw);
+ if (typeof value !== "object" || value === null || !("token" in value)) return null;
+ const token = value.token;
+ if (typeof token !== "string") return null;
+ if (!("releasedPriors" in value) || value.releasedPriors === undefined) return { token };
+ const releasedPriors = value.releasedPriors;
+ if (
+ typeof releasedPriors !== "object" ||
+ releasedPriors === null ||
+ !("zIndex" in releasedPriors) ||
+ !("position" in releasedPriors)
+ ) {
+ return null;
+ }
+ const { zIndex, position } = releasedPriors;
+ return typeof zIndex === "string" && typeof position === "string"
+ ? { token, releasedPriors: { zIndex, position } }
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+function writePendingRevealCommit(element: HTMLElement, state: PendingRevealCommit): void {
+ element.setAttribute(LAYER_REVEAL_PENDING_COMMIT_ATTR, JSON.stringify(state));
+}
+
+/** Hand an active reveal lift to one pending durable z commit. */
+export function beginLayerRevealCommit(element: HTMLElement): LayerRevealCommitOwnership | null {
+ const priorZ = element.getAttribute(LAYER_REVEAL_PRIOR_Z_ATTR);
+ if (priorZ == null) return null;
+ const ownership = {
+ token: `reveal-z-${revealCommitSequence++}`,
+ priorZ,
+ priorPosition: element.getAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR),
+ activeLiftStyles: { zIndex: element.style.zIndex, position: element.style.position },
+ };
+ writePendingRevealCommit(element, { token: ownership.token });
+ element.removeAttribute(LAYER_REVEAL_PRIOR_Z_ATTR);
+ element.removeAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR);
+ return ownership;
+}
+
+/** Durable success consumes the reveal regardless of whether selection released it meanwhile. */
+export function completeLayerRevealCommit(
+ element: HTMLElement,
+ ownership: LayerRevealCommitOwnership,
+): void {
+ if (readPendingRevealCommit(element)?.token === ownership.token) {
+ element.removeAttribute(LAYER_REVEAL_PENDING_COMMIT_ATTR);
+ }
+}
+
+/**
+ * Roll back only the reveal transaction this commit owns. An active reveal gets
+ * its temporary lift back; a reveal released while persistence was pending gets
+ * its exact authored inline styles back, with no resurrected metadata.
+ */
+export function rollbackLayerRevealCommit(
+ element: HTMLElement,
+ ownership: LayerRevealCommitOwnership,
+): void {
+ const pending = readPendingRevealCommit(element);
+ if (pending?.token !== ownership.token) return;
+ element.removeAttribute(LAYER_REVEAL_PENDING_COMMIT_ATTR);
+ element.removeAttribute(LAYER_REVEAL_PRIOR_Z_ATTR);
+ element.removeAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR);
+ if (pending.releasedPriors) {
+ restoreInline(element, "z-index", pending.releasedPriors.zIndex);
+ restoreInline(element, "position", pending.releasedPriors.position);
+ return;
+ }
+ restoreInline(element, "z-index", ownership.activeLiftStyles.zIndex);
+ restoreInline(element, "position", ownership.activeLiftStyles.position);
+ element.setAttribute(LAYER_REVEAL_PRIOR_Z_ATTR, ownership.priorZ);
+ if (ownership.priorPosition != null) {
+ element.setAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR, ownership.priorPosition);
+ }
+}
+
+/** Restore a property ONLY when its current inline value is still the one this
+ * override wrote — a later real edit (commit, animation seek) is the new
+ * truth and must not be clobbered. */
+function restoreIfOurs(
+ el: HTMLElement,
+ property: "display" | "visibility" | "opacity",
+ applied: string | undefined,
+ prior: string,
+): void {
+ if (applied == null) return;
+ if (el.style.getPropertyValue(property) !== applied) return;
+ restoreInline(el, property, prior);
+}
+
+/** What hides this node at the current frame, per computed style. */
+function readHideSignals(el: HTMLElement, win: Window) {
+ const computed = win.getComputedStyle(el);
+ const opacity = Number.parseFloat(computed.opacity);
+ return {
+ display: computed.display === "none",
+ visibility: computed.visibility === "hidden" || computed.visibility === "collapse",
+ opacity: Number.isFinite(opacity) && opacity <= 0.01,
+ };
+}
+
+/** Force one hidden node visible with inline styles; returns priors + applied. */
+function revealNode(
+ el: HTMLElement,
+ win: Window,
+ needs: ReturnType<typeof readHideSignals>,
+): RevealedNode {
+ const priors = {
+ display: el.style.display,
+ visibility: el.style.visibility,
+ opacity: el.style.opacity,
+ };
+ const applied: RevealedNode["applied"] = {};
+ if (needs.display) {
+ // Prefer whatever the stylesheet says once the inline hide is lifted;
+ // only force block when the sheet itself hides it.
+ el.style.removeProperty("display");
+ if (win.getComputedStyle(el).display === "none") el.style.display = "block";
+ applied.display = el.style.display;
+ }
+ if (needs.visibility) {
+ el.style.visibility = "visible";
+ applied.visibility = "visible";
+ }
+ if (needs.opacity) {
+ el.style.opacity = "1";
+ applied.opacity = "1";
+ }
+ return { element: el, priors, applied };
+}
+
+/** Walk `element` → body, force-revealing every hiding node; returns the touched nodes. */
+function revealHiddenChain(element: HTMLElement): RevealedNode[] {
+ const doc = element.ownerDocument;
+ const win = doc.defaultView;
+ if (!win) return [];
+ const nodes: RevealedNode[] = [];
+ let el: HTMLElement | null = element;
+ while (el && el !== doc.body && el !== doc.documentElement) {
+ let needs: ReturnType<typeof readHideSignals>;
+ try {
+ needs = readHideSignals(el, win);
+ } catch {
+ break; // detached / cross-realm — leave the rest alone
+ }
+ if (needs.display || needs.visibility || needs.opacity) nodes.push(revealNode(el, win, needs));
+ el = el.parentElement;
+ }
+ return nodes;
+}
+
+/**
+ * Lift the selected element to the TOP of the paint order while selected —
+ * regardless of its authored z or panel position. The true z is parked in
+ * LAYER_REVEAL_PRIOR_Z_ATTR so every studio z reader keeps reporting it (the
+ * lift is invisible to menus, badges, the lane mirror, and the panel sort);
+ * only the renderer sees the lifted inline value. A static element gets a
+ * temporary position:relative (layout-preserving) so the z applies, with the
+ * prior position parked in LAYER_REVEAL_PRIOR_POSITION_ATTR for the z-commit's
+ * static check. Exported for direct unit testing.
+ */
+export function liftElementToTop(element: HTMLElement): RevealLift | null {
+ const win = element.ownerDocument.defaultView;
+ if (!win) return null;
+ const priors = { zIndex: element.style.zIndex, position: element.style.position };
+ let positionLifted = false;
+ try {
+ element.setAttribute(LAYER_REVEAL_PRIOR_Z_ATTR, String(readEffectiveZIndex(element)));
+ if (win.getComputedStyle(element).position === "static") {
+ element.setAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR, "static");
+ element.style.position = "relative";
+ positionLifted = true;
+ }
+ } catch {
+ element.removeAttribute(LAYER_REVEAL_PRIOR_Z_ATTR);
+ return null; // detached / cross-realm — no lift
+ }
+ element.style.zIndex = LAYER_REVEAL_LIFT_Z;
+ return { priors, positionLifted };
+}
+
+/**
+ * Undo an active lift. Skipped entirely when the prior-z attribute is gone —
+ * a z-reorder commit consumed the lift (handleDomZIndexReorderCommit removes
+ * the attributes and writes the new real z), and that commit is the truth.
+ * Exported for direct unit testing.
+ */
+export function restoreLiftedElement(element: HTMLElement, lift: RevealLift): void {
+ if (!element.hasAttribute(LAYER_REVEAL_PRIOR_Z_ATTR)) {
+ const pending = readPendingRevealCommit(element);
+ if (pending && !pending.releasedPriors) {
+ // Persistence temporarily owns the live z. Hand it the exact authored
+ // priors so a later rejection can restore them after this hook lets go.
+ writePendingRevealCommit(element, { ...pending, releasedPriors: lift.priors });
+ }
+ return;
+ }
+ element.removeAttribute(LAYER_REVEAL_PRIOR_Z_ATTR);
+ element.removeAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR);
+ if (element.style.zIndex === LAYER_REVEAL_LIFT_Z) {
+ restoreInline(element, "z-index", lift.priors.zIndex);
+ }
+ if (lift.positionLifted && element.style.position === "relative") {
+ restoreInline(element, "position", lift.priors.position);
+ }
+}
+
+/**
+ * Temporary "show me this element" override for the Layers panel
+ * (Webflow-navigator style): clicking a layer forces it (and every hiding
+ * ancestor up to the body) visible with LIVE inline styles, and paints it on
+ * TOP of the stack while selected (see liftElementToTop).
+ *
+ * Strictly ephemeral by construction:
+ * - Exact prior inline values are recorded per touched node and restored on
+ * every exit path — reveal of a different layer, deselect, playback start,
+ * unmount. Nothing is ever sent to a persist path, and each property is
+ * restored only while it still holds the value this override wrote.
+ * - A post-edit iframe reload replaces the DOM; detached nodes are skipped on
+ * restore (the fresh document never had the override).
+ * - Scrubbing/playing lets the runtime and GSAP rewrite these same inline
+ * styles — that is the animation showing reality, and the override is
+ * dropped on play for exactly that reason.
+ */
+export function useLayerRevealOverride({
+ isPlaying,
+ selectedElement,
+}: {
+ isPlaying: boolean;
+ selectedElement: HTMLElement | null;
+}): {
+ scheduleReveal: (element: HTMLElement, delayMs: number) => void;
+} {
+ const stateRef = useRef<RevealState | null>(null);
+ const pendingRevealRef = useRef<{ timer: number; element: HTMLElement } | null>(null);
+ const currentRef = useRef({ isPlaying, selectedElement });
+ currentRef.current = { isPlaying, selectedElement };
+
+ const restoreReveal = useCallback(() => {
+ const state = stateRef.current;
+ stateRef.current = null;
+ if (!state) return;
+ for (const { element, priors, applied } of state.nodes) {
+ if (!element.isConnected) continue;
+ restoreIfOurs(element, "display", applied.display, priors.display);
+ restoreIfOurs(element, "visibility", applied.visibility, priors.visibility);
+ restoreIfOurs(element, "opacity", applied.opacity, priors.opacity);
+ }
+ if (state.lift && state.base.isConnected) restoreLiftedElement(state.base, state.lift);
+ }, []);
+
+ const reveal = useCallback(
+ (element: HTMLElement) => {
+ restoreReveal();
+ const nodes = revealHiddenChain(element);
+ const lift = liftElementToTop(element);
+ if (nodes.length > 0 || lift) stateRef.current = { base: element, nodes, lift };
+ },
+ [restoreReveal],
+ );
+
+ const cancelScheduledReveal = useCallback(() => {
+ const pending = pendingRevealRef.current;
+ pendingRevealRef.current = null;
+ if (pending) window.clearTimeout(pending.timer);
+ }, []);
+
+ const scheduleReveal = useCallback(
+ (element: HTMLElement, delayMs: number) => {
+ cancelScheduledReveal();
+ const current = currentRef.current;
+ if (current.isPlaying) return;
+ const attemptReveal = () => {
+ const latest = currentRef.current;
+ if (latest.isPlaying || latest.selectedElement !== element || !element.isConnected) {
+ pendingRevealRef.current = null;
+ return;
+ }
+ if (zPersistCounts.has(element)) {
+ const timer = window.setTimeout(attemptReveal, REVEAL_RETRY_MS);
+ pendingRevealRef.current = { timer, element };
+ return;
+ }
+ pendingRevealRef.current = null;
+ reveal(element);
+ };
+ const timer = window.setTimeout(attemptReveal, delayMs);
+ pendingRevealRef.current = { timer, element };
+ },
+ [cancelScheduledReveal, reveal],
+ );
+
+ // Selection and playback jointly own eligibility for both pending and active
+ // reveals. Cancel first; playback or a different selection then restores the
+ // animation/authored styles.
+ useEffect(() => {
+ const pending = pendingRevealRef.current;
+ if (isPlaying || (pending && pending.element !== selectedElement)) cancelScheduledReveal();
+ const base = stateRef.current?.base;
+ if (isPlaying || (base && selectedElement !== base)) restoreReveal();
+ }, [cancelScheduledReveal, isPlaying, restoreReveal, selectedElement]);
+
+ // Unmount: never leave a timer or override behind.
+ useEffect(
+ () => () => {
+ cancelScheduledReveal();
+ restoreReveal();
+ },
+ [cancelScheduledReveal, restoreReveal],
+ );
+
+ return { scheduleReveal };
+}
diff --git a/packages/studio/src/components/nle/PreviewOverlays.tsx b/packages/studio/src/components/nle/PreviewOverlays.tsx
index 19c9a234f7..2eeb4f6294 100644
--- a/packages/studio/src/components/nle/PreviewOverlays.tsx
+++ b/packages/studio/src/components/nle/PreviewOverlays.tsx
@@ -19,6 +19,9 @@ import { readStudioUiPreferences } from "../../utils/studioUiPreferences";
import { readHfId, type DomEditSelection } from "../editor/domEditing";
import { buildStableSelector } from "../editor/domEditingDom";
import { deriveTimelineStoreKey } from "../../player/lib/timelineElementHelpers";
+import { zReorderCoalesceKey } from "../../hooks/useElementLifecycleOps";
+import { useCanvasZOrderTimelineMirror } from "./useCanvasZOrderTimelineMirror";
+import { runZLaneGesture } from "./zLaneGesture";
import type { BlockPreviewInfo } from "../sidebar/BlocksTab";
import type { GestureRecordingState } from "../editor/GestureRecordControl";
import type { ReactNode } from "react";
@@ -158,6 +161,7 @@ export function PreviewOverlays({
handleDomEditElementDelete,
handleDomZIndexReorderCommit,
} = useDomEditActionsContext();
+ const mirrorZOrderToTimeline = useCanvasZOrderTimelineMirror();
// fallow-ignore-next-line complexity
const [snapPrefs, setSnapPrefs] = useState(() => {
@@ -224,7 +228,7 @@ export function PreviewOverlays({
onRotationCommit={handleDomRotationCommit}
onStyleCommit={handleDomStyleCommit}
onDeleteSelection={handleDomEditElementDelete}
- onApplyZIndex={(sel, patches, action) => {
+ onApplyZIndex={(sel, patches, action, crossed) => {
const { entries, dropped } = resolveZIndexEntries(sel, patches);
if (dropped.length > 0) {
// These siblings can't be written to source. Apply their live z
@@ -237,7 +241,28 @@ export function PreviewOverlays({
dropped.map((patch) => describeZIndexElement(patch.element)).join(", "),
);
}
- if (entries.length > 0) handleDomZIndexReorderCommit(entries, undefined, action);
+ if (entries.length === 0) return;
+ // Shared undo coalesce key: passed to BOTH the z persist and the
+ // timeline lane mirror below so editHistory folds the two records
+ // into one undo entry (same value handleDomZIndexReorderCommit would
+ // default to — passed explicitly so the mirror shares it by
+ // construction, not by formula duplication).
+ const coalesceKey = zReorderCoalesceKey(entries, action);
+ // One serialized z→lane transaction: the mirror runs only AFTER the
+ // z commit resolved AND reported durable targets, and a second rapid
+ // gesture cannot interleave between the two phases — see
+ // runZLaneGesture. A failed z commit already toasted + rolled back.
+ runZLaneGesture({
+ commitZ: () => handleDomZIndexReorderCommit(entries, coalesceKey, action),
+ mirror: () =>
+ mirrorZOrderToTimeline({
+ selectionKey: entries.find((e) => e.element === sel.element)?.key,
+ action,
+ crossed,
+ sourceFile: sel.sourceFile,
+ coalesceKey,
+ }),
+ }).catch(() => undefined);
}}
gridVisible={snapPrefs.gridVisible}
gridSpacing={snapPrefs.gridSpacing}
diff --git a/packages/studio/src/components/nle/TimelinePane.test.ts b/packages/studio/src/components/nle/TimelinePane.test.ts
index e01813bc43..1e4c0c082f 100644
--- a/packages/studio/src/components/nle/TimelinePane.test.ts
+++ b/packages/studio/src/components/nle/TimelinePane.test.ts
@@ -22,6 +22,7 @@ describe("TimelinePane move wrapper", () => {
"clip-lane-move:7",
"track-insert",
onMoveElements,
+ Number.POSITIVE_INFINITY,
);
expect(onMoveElements).toHaveBeenCalledWith(
[
@@ -32,6 +33,8 @@ describe("TimelinePane move wrapper", () => {
],
"clip-lane-move:7",
"track-insert",
+ // The per-gesture coalesce window rides along with the shared key.
+ Number.POSITIVE_INFINITY,
);
});
diff --git a/packages/studio/src/components/nle/TimelinePane.tsx b/packages/studio/src/components/nle/TimelinePane.tsx
index 1b0b402eab..3c9587f756 100644
--- a/packages/studio/src/components/nle/TimelinePane.tsx
+++ b/packages/studio/src/components/nle/TimelinePane.tsx
@@ -21,7 +21,9 @@ export function forwardRebasedTimelineMoveElements(
edits: TimelineMoveEdit[],
coalesceKey?: string,
operation?: TimelineMoveOperation,
+ coalesceMs?: number,
) => Promise<void> | void,
+ coalesceMs?: number,
) {
return onMoveElements(
edits.map(({ element, updates }) => {
@@ -34,6 +36,7 @@ export function forwardRebasedTimelineMoveElements(
}),
coalesceKey,
operation,
+ coalesceMs,
);
}
@@ -160,6 +163,7 @@ export function TimelinePane({
edits: Array<{ element: TimelineElement; updates: Pick<TimelineElement, "start" | "track"> }>,
coalesceKey?: string,
operation?: TimelineMoveOperation,
+ coalesceMs?: number,
) => {
// Match the sibling handlers: report the telemetry when the batch touches at
// least one expanded sub-comp child (the clips being rebased to local coords).
@@ -167,7 +171,13 @@ export function TimelinePane({
trackStudioExpandedClipEdit({ action: "move" });
}
if (!onMoveElements) return;
- return forwardRebasedTimelineMoveElements(edits, coalesceKey, operation, onMoveElements);
+ return forwardRebasedTimelineMoveElements(
+ edits,
+ coalesceKey,
+ operation,
+ onMoveElements,
+ coalesceMs,
+ );
},
[onMoveElements],
);
diff --git a/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.test.tsx b/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.test.tsx
new file mode 100644
index 0000000000..e4c041053f
--- /dev/null
+++ b/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.test.tsx
@@ -0,0 +1,440 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { afterEach, describe, expect, it } from "vitest";
+import { usePlayerStore, type TimelineElement } from "../../player";
+import { TimelineEditProvider } from "../../contexts/TimelineEditContext";
+import type { TimelineEditCallbacks } from "../../player/components/timelineCallbacks";
+import { useElementLifecycleOps, zReorderCoalesceKey } from "../../hooks/useElementLifecycleOps";
+import {
+ useCanvasZOrderTimelineMirror,
+ type MirrorZOrderInput,
+} from "./useCanvasZOrderTimelineMirror";
+import { makeLifecycleOpsParams } from "../../hooks/elementLifecycleOpsTestUtils";
+import { mountReactHarness } from "../../hooks/domSelectionTestHarness";
+import {
+ buildEditHistoryEntry,
+ createEmptyEditHistory,
+ pushEditHistoryEntry,
+ type EditHistoryState,
+} from "../../utils/editHistory";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+afterEach(() => {
+ document.body.innerHTML = "";
+ // Wrapped in act: mounted harnesses subscribe to the store via
+ // useExpandedTimelineElements, so the reset re-renders them.
+ act(() => usePlayerStore.getState().setElements([]));
+});
+
+/** Set the store elements inside act (mounted harnesses re-render on it). */
+function setStoreElements(elements: TimelineElement[]): void {
+ act(() => usePlayerStore.getState().setElements(elements));
+}
+
+// Store keys follow buildTimelineElementKey's `<sourceFile>#<domId>` branch —
+// the same shape deriveTimelineStoreKey produces for reorder entries.
+function storeEl(domId: string, track: number, start: number, duration: number): TimelineElement {
+ return {
+ id: domId,
+ key: `index.html#${domId}`,
+ tag: "video",
+ start,
+ duration,
+ track,
+ domId,
+ };
+}
+
+type ReorderEntries = Array<{
+ element: HTMLElement;
+ zIndex: number;
+ id?: string;
+ selector?: string;
+ sourceFile: string;
+ key?: string;
+}>;
+
+interface HarnessApi {
+ commitZ: (entries: ReorderEntries, coalesceKey: string, action: string) => Promise<unknown>;
+ mirror: (input: MirrorZOrderInput) => Promise<boolean>;
+}
+
+/**
+ * Mount the REAL wiring pair PreviewOverlays composes — handleDomZIndexReorderCommit
+ * (z persist) + useCanvasZOrderTimelineMirror (lane mirror) — over a shared,
+ * real editHistory reducer so the undo-fold assertion exercises the actual
+ * pushEditHistoryEntry coalescing:
+ *
+ * - the z sink mimics commitDomEditPatchBatches' recordEdit call verbatim
+ * (kind "manual", options.coalesceKey — see useDomEditCommits.ts), and
+ * - the move sink mimics persistTimelineBatchEdit → saveProjectFilesWithHistory
+ * (kind "timeline", the coalesceKey forwarded through onMoveElements — see
+ * timelineEditingHelpers.ts / studioFileHistory.ts),
+ *
+ * with a deterministic clock inside the reducer's 300ms coalesce window.
+ */
+function mountMirrorHarness(history: {
+ state: EditHistoryState;
+ now: () => number;
+ fileContent: { current: string };
+ moveCoalesceKeys: string[];
+}) {
+ const record = (
+ label: string,
+ kind: "manual" | "timeline",
+ coalesceKey: string,
+ coalesceMs: number | undefined,
+ after: string,
+ ) => {
+ const entry = buildEditHistoryEntry({
+ id: `e-${history.now()}`,
+ projectId: "p",
+ label,
+ kind,
+ coalesceKey,
+ coalesceMs,
+ now: history.now(),
+ files: { "index.html": { before: history.fileContent.current, after } },
+ });
+ history.fileContent.current = after;
+ history.state = pushEditHistoryEntry(history.state, entry);
+ };
+
+ const onMoveElements: TimelineEditCallbacks["onMoveElements"] = (
+ _edits,
+ coalesceKey,
+ _operation,
+ coalesceMs,
+ ) => {
+ history.moveCoalesceKeys.push(coalesceKey ?? "<none>");
+ record("Move timeline clips", "timeline", coalesceKey ?? "<none>", coalesceMs, "C-move");
+ };
+
+ const api: Partial<HarnessApi> = {};
+ function Harness() {
+ const { handleDomZIndexReorderCommit } = useElementLifecycleOps(
+ makeLifecycleOpsParams({
+ commitDomEditPatchBatches: async (_batches, options) => {
+ record(options.label, "manual", options.coalesceKey, options.coalesceMs, "B-z");
+ return { durable: true, allMatched: true, changed: true };
+ },
+ }),
+ );
+ api.commitZ = handleDomZIndexReorderCommit;
+ api.mirror = useCanvasZOrderTimelineMirror();
+ return null;
+ }
+ mountReactHarness(
+ <TimelineEditProvider value={{ onMoveElements }}>
+ <Harness />
+ </TimelineEditProvider>,
+ );
+ return api as HarnessApi;
+}
+
+function makeHistory() {
+ let tick = 1000;
+ return {
+ state: createEmptyEditHistory(),
+ // Deterministic clock: consecutive records land 400ms apart — PAST the
+ // reducer's default 300ms coalesce window, as in the live flow where the
+ // mirror is dispatched only after the z persist's server round-trip
+ // resolves (real network latency exceeds 300ms). The fold must therefore
+ // ride the gesture's explicit coalesceMs window, not the default.
+ now: () => (tick += 400),
+ fileContent: { current: "A-original" },
+ moveCoalesceKeys: [] as string[],
+ };
+}
+
+function mountMirrorOnlyHarness(
+ onMoveElements: TimelineEditCallbacks["onMoveElements"],
+): Pick<HarnessApi, "mirror"> {
+ const api: Partial<HarnessApi> = {};
+ function Harness() {
+ api.mirror = useCanvasZOrderTimelineMirror();
+ return null;
+ }
+ mountReactHarness(
+ <TimelineEditProvider value={{ onMoveElements }}>
+ <Harness />
+ </TimelineEditProvider>,
+ );
+ const mirror = api.mirror;
+ if (!mirror) throw new Error("mirror harness failed to mount");
+ return { mirror };
+}
+
+function domTarget(id: string): HTMLElement {
+ const el = document.createElement("div");
+ el.id = id;
+ document.body.appendChild(el);
+ return el;
+}
+
+describe("useCanvasZOrderTimelineMirror", () => {
+ it("folds the z write and the mirrored lane write into ONE undo entry (shared coalesce key)", async () => {
+ // Timeline: t on lane 2, b on lane 1 (the crossed neighbor), a on lane 0
+ // free over t's span → bring-forward mirrors to a kind:"move" onto lane 0.
+ setStoreElements([storeEl("a", 0, 20, 5), storeEl("b", 1, 0, 10), storeEl("t", 2, 0, 10)]);
+ const history = makeHistory();
+ const api = mountMirrorHarness(history);
+
+ const target = domTarget("t");
+ const entries: ReorderEntries = [
+ { element: target, zIndex: 7, id: "t", sourceFile: "index.html", key: "index.html#t" },
+ ];
+ const coalesceKey = zReorderCoalesceKey(entries, "bring-forward");
+ // Gesture-unique key: action + ids + a per-call gesture sequence, so two
+ // SEPARATE actions on the same selection never share a key (see the
+ // two-gestures test below) while this gesture's two records do.
+ expect(coalesceKey).toMatch(/^z-reorder:bring-forward:t:g\d+$/);
+
+ await act(async () => {
+ // The PreviewOverlays wiring: z commit first, mirror after it resolves,
+ // BOTH with the same key.
+ await api.commitZ(entries, coalesceKey, "bring-forward");
+ const mirrored = await api.mirror({
+ selectionKey: "index.html#t",
+ action: "bring-forward",
+ crossed: domTarget("b"),
+ sourceFile: "index.html",
+ coalesceKey,
+ });
+ expect(mirrored).toBe(true);
+ });
+
+ // The move persist received the EXACT z coalesce key…
+ expect(history.moveCoalesceKeys).toEqual([coalesceKey]);
+ // …and the real reducer folded the two records into one undo entry spanning
+ // pre-z "before" → post-move "after". One Cmd+Z reverts both writes.
+ expect(history.state.undo).toHaveLength(1);
+ expect(history.state.undo[0].files["index.html"]).toMatchObject({
+ before: "A-original",
+ after: "C-move",
+ });
+ // Timeline UI reflects the lane change without a reload: optimistic store update.
+ const t = usePlayerStore.getState().elements.find((e) => e.key === "index.html#t");
+ expect(t?.track).toBe(0);
+ });
+
+ it("two SEPARATE gestures on the same selection produce TWO undo entries (distinct keys)", async () => {
+ // Two consecutive gestures on the same element: each mints its own coalesce
+ // key (gesture sequence), so even an unbounded per-gesture window must never
+ // merge distinct user actions into one undo step.
+ setStoreElements([storeEl("t", 0, 0, 10), storeEl("b", 1, 0, 10)]);
+ const history = makeHistory();
+ const api = mountMirrorHarness(history);
+
+ const target = domTarget("t");
+ const entries: ReorderEntries = [
+ { element: target, zIndex: 7, id: "t", sourceFile: "index.html", key: "index.html#t" },
+ ];
+
+ // Identical action + identical selection still mints a fresh key per call.
+ expect(zReorderCoalesceKey(entries, "send-backward")).not.toBe(
+ zReorderCoalesceKey(entries, "send-backward"),
+ );
+
+ const keys: string[] = [];
+ // Gesture 1: t (top) sent backward past b → back-to-back, no free lane in
+ // the bounded interval → insert immediately below b (t and b swap lanes).
+ // Gesture 2: t brought forward past b → insert immediately above b (swap
+ // back). Both gestures mirror (lane move persists), so each records a
+ // z+move pair.
+ const gestures = [
+ { action: "send-backward" as const, crossedId: "b" },
+ { action: "bring-forward" as const, crossedId: "b" },
+ ];
+ for (const { action, crossedId } of gestures) {
+ const coalesceKey = zReorderCoalesceKey(entries, action);
+ keys.push(coalesceKey);
+ await act(async () => {
+ await api.commitZ(entries, coalesceKey, action);
+ const mirrored = await api.mirror({
+ selectionKey: "index.html#t",
+ action,
+ crossed: domTarget(crossedId),
+ sourceFile: "index.html",
+ coalesceKey,
+ });
+ expect(mirrored).toBe(true);
+ });
+ }
+
+ expect(keys[0]).not.toBe(keys[1]); // fresh key per gesture
+ // Each gesture folded its own z+move pair, but the two gestures stayed apart.
+ expect(history.state.undo).toHaveLength(2);
+ expect(history.moveCoalesceKeys).toEqual(keys);
+ });
+
+ it("z-only actions leave the timeline untouched (resolver null → single z undo entry)", async () => {
+ // t has NO overlapping neighbor above → bring-forward has no lane mirror.
+ setStoreElements([storeEl("a", 0, 20, 5), storeEl("t", 1, 0, 10)]);
+ const history = makeHistory();
+ const api = mountMirrorHarness(history);
+
+ const entries: ReorderEntries = [
+ {
+ element: domTarget("t"),
+ zIndex: 3,
+ id: "t",
+ sourceFile: "index.html",
+ key: "index.html#t",
+ },
+ ];
+ const coalesceKey = zReorderCoalesceKey(entries, "bring-forward");
+ await act(async () => {
+ await api.commitZ(entries, coalesceKey, "bring-forward");
+ const mirrored = await api.mirror({
+ selectionKey: "index.html#t",
+ action: "bring-forward",
+ crossed: null,
+ sourceFile: "index.html",
+ coalesceKey,
+ });
+ expect(mirrored).toBe(false);
+ });
+
+ expect(history.moveCoalesceKeys).toEqual([]); // no lane persist dispatched
+ expect(history.state.undo).toHaveLength(1); // just the z entry
+ const t = usePlayerStore.getState().elements.find((e) => e.key === "index.html#t");
+ expect(t?.track).toBe(1); // lane unchanged
+ });
+
+ it("elements that are not timeline clips resolve false without touching the persist path", async () => {
+ setStoreElements([storeEl("a", 0, 0, 10)]);
+ const history = makeHistory();
+ const api = mountMirrorHarness(history);
+ const mirrored = await act(async () =>
+ api.mirror({
+ selectionKey: undefined, // canvas-only decoration: no timeline key
+ action: "send-to-back",
+ crossed: null,
+ sourceFile: "index.html",
+ coalesceKey: "z-reorder:send-to-back:x",
+ }),
+ );
+ expect(mirrored).toBe(false);
+ expect(history.moveCoalesceKeys).toEqual([]);
+ });
+
+ it("maps the crossed neighbor to its timeline key and rebases expanded sub-comp children", async () => {
+ // t is an expanded sub-comp child (expandedParentStart 5, absolute start 5):
+ // the mirror must forward its persist in LOCAL time (start 0), the same
+ // rebase a timeline lane drag applies (forwardRebasedTimelineMoveElements).
+ setStoreElements([
+ {
+ ...storeEl("a", 0, 25, 5),
+ sourceFile: "sub.html",
+ key: "sub.html#a",
+ expandedParentStart: 5,
+ },
+ {
+ ...storeEl("b", 1, 5, 10),
+ sourceFile: "sub.html",
+ key: "sub.html#b",
+ expandedParentStart: 5,
+ },
+ {
+ ...storeEl("t", 2, 5, 10),
+ sourceFile: "sub.html",
+ key: "sub.html#t",
+ expandedParentStart: 5,
+ },
+ ]);
+ const edits: Array<{ element: TimelineElement; updates: { start: number; track: number } }> =
+ [];
+ const onMoveElements: TimelineEditCallbacks["onMoveElements"] = (batch) => {
+ edits.push(...batch);
+ };
+ const { mirror } = mountMirrorOnlyHarness(onMoveElements);
+
+ const mirrored = await act(async () =>
+ mirror({
+ selectionKey: "sub.html#t",
+ action: "bring-forward",
+ // The crossed sibling maps to sub.html#b via its DOM id + sourceFile —
+ // the same derivation reorder entries use (deriveTimelineStoreKey).
+ crossed: domTarget("b"),
+ sourceFile: "sub.html",
+ coalesceKey: "z-reorder:bring-forward:t",
+ }),
+ );
+ expect(mirrored).toBe(true);
+ expect(edits).toHaveLength(1);
+ // Rebased to sub-comp local coords: absolute 5 − parent start 5 = 0.
+ expect(edits[0].element.start).toBe(0);
+ expect(edits[0].updates).toMatchObject({ start: 0, track: 0 });
+ });
+
+ it("maps a cross-file duplicate selector to the source-scoped crossed occurrence", async () => {
+ setStoreElements([
+ {
+ id: "scene.html:.sub:0",
+ key: "scene.html:.sub:0",
+ tag: "div",
+ start: 20,
+ duration: 5,
+ track: 0,
+ selector: ".sub",
+ selectorIndex: 0,
+ sourceFile: "scene.html",
+ },
+ {
+ id: "scene.html:.sub:1",
+ key: "scene.html:.sub:1",
+ tag: "div",
+ start: 0,
+ duration: 10,
+ track: 1,
+ selector: ".sub",
+ selectorIndex: 1,
+ sourceFile: "scene.html",
+ },
+ {
+ ...storeEl("t", 2, 0, 10),
+ key: "scene.html#t",
+ sourceFile: "scene.html",
+ },
+ ]);
+ const edits: Array<{ element: TimelineElement; updates: { start: number; track: number } }> =
+ [];
+ const onMoveElements: TimelineEditCallbacks["onMoveElements"] = (batch) => {
+ edits.push(...batch);
+ };
+ const { mirror } = mountMirrorOnlyHarness(onMoveElements);
+
+ // This root-file duplicate precedes the scene nodes in the flattened preview
+ // DOM. It must not offset scene.html's selector indices.
+ const rootDuplicate = document.createElement("div");
+ rootDuplicate.className = "sub";
+ document.body.appendChild(rootDuplicate);
+ const scene = document.createElement("div");
+ scene.setAttribute("data-composition-id", "scene");
+ scene.setAttribute("data-composition-file", "scene.html");
+ document.body.appendChild(scene);
+ const first = document.createElement("div");
+ first.className = "sub";
+ scene.appendChild(first);
+ const crossed = document.createElement("div");
+ crossed.className = "sub";
+ scene.appendChild(crossed);
+
+ const mirrored = await act(async () =>
+ mirror({
+ selectionKey: "scene.html#t",
+ action: "bring-forward",
+ crossed,
+ sourceFile: "scene.html",
+ coalesceKey: "z-reorder:bring-forward:t",
+ }),
+ );
+
+ expect(mirrored).toBe(true);
+ expect(edits).toHaveLength(1);
+ expect(edits[0].updates.track).toBe(0);
+ });
+});
diff --git a/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.ts b/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.ts
new file mode 100644
index 0000000000..994e58da87
--- /dev/null
+++ b/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.ts
@@ -0,0 +1,191 @@
+import { useCallback, useRef } from "react";
+import { usePlayerStore } from "../../player";
+import { useExpandedTimelineElements } from "../../player/hooks/useExpandedTimelineElements";
+import { useTimelineEditContextOptional } from "../../contexts/TimelineEditContext";
+import {
+ displayTrackOrder,
+ resolveRepositionLaneMove,
+ resolveZMirrorLaneMove,
+ type ZMirrorAction,
+ type ZMirrorLaneMove,
+} from "../../player/components/timelineZMirror";
+import type { TimelineElement } from "../../player/store/playerStore";
+import { commitZMirrorLaneMove } from "../../player/components/timelineClipDragCommit";
+import { deriveTimelineStoreKey } from "../../player/lib/timelineElementHelpers";
+import { buildStableSelector, getSelectorIndex } from "../editor/domEditingDom";
+import { useStudioShellContextOptional } from "../../contexts/StudioContext";
+import { forwardRebasedTimelineMoveElements } from "./TimelinePane";
+
+export interface MirrorZOrderInput {
+ /** Timeline store key of the element the menu acted on (entry.key), if any. */
+ selectionKey: string | undefined;
+ action: ZMirrorAction;
+ /** Sibling a forward/backward step moved past (from resolveCrossedNeighbor). */
+ crossed: HTMLElement | null;
+ /** Source file of the selection — siblings share it (same document). */
+ sourceFile: string;
+ /** The z persist's coalesce key (zReorderCoalesceKey) — REQUIRED so the lane
+ * write folds into the same undo entry as the z write. */
+ coalesceKey: string;
+}
+
+/**
+ * Mirror a successful canvas z-order menu action into a timeline LANE move.
+ *
+ * The caller (PreviewOverlays) invokes the returned callback AFTER the z commit
+ * resolved — serializing the two same-file writes, exactly like the lane-drag's
+ * move→z ordering (see persistMoveEdits' doc) — and with the SAME coalesce key
+ * the z persist recorded, so editHistory folds both records into one undo entry.
+ * Because the z round-trip puts a real-network gap between the two records, the
+ * lane persist carries an unbounded per-gesture coalesce window (see
+ * commitZMirrorLaneMove) — the shared key is unique per gesture
+ * (zReorderCoalesceKey's gesture seq), so the fold stays gesture-scoped.
+ *
+ * Element source: `useExpandedTimelineElements()` — the same expanded display
+ * set the Timeline renders and the resolver expects (post-normalizeToZones
+ * lanes, expanded sub-comp children on their synthetic rows). No new expansion
+ * is built here.
+ *
+ * The mirror persists through the SAME machinery as a timeline lane drag
+ * (commitZMirrorLaneMove → persistMoveEdits → onMoveElements, with expanded
+ * children rebased to local coords via forwardRebasedTimelineMoveElements) —
+ * optimistic store update + rollback included, so the timeline reflects the
+ * lane change without a reload. The deps below deliberately OMIT
+ * `readZIndex`/`onStackingPatches`: the lane→z stacking sync
+ * (syncStackingForEdit) must not fire and recompute the z values the user just
+ * set — commitZMirrorLaneMove never calls it, and without these deps it would
+ * no-op even if called.
+ *
+ * Resolves `true` when a lane move persisted, `false` for z-only actions (no
+ * timeline mirror applies) or a rolled-back persist.
+ */
+export function useCanvasZOrderTimelineMirror(): (input: MirrorZOrderInput) => Promise<boolean> {
+ const commitMirrorMove = useMirrorLaneMoveCommit();
+ const activeCompPath = useStudioShellContextOptional()?.activeCompPath ?? null;
+
+ return useCallback(
+ (input: MirrorZOrderInput) =>
+ commitMirrorMove(input.selectionKey, input.coalesceKey, (element, els) => {
+ // Map the crossed neighbor to its timeline key the same way z-reorder
+ // entries get theirs (siblingZIndexEntry): DOM id, else stable selector
+ // WITH its selector index, scoped to the selection's source file. The
+ // index matters: class selectors are duplicated across clips (.sub),
+ // and a key derived without it resolves to occurrence 0 — a DIFFERENT
+ // clip — silently mirroring against the wrong neighbor.
+ const crossedSelector = input.crossed ? buildStableSelector(input.crossed) : undefined;
+ const crossedKey = input.crossed
+ ? deriveTimelineStoreKey({
+ domId: input.crossed.id || undefined,
+ selector: crossedSelector,
+ selectorIndex: getSelectorIndex(
+ input.crossed.ownerDocument,
+ input.crossed,
+ crossedSelector,
+ input.sourceFile,
+ activeCompPath,
+ ),
+ sourceFile: input.sourceFile,
+ })
+ : null;
+ return resolveZMirrorLaneMove({ action: input.action, element, elements: els, crossedKey });
+ }),
+ [commitMirrorMove, activeCompPath],
+ );
+}
+
+export interface LayerReorderMirrorInput {
+ /** Timeline store key of the dragged layer (entry.key), if any. */
+ selectionKey: string | undefined;
+ /** Reordered sibling keys in DESIRED render order, bottom→top (null = no
+ * timeline presence) — see resolveRepositionLaneMove. */
+ desiredOrderKeys: ReadonlyArray<string | null>;
+ /** The z persist's coalesce key — REQUIRED so the lane write folds into the
+ * same undo entry as the z write. */
+ coalesceKey: string;
+}
+
+/**
+ * Mirror a Layers-panel drag (arbitrary reposition, possibly jumping several
+ * siblings) into a timeline lane move — the "equal jump". Identical plumbing,
+ * serialization, and undo-fold contract as {@link useCanvasZOrderTimelineMirror};
+ * only the resolver differs (resolveRepositionLaneMove's between-new-neighbors
+ * rule instead of the menu's four fixed actions).
+ */
+export function useLayerReorderTimelineMirror(): (
+ input: LayerReorderMirrorInput,
+) => Promise<boolean> {
+ const commitMirrorMove = useMirrorLaneMoveCommit();
+
+ return useCallback(
+ (input: LayerReorderMirrorInput) =>
+ commitMirrorMove(input.selectionKey, input.coalesceKey, (element, els) =>
+ resolveRepositionLaneMove({
+ element,
+ elements: els,
+ desiredOrderKeys: input.desiredOrderKeys,
+ }),
+ ),
+ [commitMirrorMove],
+ );
+}
+
+/**
+ * Shared commit plumbing for both mirrors: resolve the selection key against
+ * the expanded display set, run the caller's resolver, and persist the lane
+ * move through commitZMirrorLaneMove with the same deps + undo-fold contract.
+ * Resolves `true` when a lane move persisted, `false` for z-only actions (no
+ * timeline mirror applies) or a rolled-back persist.
+ */
+function useMirrorLaneMoveCommit(): (
+ selectionKey: string | undefined,
+ coalesceKey: string,
+ resolveMove: (element: TimelineElement, elements: TimelineElement[]) => ZMirrorLaneMove,
+) => Promise<boolean> {
+ const elements = useExpandedTimelineElements();
+ const elementsRef = useRef(elements);
+ elementsRef.current = elements;
+ const { onMoveElements } = useTimelineEditContextOptional();
+
+ return useCallback(
+ (selectionKey, coalesceKey, resolveMove) => {
+ const els = elementsRef.current;
+ const element = selectionKey ? els.find((e) => (e.key ?? e.id) === selectionKey) : undefined;
+ // Not a timeline clip (canvas-only decoration) → z-only action, unchanged.
+ if (!element) return Promise.resolve(false);
+
+ const move = resolveMove(element, els);
+ if (!move) return Promise.resolve(false);
+
+ return commitZMirrorLaneMove(
+ element,
+ move,
+ {
+ elements: els,
+ trackOrder: displayTrackOrder(els),
+ updateElement: (key, updates) => usePlayerStore.getState().updateElement(key, updates),
+ onMoveElements: onMoveElements
+ ? (edits, coalesceKey2, operation, coalesceMs) =>
+ forwardRebasedTimelineMoveElements(
+ edits,
+ coalesceKey2,
+ operation,
+ onMoveElements,
+ coalesceMs,
+ )
+ : undefined,
+ // NO readZIndex / onStackingPatches: see the hook doc — the lane→z
+ // stacking sync must not re-trigger and fight the just-set z values.
+ },
+ coalesceKey,
+ // Unbounded fold window: this record lands only AFTER the z persist's
+ // server round-trip resolved, so the gap between the gesture's two
+ // records exceeds editHistory's 300ms default under real latency and
+ // the fold would silently split into two undo entries. The shared key
+ // is unique per gesture (zReorderCoalesceKey's gesture seq), so the
+ // unbounded window can never merge two distinct user actions.
+ Number.POSITIVE_INFINITY,
+ );
+ },
+ [onMoveElements],
+ );
+}
diff --git a/packages/studio/src/components/nle/useTimelineEditCallbacks.ts b/packages/studio/src/components/nle/useTimelineEditCallbacks.ts
index ec6f9ff725..7413aa18a4 100644
--- a/packages/studio/src/components/nle/useTimelineEditCallbacks.ts
+++ b/packages/studio/src/components/nle/useTimelineEditCallbacks.ts
@@ -22,6 +22,7 @@ export interface TimelineEditCallbackDeps {
edits: Array<{ element: TimelineElement; updates: Pick<TimelineElement, "start" | "track"> }>,
coalesceKey?: string,
operation?: TimelineMoveOperation,
+ coalesceMs?: number,
) => Promise<void> | void;
handleTimelineElementResize: (
element: TimelineElement,
diff --git a/packages/studio/src/components/nle/zLaneGesture.test.ts b/packages/studio/src/components/nle/zLaneGesture.test.ts
new file mode 100644
index 0000000000..6ee0e44458
--- /dev/null
+++ b/packages/studio/src/components/nle/zLaneGesture.test.ts
@@ -0,0 +1,176 @@
+import { describe, expect, it, vi } from "vitest";
+import { runLaneZGesture, runZLaneGesture } from "./zLaneGesture";
+
+const durable = { durable: true, allMatched: true, changed: true };
+
+function deferred<T>() {
+ let resolve!: (v: T) => void;
+ let reject!: (e: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+describe("runZLaneGesture", () => {
+ it("runs the mirror after a durable z commit and resolves its result", async () => {
+ const order: string[] = [];
+ const result = await runZLaneGesture({
+ commitZ: async () => {
+ order.push("z");
+ return durable;
+ },
+ mirror: async () => {
+ order.push("mirror");
+ return true;
+ },
+ });
+ expect(result).toBe(true);
+ expect(order).toEqual(["z", "mirror"]);
+ });
+
+ it("skips the mirror when the z commit reports unmatched targets", async () => {
+ const mirror = vi.fn(async () => true);
+ const result = await runZLaneGesture({
+ commitZ: async () => ({ durable: false, allMatched: false, changed: true }),
+ mirror,
+ });
+ expect(result).toBe(false);
+ expect(mirror).not.toHaveBeenCalled();
+ });
+
+ it("still mirrors on a void resolution (empty-entries commit path)", async () => {
+ const mirror = vi.fn(async () => true);
+ await runZLaneGesture({ commitZ: async () => undefined, mirror });
+ expect(mirror).toHaveBeenCalledTimes(1);
+ });
+
+ it("serializes gestures: B's z phase waits for A's mirror phase", async () => {
+ const order: string[] = [];
+ const aMirrorGate = deferred<void>();
+
+ const a = runZLaneGesture({
+ commitZ: async () => {
+ order.push("A:z");
+ return durable;
+ },
+ mirror: async () => {
+ await aMirrorGate.promise;
+ order.push("A:mirror");
+ return true;
+ },
+ });
+ const b = runZLaneGesture({
+ commitZ: async () => {
+ order.push("B:z");
+ return durable;
+ },
+ mirror: async () => {
+ order.push("B:mirror");
+ return true;
+ },
+ });
+
+ // Give B every chance to start early — it must not.
+ await new Promise((r) => setTimeout(r, 10));
+ expect(order).toEqual(["A:z"]);
+
+ aMirrorGate.resolve();
+ await Promise.all([a, b]);
+ expect(order).toEqual(["A:z", "A:mirror", "B:z", "B:mirror"]);
+ });
+
+ it("holds a lane→z gesture until an overlapping z→lane gesture fully settles", async () => {
+ const order: string[] = [];
+ const mirrorGate = deferred<void>();
+ const zFirst = runZLaneGesture({
+ commitZ: async () => {
+ order.push("z-first:z");
+ return durable;
+ },
+ mirror: async () => {
+ order.push("z-first:lane-start");
+ await mirrorGate.promise;
+ order.push("z-first:lane-end");
+ return true;
+ },
+ });
+ const laneFirst = runLaneZGesture({
+ commitLane: async () => {
+ order.push("lane-first:lane");
+ return true;
+ },
+ commitZ: async () => {
+ order.push("lane-first:z");
+ },
+ });
+
+ await Promise.resolve();
+ expect(order).toEqual(["z-first:z", "z-first:lane-start"]);
+ mirrorGate.resolve();
+ await Promise.all([zFirst, laneFirst]);
+ expect(order).toEqual([
+ "z-first:z",
+ "z-first:lane-start",
+ "z-first:lane-end",
+ "lane-first:lane",
+ "lane-first:z",
+ ]);
+ });
+
+ it("holds a z→lane gesture until an overlapping lane→z gesture fully settles", async () => {
+ const order: string[] = [];
+ const zGate = deferred<void>();
+ const laneFirst = runLaneZGesture({
+ commitLane: async () => {
+ order.push("lane-first:lane");
+ return true;
+ },
+ commitZ: async () => {
+ order.push("lane-first:z-start");
+ await zGate.promise;
+ order.push("lane-first:z-end");
+ },
+ });
+ const zFirst = runZLaneGesture({
+ commitZ: async () => {
+ order.push("z-first:z");
+ return durable;
+ },
+ mirror: async () => {
+ order.push("z-first:lane");
+ return true;
+ },
+ });
+
+ await Promise.resolve();
+ expect(order).toEqual(["lane-first:lane", "lane-first:z-start"]);
+ zGate.resolve();
+ await Promise.all([laneFirst, zFirst]);
+ expect(order).toEqual([
+ "lane-first:lane",
+ "lane-first:z-start",
+ "lane-first:z-end",
+ "z-first:z",
+ "z-first:lane",
+ ]);
+ });
+
+ it("a failed gesture rejects its caller but never wedges the queue", async () => {
+ const boom = new Error("z failed");
+ const failed = runZLaneGesture({
+ commitZ: async () => {
+ throw boom;
+ },
+ mirror: async () => true,
+ });
+ await expect(failed).rejects.toBe(boom);
+
+ const next = await runZLaneGesture({
+ commitZ: async () => durable,
+ mirror: async () => true,
+ });
+ expect(next).toBe(true);
+ });
+});
diff --git a/packages/studio/src/components/nle/zLaneGesture.ts b/packages/studio/src/components/nle/zLaneGesture.ts
new file mode 100644
index 0000000000..711fbd9760
--- /dev/null
+++ b/packages/studio/src/components/nle/zLaneGesture.ts
@@ -0,0 +1,77 @@
+import type { DomEditPatchBatchesResult } from "../../hooks/domEditCommitTypes";
+
+/**
+ * Run one COMPLETE z→lane gesture — the z-index persist followed by its
+ * timeline lane mirror — as a single serialized transaction.
+ *
+ * Why a queue: the two phases persist through DIFFERENT pipelines (the z patch
+ * rides the DOM-edit save queue, the lane move rides the timeline/SDK move
+ * path). Each gesture orders its own phases by awaiting the z persist, but
+ * without cross-gesture serialization a second rapid gesture can land between
+ * the first gesture's phases and the interleaved file writes can clobber each
+ * other. Canvas z→lane and timeline lane→z gestures both chain through this
+ * single module-level tail, so gesture B cannot start until gesture A settled.
+ *
+ * Why the durability gate: a resolved z commit is not necessarily durable —
+ * when the server cannot match a patch target, commitDomEditPatchBatches
+ * resolves with `durable: false` (after scheduling a reload to
+ * reconverge). Mirroring a lane move onto a z state that disk never held
+ * would desync track order from what actually paints, so the mirror phase is
+ * skipped and the gesture resolves `false`.
+ *
+ * Failures never wedge the queue: a rejected gesture propagates to ITS caller
+ * while the tail continues for the next gesture.
+ */
+let gestureTail: Promise<void> | null = null;
+
+/** The single ordering owner for every gesture that crosses z/lane persistence. */
+export function serializeZLaneGesture<Result>(run: () => Promise<Result>): Promise<Result> {
+ const previous = gestureTail;
+ // Preserve synchronous optimistic updates for the first gesture. A queued
+ // gesture starts only after the preceding gesture fully settled.
+ let gesture: Promise<Result>;
+ if (previous) {
+ gesture = previous.then(run, run);
+ } else {
+ try {
+ gesture = Promise.resolve(run());
+ } catch (error) {
+ gesture = Promise.reject(error);
+ }
+ }
+ const tail = gesture.then(
+ () => undefined,
+ () => undefined,
+ );
+ gestureTail = tail;
+ void tail.then(() => {
+ if (gestureTail === tail) gestureTail = null;
+ });
+ return gesture;
+}
+
+export function runZLaneGesture(input: {
+ /** Phase 1: persist the z patch (handleDomZIndexReorderCommit). */
+ commitZ: () => Promise<DomEditPatchBatchesResult | undefined | void>;
+ /** Phase 2: mirror into a timeline lane move; only runs on a durable phase 1. */
+ mirror: () => Promise<boolean>;
+}): Promise<boolean> {
+ const run = async (): Promise<boolean> => {
+ const result = await input.commitZ();
+ if (result && !result.durable) return false;
+ return input.mirror();
+ };
+ return serializeZLaneGesture(run);
+}
+
+/** Run one lane→z gesture under the same owner as canvas z→lane gestures. */
+export function runLaneZGesture(input: {
+ commitLane: () => Promise<boolean>;
+ commitZ: () => Promise<void>;
+}): Promise<boolean> {
+ return serializeZLaneGesture(async () => {
+ if (!(await input.commitLane())) return false;
+ await input.commitZ();
+ return true;
+ });
+}
diff --git a/packages/studio/src/hooks/domEditCommitTypes.ts b/packages/studio/src/hooks/domEditCommitTypes.ts
index d8e762f1a1..808f50a1fa 100644
--- a/packages/studio/src/hooks/domEditCommitTypes.ts
+++ b/packages/studio/src/hooks/domEditCommitTypes.ts
@@ -11,6 +11,8 @@ export type CommitDomEditPatchBatches = (
options: {
label: string;
coalesceKey: string;
+ /** Per-entry undo coalesce window override (ms) — see EditHistoryEntry.coalesceMs. */
+ coalesceMs?: number;
/**
* Request skipping the preview iframe reload after a successful persist.
* Only honored when the persist is provably in sync with the live DOM:
@@ -20,7 +22,21 @@ export type CommitDomEditPatchBatches = (
*/
skipReload?: boolean;
},
-) => Promise<void>;
+) => Promise<DomEditPatchBatchesResult>;
+
+/**
+ * Durability report for a patch-batches commit. `durable === false` means the
+ * server could not locate at least one patch target on disk — the preview was
+ * reloaded to reconverge, and dependent follow-up writes (the z→lane timeline
+ * mirror) must be skipped. `allMatched` retains the underlying match detail.
+ * `changed === false` means no source file was written: every patch was a
+ * byte-identical no-op, or the atomic gesture was refused before any write.
+ */
+export interface DomEditPatchBatchesResult {
+ durable: boolean;
+ allMatched: boolean;
+ changed: boolean;
+}
export type PersistDomEditOperations = (
selection: DomEditSelection,
diff --git a/packages/studio/src/hooks/elementLifecycleOpsTestUtils.ts b/packages/studio/src/hooks/elementLifecycleOpsTestUtils.ts
new file mode 100644
index 0000000000..a0b86cc8f9
--- /dev/null
+++ b/packages/studio/src/hooks/elementLifecycleOpsTestUtils.ts
@@ -0,0 +1,25 @@
+import { vi } from "vitest";
+import type { useElementLifecycleOps } from "./useElementLifecycleOps";
+
+type LifecycleOpsParams = Parameters<typeof useElementLifecycleOps>[0];
+
+/**
+ * Baseline `useElementLifecycleOps` params for tests: inert stubs for every
+ * dependency, overridden per test (typically just `commitDomEditPatchBatches`).
+ * Shared by the z-reorder commit tests and the timeline-mirror harness.
+ */
+export function makeLifecycleOpsParams(
+ overrides: Partial<LifecycleOpsParams> & Pick<LifecycleOpsParams, "commitDomEditPatchBatches">,
+): LifecycleOpsParams {
+ return {
+ activeCompPath: "index.html",
+ showToast: vi.fn(),
+ writeProjectFile: vi.fn(async () => {}),
+ domEditSaveTimestampRef: { current: 0 },
+ editHistory: { recordEdit: vi.fn(async () => {}) },
+ projectIdRef: { current: null },
+ reloadPreview: vi.fn(),
+ clearDomSelection: vi.fn(),
+ ...overrides,
+ };
+}
diff --git a/packages/studio/src/hooks/fetchStubTestUtils.ts b/packages/studio/src/hooks/fetchStubTestUtils.ts
new file mode 100644
index 0000000000..1cd61d13e3
--- /dev/null
+++ b/packages/studio/src/hooks/fetchStubTestUtils.ts
@@ -0,0 +1,16 @@
+// Shared helpers for test-side `fetch` stubs (timelineTimingSync.test.ts,
+// useTimelineEditing.test.tsx): a JSON Response factory and a Request → URL
+// normalizer. Test-only module — imported exclusively from *.test.* files.
+
+export function jsonResponse(body: unknown): Response {
+ return new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+}
+
+export function requestUrl(input: Parameters<typeof fetch>[0]): string {
+ if (typeof input === "string") return input;
+ if (input instanceof URL) return input.toString();
+ return input.url;
+}
diff --git a/packages/studio/src/hooks/timelineEditingHelpers.test.ts b/packages/studio/src/hooks/timelineEditingHelpers.test.ts
index ef0ee5de91..98c263f2ad 100644
--- a/packages/studio/src/hooks/timelineEditingHelpers.test.ts
+++ b/packages/studio/src/hooks/timelineEditingHelpers.test.ts
@@ -5,6 +5,7 @@ import {
buildTimelineMoveTimingPatch,
deleteSelectedKeyframes,
extendRootDurationIfNeeded,
+ patchIframeDomTiming,
persistTimelineBatchEdit,
type PersistTimelineBatchChange,
} from "./timelineEditingHelpers";
@@ -42,7 +43,11 @@ describe("applyTimelineStackingReorder", () => {
it("commits via the change's own locator even when the element is not in timelineElements", () => {
// Sub-comp children live in the preview iframe but NOT in the top-level
// timelineElements list — the intent must be self-contained.
- const iframe = makeIframeWith(`<div id="chip" style="z-index: 1"></div>`);
+ const iframe = makeIframeWith(`
+ <div data-composition-id="scene" data-composition-file="scenes/scene.html">
+ <div id="chip" style="z-index: 1"></div>
+ </div>
+ `);
const commit = vi.fn<(entries: unknown[]) => void>();
applyTimelineStackingReorder({
@@ -96,6 +101,92 @@ describe("applyTimelineStackingReorder", () => {
expect(commit).not.toHaveBeenCalled();
});
+
+ it("resolves selectorIndex within the change's source file", () => {
+ const iframe = makeIframeWith(`
+ <div data-composition-id="root">
+ <div class="chip">root</div>
+ <div data-composition-id="scene" data-composition-file="scenes/scene.html">
+ <div class="chip">scene zero</div>
+ <div class="chip" style="z-index: 1">scene one</div>
+ </div>
+ </div>
+ `);
+ const sceneOne = iframe.contentDocument?.querySelectorAll(".chip")[2];
+ const commit = vi.fn<(entries: unknown[]) => void>();
+
+ applyTimelineStackingReorder({
+ element: el({ id: "scene-one", tag: "div" }),
+ stackingReorder: {
+ contextKey: "scene",
+ placement: { type: "above", layerId: "layer:scene:x" },
+ zIndexChanges: [
+ {
+ key: "scenes/scene.html#.chip:1",
+ zIndex: 5,
+ selector: ".chip",
+ selectorIndex: 1,
+ sourceFile: "scenes/scene.html",
+ },
+ ],
+ },
+ timelineElements: [],
+ iframe,
+ activeCompPath: "index.html",
+ commit,
+ });
+
+ const entries = commit.mock.calls[0]![0] as Array<{ element: Element }>;
+ expect(entries[0]!.element).toBe(sceneOne);
+ });
+});
+
+describe("patchIframeDomTiming", () => {
+ it("resolves selectorIndex within the element's source file", () => {
+ const iframe = makeIframeWith(`
+ <div data-composition-id="root">
+ <div class="clip" data-start="1">root</div>
+ <div data-composition-id="scene" data-composition-file="scenes/scene.html">
+ <div class="clip" data-start="2">scene zero</div>
+ <div class="clip" data-start="3">scene one</div>
+ </div>
+ </div>
+ `);
+ const clips = iframe.contentDocument?.querySelectorAll<HTMLElement>(".clip");
+ const target = el({
+ id: "scene-one",
+ tag: "div",
+ selector: ".clip",
+ selectorIndex: 1,
+ sourceFile: "scenes/scene.html",
+ });
+
+ patchIframeDomTiming(iframe, target, [["data-start", "9"]], "index.html");
+
+ expect([...clips!].map((clip) => clip.dataset.start)).toEqual(["1", "2", "9"]);
+ });
+
+ it("resolves duplicate domId within the element's source file", () => {
+ const iframe = makeIframeWith(`
+ <div data-composition-id="root">
+ <div id="card" data-start="1">root</div>
+ <div data-composition-id="scene" data-composition-file="scenes/scene.html">
+ <div id="card" data-start="2">scene</div>
+ </div>
+ </div>
+ `);
+ const cards = iframe.contentDocument?.querySelectorAll<HTMLElement>("#card");
+ const target = el({
+ id: "scene-card",
+ tag: "div",
+ domId: "card",
+ sourceFile: "scenes/scene.html",
+ });
+
+ patchIframeDomTiming(iframe, target, [["data-start", "9"]], "index.html");
+
+ expect([...cards!].map((card) => card.dataset.start)).toEqual(["1", "9"]);
+ });
});
describe("extendRootDurationIfNeeded", () => {
diff --git a/packages/studio/src/hooks/timelineEditingHelpers.ts b/packages/studio/src/hooks/timelineEditingHelpers.ts
index 6304e259da..a1ed15cfdf 100644
--- a/packages/studio/src/hooks/timelineEditingHelpers.ts
+++ b/packages/studio/src/hooks/timelineEditingHelpers.ts
@@ -13,6 +13,7 @@ import { saveProjectFilesWithHistory, type RecordEditInput } from "../utils/stud
import type { TimelineZIndexReorderCommit } from "./useTimelineEditingTypes";
import { setCompositionDurationToContent } from "../utils/timelineAssetDrop";
import { readFileContent } from "./timelineTimingSync";
+import { findElementForSelection } from "../components/editor/domEditingElement";
export { deleteSelectedKeyframes } from "./deleteSelectedKeyframes";
export { readFileContent };
function isHTMLElement(element: Element | null): element is HTMLElement {
@@ -53,12 +54,6 @@ export function applyTimelineStackingReorder(input: {
input.timelineElements.map((el) => [getTimelineElementIdentity(el), el]),
);
const doc = input.iframe?.contentDocument ?? null;
- const findLive = (domId?: string, selector?: string, selectorIndex?: number): Element | null => {
- if (!doc) return null;
- if (domId) return doc.getElementById(domId);
- if (selector) return doc.querySelectorAll(selector)[selectorIndex ?? 0] ?? null;
- return null;
- };
const commitEntries: Array<{
element: HTMLElement;
zIndex: number;
@@ -73,7 +68,15 @@ export function applyTimelineStackingReorder(input: {
const domId = change.domId ?? sibling?.domId;
const selector = change.selector ?? sibling?.selector;
const selectorIndex = change.selectorIndex ?? sibling?.selectorIndex;
- const element = findLive(domId, selector, selectorIndex);
+ const sourceFile =
+ change.sourceFile ?? sibling?.sourceFile ?? input.activeCompPath ?? "index.html";
+ const element = doc
+ ? findElementForSelection(
+ doc,
+ { id: domId, selector, selectorIndex, sourceFile },
+ input.activeCompPath,
+ )
+ : null;
if (!isHTMLElement(element)) return Promise.resolve();
if (getElementZIndex(element) === change.zIndex) continue;
commitEntries.push({
@@ -82,12 +85,15 @@ export function applyTimelineStackingReorder(input: {
id: domId ?? sibling?.id ?? change.key,
selector,
selectorIndex,
- sourceFile: change.sourceFile ?? sibling?.sourceFile ?? input.activeCompPath ?? "index.html",
+ sourceFile,
key: change.key,
});
}
if (commitEntries.length === 0) return Promise.resolve();
- return input.commit?.(commitEntries, input.coalesceKey) ?? Promise.resolve();
+ // The durability report is for gesture-level callers (z→lane mirror); this
+ // lane-drag z-sync path has no dependent follow-up write — swallow it.
+ // Promise.resolve-wrapped: a commit implementation may return void.
+ return Promise.resolve(input.commit?.(commitEntries, input.coalesceKey)).then(() => undefined);
}
export function extendRootDurationIfNeeded(newEnd: number): boolean {
const store = usePlayerStore.getState();
@@ -126,15 +132,22 @@ export type PatchTarget = NonNullable<ReturnType<typeof buildPatchTarget>>;
export function findTimelineElementInIframe(
iframe: HTMLIFrameElement | null,
element: TimelineElement,
+ activeCompositionPath: string | null = null,
): Element | null {
try {
const doc = iframe?.contentDocument;
if (!doc) return null;
- return element.domId
- ? doc.getElementById(element.domId)
- : element.selector
- ? (doc.querySelectorAll(element.selector)[element.selectorIndex ?? 0] ?? null)
- : null;
+ return findElementForSelection(
+ doc,
+ {
+ hfId: element.hfId,
+ id: element.domId,
+ selector: element.selector,
+ selectorIndex: element.selectorIndex,
+ sourceFile: element.sourceFile || activeCompositionPath || "index.html",
+ },
+ activeCompositionPath,
+ );
} catch {
return null;
}
@@ -143,9 +156,10 @@ export function patchIframeDomTiming(
iframe: HTMLIFrameElement | null,
element: TimelineElement,
attrs: Array<[string, string]>,
+ activeCompositionPath: string | null = null,
): void {
try {
- const el = findTimelineElementInIframe(iframe, element);
+ const el = findTimelineElementInIframe(iframe, element, activeCompositionPath);
if (!el) return;
for (const [name, value] of attrs) el.setAttribute(name, value);
} catch {
@@ -299,6 +313,8 @@ export interface PersistTimelineBatchEditInput {
domEditSaveTimestampRef: React.MutableRefObject<number>;
pendingTimelineEditPathRef: React.MutableRefObject<Set<string>>;
coalesceKey?: string;
+ /** Per-entry undo coalesce window override (ms) — see EditHistoryEntry.coalesceMs. */
+ coalesceMs?: number;
}
export async function persistTimelineBatchEdit(
@@ -347,6 +363,7 @@ export async function persistTimelineBatchEdit(
label: input.label,
kind: "timeline",
coalesceKey: input.coalesceKey,
+ coalesceMs: input.coalesceMs,
files,
readFile: async (path) => originals.get(path) ?? readFileContent(input.projectId, path),
writeFile: input.writeProjectFile,
diff --git a/packages/studio/src/hooks/timelineMoveAdapter.ts b/packages/studio/src/hooks/timelineMoveAdapter.ts
index 7672888e61..f5b9b2fb65 100644
--- a/packages/studio/src/hooks/timelineMoveAdapter.ts
+++ b/packages/studio/src/hooks/timelineMoveAdapter.ts
@@ -23,6 +23,7 @@ export function persistTimelineMoveEditsAtomically(
coalesceKey: string | undefined,
operation: TimelineMoveOperation,
deps: AtomicMoveDeps,
+ coalesceMs?: number,
): Promise<void> {
return deps.handleTimelineGroupMove(
edits.map(({ element, updates }) => ({
@@ -34,6 +35,6 @@ export function persistTimelineMoveEditsAtomically(
// ("timing") omit it so they stay eligible for the SDK fast path.
track: operation === "timing" ? undefined : updates.track,
})),
- { coalesceKey },
+ { coalesceKey, coalesceMs },
);
}
diff --git a/packages/studio/src/hooks/timelineTimingSync.test.ts b/packages/studio/src/hooks/timelineTimingSync.test.ts
index f0e45e3ab3..8ff9dffcf4 100644
--- a/packages/studio/src/hooks/timelineTimingSync.test.ts
+++ b/packages/studio/src/hooks/timelineTimingSync.test.ts
@@ -1,9 +1,12 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it, vi } from "vitest";
import { usePlayerStore } from "../player/store/playerStore";
+import { jsonResponse, requestUrl } from "./fetchStubTestUtils";
+import type { TimelineElement } from "../player/store/playerStore";
import {
captureDurationRollback,
finishClipTimingFallback,
+ finishGroupTimingGsapFallback,
readFileContent,
shiftGsapPositions,
} from "./timelineTimingSync";
@@ -14,38 +17,38 @@ afterEach(() => {
vi.unstubAllGlobals();
});
-function jsonResponse(body: unknown): Response {
- return new Response(JSON.stringify(body), {
- status: 200,
- headers: { "content-type": "application/json" },
- });
-}
-
-function requestUrl(input: Parameters<typeof fetch>[0]): string {
- if (typeof input === "string") return input;
- if (input instanceof URL) return input.toString();
- return input.url;
-}
-
/**
* Stub fetch: `/files/` reads return contents from the queue (repeating the
- * last entry), the GSAP-mutation endpoint answers with `gsapBody` (a thrown
- * Error rejects the call with a non-ok response).
+ * last entry), the GSAP-mutation endpoint owns the first/last contents as its
+ * atomic before/after pair, and rollback succeeds conditionally.
*/
-function stubFetch(fileContents: string[], gsapBody: unknown | Error) {
- let readIndex = 0;
+function stubFetch(
+ fileContents: string[],
+ gsapBody: unknown | Error,
+ supportsOwnedMutations = true,
+ gsapStatus = 200,
+) {
const fetchMock = vi.fn(async (input: Parameters<typeof fetch>[0]): Promise<Response> => {
const url = requestUrl(input);
+ if (url.includes("/gsap-mutation-capabilities")) {
+ return supportsOwnedMutations
+ ? jsonResponse({ atomicOwnershipPairs: true })
+ : new Response(JSON.stringify({ error: "not found" }), { status: 404 });
+ }
if (url.includes("/files/")) {
- const content = fileContents[Math.min(readIndex, fileContents.length - 1)];
- readIndex += 1;
- return jsonResponse({ content });
+ return jsonResponse({ content: fileContents.at(-1) });
+ }
+ if (url.includes("/gsap-mutation-rollback/")) {
+ return jsonResponse({ ok: true, restored: true, conflict: false });
}
if (url.includes("/gsap-mutations/")) {
if (gsapBody instanceof Error) {
return new Response(JSON.stringify({ error: gsapBody.message }), { status: 500 });
}
- return jsonResponse(gsapBody);
+ return new Response(JSON.stringify(gsapBody), {
+ status: gsapStatus,
+ headers: { "content-type": "application/json" },
+ });
}
throw new Error(`Unexpected fetch: ${url}`);
});
@@ -70,12 +73,13 @@ function clipFallbackInput(overrides: {
}
describe("finishClipTimingFallback failure domains", () => {
- it("still syncs the preview when the history-fold step fails after a successful mutation", async () => {
- // Mutation succeeds (server rewrite already on disk), but recordEdit (the
- // fold step) throws. The preview MUST still be synced — otherwise stale
- // GSAP positions stay on screen. iframe=null makes the sync observable as
- // one reloadPreview() call.
- stubFetch(["<before>", "<after>"], { mutated: true, scriptText: "tl.to()" });
+ it("rolls back and skips preview sync when history recording fails", async () => {
+ stubFetch(["<before>", "<before>", "<after>"], {
+ mutated: true,
+ scriptText: "tl.to()",
+ before: "<before>",
+ after: "<after>",
+ });
const reloadPreview = vi.fn();
const foldError = new Error("history fold failed");
const recordEdit = vi.fn(async () => {
@@ -86,12 +90,18 @@ describe("finishClipTimingFallback failure domains", () => {
await finishClipTimingFallback(clipFallbackInput({ reloadPreview, recordEdit }));
expect(recordEdit).toHaveBeenCalledTimes(1);
- expect(reloadPreview).toHaveBeenCalledTimes(1);
- // The fold error is surfaced, not swallowed silently.
+ expect(reloadPreview).not.toHaveBeenCalled();
expect(consoleError).toHaveBeenCalledWith(expect.stringContaining("GSAP"), foldError);
+ const rollback = vi
+ .mocked(fetch)
+ .mock.calls.find(([input]) => requestUrl(input).includes("/gsap-mutation-rollback/"));
+ expect(JSON.parse(String(rollback?.[1]?.body))).toEqual({
+ expected: "<after>",
+ restore: "<before>",
+ });
});
- it("skips the preview sync when the MUTATION itself fails", async () => {
+ it("reloads when the mutation endpoint fails after dispatch", async () => {
stubFetch(["<before>"], new Error("mutation blew up"));
const reloadPreview = vi.fn();
const recordEdit = vi.fn(async () => {});
@@ -100,12 +110,77 @@ describe("finishClipTimingFallback failure domains", () => {
await finishClipTimingFallback(clipFallbackInput({ reloadPreview, recordEdit }));
expect(recordEdit).not.toHaveBeenCalled();
- expect(reloadPreview).not.toHaveBeenCalled();
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
expect(consoleError).toHaveBeenCalledTimes(1);
});
+ it("reloads when a successful response omits the exact ownership pair", async () => {
+ stubFetch(["<possible-write>"], {});
+ const reloadPreview = vi.fn();
+ const recordEdit = vi.fn(async () => {});
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ await finishClipTimingFallback(clipFallbackInput({ reloadPreview, recordEdit }));
+
+ expect(recordEdit).not.toHaveBeenCalled();
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ expect(consoleError).toHaveBeenCalledWith(
+ expect.stringContaining("GSAP"),
+ expect.objectContaining({ message: "Invalid owned GSAP mutation response" }),
+ );
+ });
+
+ it("reloads when the mutation transport fails after dispatch", async () => {
+ const transportError = new TypeError("connection reset");
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: Parameters<typeof fetch>[0]) => {
+ const url = requestUrl(input);
+ if (url.includes("/gsap-mutation-capabilities")) {
+ return jsonResponse({ atomicOwnershipPairs: true });
+ }
+ if (url.includes("/gsap-mutations/")) throw transportError;
+ throw new Error(`Unexpected fetch: ${url}`);
+ }),
+ );
+ const reloadPreview = vi.fn();
+ const recordEdit = vi.fn(async () => {});
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ await finishClipTimingFallback(clipFallbackInput({ reloadPreview, recordEdit }));
+
+ expect(recordEdit).not.toHaveBeenCalled();
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ expect(consoleError).toHaveBeenCalledWith(
+ expect.stringContaining("GSAP"),
+ expect.objectContaining({ cause: transportError }),
+ );
+ });
+
+ it("reloads the preview when the mutation endpoint reports an ownership conflict", async () => {
+ stubFetch(
+ ["<successor>"],
+ { error: "file changed during GSAP mutation", conflict: true },
+ true,
+ 409,
+ );
+ const reloadPreview = vi.fn();
+ const recordEdit = vi.fn(async () => {});
+ vi.spyOn(console, "error").mockImplementation(() => {});
+
+ await finishClipTimingFallback(clipFallbackInput({ reloadPreview, recordEdit }));
+
+ expect(recordEdit).not.toHaveBeenCalled();
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ });
+
it("records the fold and syncs on the happy path", async () => {
- stubFetch(["<before>", "<after>"], { mutated: true, scriptText: "tl.to()" });
+ stubFetch(["<before>", "<before>", "<after>"], {
+ mutated: true,
+ scriptText: "tl.to()",
+ before: "<before>",
+ after: "<after>",
+ });
const reloadPreview = vi.fn();
const recordEdit = vi.fn(async () => {});
@@ -114,6 +189,51 @@ describe("finishClipTimingFallback failure domains", () => {
expect(recordEdit).toHaveBeenCalledTimes(1);
expect(reloadPreview).toHaveBeenCalledTimes(1);
});
+
+ it("preflights ownership support before sending a mutation", async () => {
+ const fetchMock = stubFetch(["<before>"], { mutated: true, scriptText: null }, false);
+ const reloadPreview = vi.fn();
+ const recordEdit = vi.fn(async () => {});
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ await finishClipTimingFallback(clipFallbackInput({ reloadPreview, recordEdit }));
+
+ expect(
+ fetchMock.mock.calls.some(([input]) => requestUrl(input).includes("/gsap-mutations/")),
+ ).toBe(false);
+ expect(recordEdit).not.toHaveBeenCalled();
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ expect(consoleError).toHaveBeenCalledWith(
+ expect.stringContaining("GSAP"),
+ expect.objectContaining({ message: "Server does not support owned GSAP mutations" }),
+ );
+ });
+
+ it("reloads and surfaces a server that violates its advertised ownership contract", async () => {
+ const fetchMock = stubFetch(["<after>"], { mutated: true, scriptText: null });
+ const reloadPreview = vi.fn();
+ const recordEdit = vi.fn(async () => {});
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ await finishClipTimingFallback(clipFallbackInput({ reloadPreview, recordEdit }));
+
+ expect(
+ fetchMock.mock.calls.some(([input]) => requestUrl(input).includes("/gsap-mutations/")),
+ ).toBe(true);
+ expect(
+ fetchMock.mock.calls.some(([input]) =>
+ requestUrl(input).includes("/gsap-mutation-rollback/"),
+ ),
+ ).toBe(false);
+ expect(recordEdit).not.toHaveBeenCalled();
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ expect(consoleError).toHaveBeenCalledWith(
+ expect.stringContaining("GSAP"),
+ expect.objectContaining({
+ message: "Invalid owned GSAP mutation response",
+ }),
+ );
+ });
});
describe("captureDurationRollback", () => {
@@ -141,10 +261,560 @@ describe("fetch URL encoding (user-influenced segments)", () => {
});
it("URI-encodes the projectId in GSAP mutation calls", async () => {
- const fetchMock = stubFetch([], { mutated: false, scriptText: null });
+ const fetchMock = stubFetch([], {
+ mutated: false,
+ scriptText: null,
+ before: "<html>",
+ after: "<html>",
+ });
await shiftGsapPositions("p one", "scenes/intro.html", "clip", 1);
expect(requestUrl(fetchMock.mock.calls[0]![0])).toBe(
"/api/projects/p%20one/gsap-mutations/scenes%2Fintro.html",
);
});
});
+
+/**
+ * Live-preview iframe stub: inline GSAP script elements plus the runtime hooks
+ * the timing rebind needs. `appendedScripts` records any script a sync path
+ * executes — the rebind-only path must record NONE — and `scriptEls` lets tests
+ * assert the original script elements were left untouched in the document.
+ */
+const LIVE_SCRIPT =
+ 'window.__timelines = window.__timelines || {}; window.__timelines["root"] = tl;';
+const LIVE_CAPTION_SCRIPT =
+ 'window.__timelines = window.__timelines || {}; window.__timelines["captions"] = capTl;';
+
+function buildLivePreviewIframe(liveScripts: string[] = [LIVE_SCRIPT]) {
+ const scriptEls = liveScripts.map((text) => {
+ const el = document.createElement("script");
+ el.textContent = text;
+ return el;
+ });
+ const container = document.createElement("div");
+ for (const el of scriptEls) container.appendChild(el);
+
+ const contentWindow = {
+ gsap: { timeline: vi.fn(), set: vi.fn() },
+ __hfForceTimelineRebind: vi.fn() as unknown,
+ __timelines: { root: { kill: vi.fn() } } as Record<string, unknown>,
+ __player: { getTime: () => 0, seek: vi.fn() },
+ __hfStudioManualEditsApply: vi.fn(),
+ };
+
+ const appendedScripts: string[] = [];
+ const realAppendChild = container.appendChild.bind(container);
+ container.appendChild = <T extends Node>(node: T): T => {
+ const result = realAppendChild(node);
+ if (node instanceof HTMLScriptElement) appendedScripts.push(node.textContent ?? "");
+ return result;
+ };
+
+ const contentDocument = {
+ querySelectorAll: (sel: string) => (sel === "script:not([src])" ? scriptEls : []),
+ createElement: (tag: string) => document.createElement(tag),
+ body: container,
+ head: document.createElement("div"),
+ };
+
+ return {
+ iframe: { contentWindow, contentDocument } as unknown as HTMLIFrameElement,
+ contentWindow,
+ container,
+ scriptEls,
+ appendedScripts,
+ };
+}
+
+describe("nothing-to-rewrite timing edits rebind in place (no script re-execution)", () => {
+ it("single clip without a domId: rebinds + seeks, executes NO script, no full reload", async () => {
+ // A selector-addressed clip (e.g. a .sub caption) has no domId, so there is
+ // no GSAP mutation to run — the timing attributes are already live-patched
+ // and __timelines is still valid, so the runtime only needs to re-derive
+ // the clip windows (rebind) and re-seek. Re-running init-style scripts
+ // (three.js setups etc.) is exactly the unsafe case this must avoid.
+ const { iframe, contentWindow, container, scriptEls, appendedScripts } =
+ buildLivePreviewIframe();
+ const reloadPreview = vi.fn();
+
+ await finishClipTimingFallback({
+ ...clipFallbackInput({ reloadPreview, recordEdit: vi.fn(async () => {}) }),
+ iframe,
+ domId: undefined,
+ });
+
+ expect(reloadPreview).not.toHaveBeenCalled();
+ expect(contentWindow.__hfForceTimelineRebind).toHaveBeenCalledTimes(1);
+ expect(contentWindow.__player.seek).toHaveBeenCalledTimes(1);
+ expect(contentWindow.__hfStudioManualEditsApply).toHaveBeenCalledTimes(1);
+ // NO script executed, the original script element untouched in place.
+ expect(appendedScripts).toHaveLength(0);
+ expect(container.contains(scriptEls[0]!)).toBe(true);
+ expect(scriptEls[0]!.textContent).toBe(LIVE_SCRIPT);
+ });
+
+ it("multi-script document (e.g. three.js + captions): rebind-only, both scripts untouched", async () => {
+ // Real compositions commonly hold heavy inline scripts (main timeline,
+ // three.js setup, captions). None of them may run twice — the rebind path
+ // must not create, remove, or re-execute any of them.
+ const { iframe, contentWindow, container, scriptEls, appendedScripts } = buildLivePreviewIframe(
+ [LIVE_SCRIPT, LIVE_CAPTION_SCRIPT],
+ );
+ const rootKill = vi.fn();
+ const captionsKill = vi.fn();
+ contentWindow.__timelines = { root: { kill: rootKill }, captions: { kill: captionsKill } };
+ const reloadPreview = vi.fn();
+
+ await finishClipTimingFallback({
+ ...clipFallbackInput({ reloadPreview, recordEdit: vi.fn(async () => {}) }),
+ iframe,
+ domId: undefined,
+ });
+
+ expect(reloadPreview).not.toHaveBeenCalled();
+ expect(appendedScripts).toHaveLength(0);
+ expect(container.contains(scriptEls[0]!)).toBe(true);
+ expect(container.contains(scriptEls[1]!)).toBe(true);
+ // The still-valid timelines are NOT killed — nothing re-registers them.
+ expect(rootKill).not.toHaveBeenCalled();
+ expect(captionsKill).not.toHaveBeenCalled();
+ expect(contentWindow.__timelines.root).toBeDefined();
+ expect(contentWindow.__timelines.captions).toBeDefined();
+ // One finalization: one seek, one rebind.
+ expect(contentWindow.__player.seek).toHaveBeenCalledTimes(1);
+ expect(contentWindow.__hfForceTimelineRebind).toHaveBeenCalledTimes(1);
+ });
+
+ it("server-confirmed no-op with an unchanged script rebinds without executing any script", async () => {
+ stubFetch([], {
+ mutated: false,
+ scriptText: LIVE_SCRIPT,
+ before: "<same>",
+ after: "<same>",
+ });
+ const { iframe, contentWindow, container, scriptEls, appendedScripts } = buildLivePreviewIframe(
+ [LIVE_SCRIPT, LIVE_CAPTION_SCRIPT],
+ );
+ const reloadPreview = vi.fn();
+
+ await finishClipTimingFallback({
+ ...clipFallbackInput({ reloadPreview, recordEdit: vi.fn(async () => {}) }),
+ iframe,
+ });
+
+ expect(reloadPreview).not.toHaveBeenCalled();
+ expect(appendedScripts).toHaveLength(0);
+ expect(scriptEls.every((script) => container.contains(script))).toBe(true);
+ expect(contentWindow.__hfForceTimelineRebind).toHaveBeenCalledTimes(1);
+ });
+
+ it("comp with ZERO GSAP scripts also rebinds in place (previously full-reloaded)", async () => {
+ // The rebind hook is installed by the runtime unconditionally — it does not
+ // depend on GSAP — so a script-less comp gets the flashless path too.
+ const { iframe, contentWindow, appendedScripts } = buildLivePreviewIframe([]);
+ const reloadPreview = vi.fn();
+
+ await finishClipTimingFallback({
+ ...clipFallbackInput({ reloadPreview, recordEdit: vi.fn(async () => {}) }),
+ iframe,
+ domId: undefined,
+ });
+
+ expect(reloadPreview).not.toHaveBeenCalled();
+ expect(contentWindow.__hfForceTimelineRebind).toHaveBeenCalledTimes(1);
+ expect(contentWindow.__player.seek).toHaveBeenCalledTimes(1);
+ expect(appendedScripts).toHaveLength(0);
+ });
+
+ it("full-reloads when the runtime rebind hook is unavailable", async () => {
+ const { iframe, contentWindow, appendedScripts } = buildLivePreviewIframe();
+ contentWindow.__hfForceTimelineRebind = undefined;
+ const reloadPreview = vi.fn();
+
+ await finishClipTimingFallback({
+ ...clipFallbackInput({ reloadPreview, recordEdit: vi.fn(async () => {}) }),
+ iframe,
+ domId: undefined,
+ });
+
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ expect(appendedScripts).toHaveLength(0);
+ });
+
+ it("still full-reloads when the server MUTATED the file but returned no script", async () => {
+ // mutated:true with scriptText:null (older server) means the live script is
+ // now STALE relative to disk — a rebind against it would show wrong
+ // positions.
+ stubFetch(["<before>", "<before>", "<after>"], {
+ mutated: true,
+ scriptText: null,
+ before: "<before>",
+ after: "<after>",
+ });
+ const { iframe, contentWindow, appendedScripts } = buildLivePreviewIframe();
+ const reloadPreview = vi.fn();
+
+ await finishClipTimingFallback({
+ ...clipFallbackInput({ reloadPreview, recordEdit: vi.fn(async () => {}) }),
+ iframe,
+ });
+
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ expect(contentWindow.__hfForceTimelineRebind).not.toHaveBeenCalled();
+ expect(appendedScripts).toHaveLength(0);
+ });
+
+ it("mutated WITH a rewritten script keeps the script-swap soft path (not rebind-only)", async () => {
+ // A genuine rewrite must re-run the REWRITTEN script — the rebind-only
+ // shortcut is reserved for the no-op case where every script is unchanged.
+ stubFetch(["<before>", "<before>", "<after>"], {
+ mutated: true,
+ scriptText: 'window.__timelines["root"] = tl2;',
+ before: "<before>",
+ after: "<after>",
+ });
+ const { iframe, contentWindow, appendedScripts } = buildLivePreviewIframe();
+ const reloadPreview = vi.fn();
+
+ await finishClipTimingFallback({
+ ...clipFallbackInput({ reloadPreview, recordEdit: vi.fn(async () => {}) }),
+ iframe,
+ });
+
+ expect(reloadPreview).not.toHaveBeenCalled();
+ expect(appendedScripts).toHaveLength(1);
+ expect(appendedScripts[0]).toContain('__timelines["root"] = tl2;');
+ expect(contentWindow.__hfForceTimelineRebind).toHaveBeenCalledTimes(1);
+ });
+
+ it("group batch where every change had nothing to rewrite (gap close over no-domId clips) rebinds in place", async () => {
+ stubFetch(["<html>"], { mutated: false, scriptText: null });
+ const { iframe, contentWindow, container, scriptEls, appendedScripts } =
+ buildLivePreviewIframe();
+ const reloadPreview = vi.fn();
+ const element = { sourceFile: "index.html" } as TimelineElement;
+
+ await finishGroupTimingGsapFallback({
+ projectId: "p1",
+ iframe,
+ reloadPreview,
+ label: "Move timeline clips",
+ errorLabel: "Failed to shift GSAP positions",
+ recordEdit: vi.fn(async () => {}) as never,
+ activeCompPath: "index.html",
+ changes: [{ element }, { element }],
+ resolveChangePath: () => "index.html",
+ // No domId → nothing to rewrite for ANY change (the gap-close blink path).
+ mutateChange: () => null,
+ });
+
+ expect(reloadPreview).not.toHaveBeenCalled();
+ expect(contentWindow.__hfForceTimelineRebind).toHaveBeenCalledTimes(1);
+ expect(contentWindow.__player.seek).toHaveBeenCalledTimes(1);
+ // No script executed, the live script element untouched.
+ expect(appendedScripts).toHaveLength(0);
+ expect(container.contains(scriptEls[0]!)).toBe(true);
+ });
+
+ it("group batch touching ANOTHER file still full-reloads even when nothing was rewritten", async () => {
+ stubFetch(["<html>"], { mutated: false, scriptText: null });
+ const { iframe, contentWindow, appendedScripts } = buildLivePreviewIframe();
+ const reloadPreview = vi.fn();
+
+ await finishGroupTimingGsapFallback({
+ projectId: "p1",
+ iframe,
+ reloadPreview,
+ label: "Move timeline clips",
+ errorLabel: "Failed to shift GSAP positions",
+ recordEdit: vi.fn(async () => {}) as never,
+ activeCompPath: "index.html",
+ changes: [
+ { element: { sourceFile: "index.html" } as TimelineElement },
+ { element: { sourceFile: "scenes/intro.html" } as TimelineElement },
+ ],
+ resolveChangePath: (el) => el.sourceFile ?? "index.html",
+ mutateChange: () => null,
+ });
+
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ expect(contentWindow.__hfForceTimelineRebind).not.toHaveBeenCalled();
+ expect(appendedScripts).toHaveLength(0);
+ });
+});
+
+function installOwnedFileServer(
+ contents: Map<string, string>,
+ options: {
+ failReadAt?: number;
+ failRollback?: boolean;
+ beforeRollback?: (path: string) => void;
+ } = {},
+) {
+ let reads = 0;
+ const rollbacks: Array<{ path: string; expected: string; restore: string; conflict: boolean }> =
+ [];
+ vi.stubGlobal(
+ "fetch",
+ // One in-memory server fixture owns capability, file, and CAS rollback
+ // routes so each transaction test observes a coherent content map.
+ // fallow-ignore-next-line complexity
+ vi.fn(async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
+ const url = requestUrl(input);
+ if (url.includes("/gsap-mutation-capabilities")) {
+ return jsonResponse({ atomicOwnershipPairs: true });
+ }
+ if (url.includes("/files/")) {
+ reads += 1;
+ if (reads === options.failReadAt) throw new Error("verification read failed");
+ const path = decodeURIComponent(url.split("/files/")[1] ?? "");
+ return jsonResponse({ content: contents.get(path) ?? "" });
+ }
+ if (url.includes("/gsap-mutation-rollback/")) {
+ const path = decodeURIComponent(url.split("/gsap-mutation-rollback/")[1] ?? "");
+ const body = JSON.parse(String(init?.body)) as { expected: string; restore: string };
+ if (options.failRollback) {
+ return new Response(JSON.stringify({ error: "rollback unavailable" }), { status: 503 });
+ }
+ options.beforeRollback?.(path);
+ const conflict = contents.get(path) !== body.expected;
+ if (!conflict) contents.set(path, body.restore);
+ rollbacks.push({ path, ...body, conflict });
+ return jsonResponse({ ok: true, restored: !conflict, conflict });
+ }
+ throw new Error(`Unexpected fetch: ${url}`);
+ }),
+ );
+ return { rollbacks, readCount: () => reads };
+}
+
+function ownedMutation(contents: Map<string, string>, path: string, before: string, after: string) {
+ contents.set(path, after);
+ return { mutated: true, scriptText: null, before, after };
+}
+
+describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {
+ const element = { sourceFile: "index.html" } as TimelineElement;
+
+ it("reverse-rolls back every successful same-file step after a late failure", async () => {
+ const contents = new Map<string, string>([["index.html", "ORIGINAL"]]);
+ const server = installOwnedFileServer(contents);
+ let clipIndex = 0;
+
+ await finishGroupTimingGsapFallback({
+ projectId: "p1",
+ iframe: buildLivePreviewIframe().iframe,
+ reloadPreview: vi.fn(),
+ label: "Move timeline clips",
+ errorLabel: "Failed to shift GSAP positions",
+ recordEdit: vi.fn(async () => {}) as never,
+ activeCompPath: "index.html",
+ changes: [{ element }, { element }, { element }],
+ resolveChangePath: () => "index.html",
+ mutateChange: async () => {
+ clipIndex += 1;
+ if (clipIndex === 1) return ownedMutation(contents, "index.html", "ORIGINAL", "STEP-1");
+ if (clipIndex === 2) return ownedMutation(contents, "index.html", "STEP-1", "STEP-2");
+ throw new Error("late failure");
+ },
+ });
+
+ expect(server.rollbacks).toEqual([
+ { path: "index.html", expected: "STEP-2", restore: "STEP-1", conflict: false },
+ { path: "index.html", expected: "STEP-1", restore: "ORIGINAL", conflict: false },
+ ]);
+ expect(contents.get("index.html")).toBe("ORIGINAL");
+ });
+
+ it("uses the endpoint's atomic before when a foreign write precedes mutation", async () => {
+ const contents = new Map<string, string>([["index.html", "FOREIGN"]]);
+ const server = installOwnedFileServer(contents);
+ let clipIndex = 0;
+
+ await finishGroupTimingGsapFallback({
+ projectId: "p1",
+ iframe: buildLivePreviewIframe().iframe,
+ reloadPreview: vi.fn(),
+ label: "Move timeline clips",
+ errorLabel: "Failed to shift GSAP positions",
+ recordEdit: vi.fn(async () => {}) as never,
+ activeCompPath: "index.html",
+ changes: [{ element }, { element }],
+ resolveChangePath: () => "index.html",
+ mutateChange: async () => {
+ clipIndex += 1;
+ if (clipIndex === 1) {
+ return ownedMutation(contents, "index.html", "FOREIGN", "FOREIGN+OWNED");
+ }
+ throw new Error("late failure");
+ },
+ });
+
+ expect(server.readCount()).toBe(0);
+ expect(server.rollbacks[0]).toEqual({
+ path: "index.html",
+ expected: "FOREIGN+OWNED",
+ restore: "FOREIGN",
+ conflict: false,
+ });
+ expect(contents.get("index.html")).toBe("FOREIGN");
+ });
+
+ it("server CAS preserves a successor that arrives as rollback starts", async () => {
+ const contents = new Map<string, string>([["index.html", "ORIGINAL"]]);
+ const server = installOwnedFileServer(contents, {
+ beforeRollback: () => contents.set("index.html", "SUCCESSOR"),
+ });
+ let clipIndex = 0;
+
+ const reloadPreview = vi.fn();
+ await finishGroupTimingGsapFallback({
+ projectId: "p1",
+ iframe: buildLivePreviewIframe().iframe,
+ reloadPreview,
+ label: "Move timeline clips",
+ errorLabel: "Failed to shift GSAP positions",
+ recordEdit: vi.fn(async () => {}) as never,
+ activeCompPath: "index.html",
+ changes: [{ element }, { element }],
+ resolveChangePath: () => "index.html",
+ mutateChange: async () => {
+ clipIndex += 1;
+ if (clipIndex === 1) return ownedMutation(contents, "index.html", "ORIGINAL", "OWNED");
+ throw new Error("late failure");
+ },
+ });
+
+ expect(server.rollbacks[0]?.conflict).toBe(true);
+ expect(contents.get("index.html")).toBe("SUCCESSOR");
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ });
+
+ it("reloads when a failed rollback request leaves owned bytes without history", async () => {
+ const contents = new Map<string, string>([["index.html", "ORIGINAL"]]);
+ installOwnedFileServer(contents, { failRollback: true });
+ const reloadPreview = vi.fn();
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
+ let clipIndex = 0;
+
+ await finishGroupTimingGsapFallback({
+ projectId: "p1",
+ iframe: buildLivePreviewIframe().iframe,
+ reloadPreview,
+ label: "Move timeline clips",
+ errorLabel: "Failed to shift GSAP positions",
+ recordEdit: vi.fn(async () => {}) as never,
+ activeCompPath: "index.html",
+ changes: [{ element }, { element }],
+ resolveChangePath: () => "index.html",
+ mutateChange: async () => {
+ clipIndex += 1;
+ if (clipIndex === 1) return ownedMutation(contents, "index.html", "ORIGINAL", "OWNED");
+ throw new Error("late failure");
+ },
+ });
+
+ expect(contents.get("index.html")).toBe("OWNED");
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ expect(consoleError).toHaveBeenCalledWith(
+ expect.stringContaining("GSAP"),
+ expect.objectContaining({ message: "Failed to restore index.html" }),
+ );
+ });
+
+ it("records first owned before and last owned after without a client snapshot", async () => {
+ const contents = new Map<string, string>([["index.html", "FOREIGN"]]);
+ const server = installOwnedFileServer(contents);
+ const recordEdit = vi.fn(async () => {});
+
+ await finishGroupTimingGsapFallback({
+ projectId: "p1",
+ iframe: buildLivePreviewIframe().iframe,
+ reloadPreview: vi.fn(),
+ label: "Move timeline clips",
+ errorLabel: "Failed to shift GSAP positions",
+ recordEdit: recordEdit as never,
+ activeCompPath: "index.html",
+ changes: [{ element }, { element }],
+ resolveChangePath: () => "index.html",
+ mutateChange: async (_change, _path) => {
+ const before = contents.get("index.html")!;
+ const after = before === "FOREIGN" ? "FOREIGN+ONE" : "FOREIGN+ONE+TWO";
+ return ownedMutation(contents, "index.html", before, after);
+ },
+ });
+
+ expect(server.readCount()).toBe(1); // final ownership verification only
+ expect(recordEdit).toHaveBeenCalledWith(
+ expect.objectContaining({
+ files: {
+ "index.html": { before: "FOREIGN", after: "FOREIGN+ONE+TWO" },
+ },
+ }),
+ );
+ });
+
+ it("rejects a discontinuous same-file chain without claiming foreign bytes", async () => {
+ const contents = new Map<string, string>([["index.html", "ORIGINAL"]]);
+ const server = installOwnedFileServer(contents);
+ const recordEdit = vi.fn(async () => {});
+ let clipIndex = 0;
+
+ const reloadPreview = vi.fn();
+ await finishGroupTimingGsapFallback({
+ projectId: "p1",
+ iframe: buildLivePreviewIframe().iframe,
+ reloadPreview,
+ label: "Move timeline clips",
+ errorLabel: "Failed to shift GSAP positions",
+ recordEdit: recordEdit as never,
+ activeCompPath: "index.html",
+ changes: [{ element }, { element }],
+ resolveChangePath: () => "index.html",
+ mutateChange: async () => {
+ clipIndex += 1;
+ if (clipIndex === 1) return ownedMutation(contents, "index.html", "ORIGINAL", "STEP-1");
+ return ownedMutation(contents, "index.html", "FOREIGN", "FOREIGN+STEP-2");
+ },
+ });
+
+ expect(recordEdit).not.toHaveBeenCalled();
+ expect(server.rollbacks).toEqual([
+ {
+ path: "index.html",
+ expected: "FOREIGN+STEP-2",
+ restore: "FOREIGN",
+ conflict: false,
+ },
+ { path: "index.html", expected: "STEP-1", restore: "ORIGINAL", conflict: true },
+ ]);
+ expect(contents.get("index.html")).toBe("FOREIGN");
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ });
+
+ it("rolls back the owned output when the history verification reread fails", async () => {
+ const contents = new Map<string, string>([["index.html", "ORIGINAL"]]);
+ const server = installOwnedFileServer(contents, { failReadAt: 1 });
+
+ await finishGroupTimingGsapFallback({
+ projectId: "p1",
+ iframe: buildLivePreviewIframe().iframe,
+ reloadPreview: vi.fn(),
+ label: "Move timeline clips",
+ errorLabel: "Failed to shift GSAP positions",
+ recordEdit: vi.fn(async () => {}) as never,
+ activeCompPath: "index.html",
+ changes: [{ element }],
+ resolveChangePath: () => "index.html",
+ mutateChange: async () => ownedMutation(contents, "index.html", "ORIGINAL", "OWNED"),
+ });
+
+ expect(server.rollbacks[0]).toEqual({
+ path: "index.html",
+ expected: "OWNED",
+ restore: "ORIGINAL",
+ conflict: false,
+ });
+ expect(contents.get("index.html")).toBe("ORIGINAL");
+ });
+});
diff --git a/packages/studio/src/hooks/timelineTimingSync.ts b/packages/studio/src/hooks/timelineTimingSync.ts
index 4db660b338..919d259a90 100644
--- a/packages/studio/src/hooks/timelineTimingSync.ts
+++ b/packages/studio/src/hooks/timelineTimingSync.ts
@@ -3,11 +3,14 @@
// 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 { applySoftReload, applySoftReloadFinalization } from "../utils/gsapSoftReload";
import { furthestClipEndFromDocument } from "../player/lib/timelineElementHelpers";
import type { RecordEditInput } from "../utils/studioFileHistory";
import { patchDocumentRootDuration } from "./timelineEditingGsap";
+class GsapPreviewConvergenceError extends Error {}
+class GsapOwnershipProtocolError extends GsapPreviewConvergenceError {}
+
export async function readFileContent(projectId: string, targetPath: string): Promise<string> {
if (targetPath.includes("\0") || targetPath.includes("..")) {
throw new Error(`Unsafe path: ${targetPath}`);
@@ -25,6 +28,49 @@ export async function readFileContent(projectId: string, targetPath: string): Pr
return data.content;
}
+/** Verify rollback ownership support before any GSAP mutation can land. */
+async function requireGsapOwnershipProtocol(projectId: string): Promise<void> {
+ const response = await fetch(
+ `/api/projects/${encodeURIComponent(projectId)}/gsap-mutation-capabilities`,
+ );
+ if (!response.ok) {
+ throw new GsapOwnershipProtocolError("Server does not support owned GSAP mutations");
+ }
+ const body = await response.json().catch(() => null);
+ if (!isRecord(body) || body.atomicOwnershipPairs !== true) {
+ throw new GsapOwnershipProtocolError("Invalid GSAP mutation capability response");
+ }
+}
+
+/** Atomically restore one GSAP mutation only while its exact output still owns
+ * the file. The server performs compare + write synchronously, eliminating the
+ * client GET→PUT window that could overwrite a successor edit. */
+async function rollbackOwnedMutation(
+ projectId: string,
+ targetPath: string,
+ expected: string,
+ restore: string,
+): Promise<"restored" | "conflict"> {
+ if (targetPath.includes("\0") || targetPath.includes("..")) {
+ throw new Error(`Unsafe path: ${targetPath}`);
+ }
+ const response = await fetch(
+ `/api/projects/${encodeURIComponent(projectId)}/gsap-mutation-rollback/${encodeURIComponent(targetPath)}`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ expected, restore }),
+ },
+ );
+ if (!response.ok) {
+ throw new Error(`Failed to restore ${targetPath}`);
+ }
+ const result = (await response.json()) as { restored?: unknown; conflict?: unknown };
+ if (result.restored === true && result.conflict === false) return "restored";
+ if (result.restored === false && result.conflict === true) return "conflict";
+ throw new Error(`Invalid restore response for ${targetPath}`);
+}
+
/** Best-effort live-iframe wrapper for patchDocumentRootDuration (see timelineEditingGsap). */
function patchIframeRootDuration(iframe: HTMLIFrameElement | null, contentEnd: number): void {
try {
@@ -34,19 +80,7 @@ function patchIframeRootDuration(iframe: HTMLIFrameElement | null, contentEnd: n
}
}
-/**
- * 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.
- */
+/** Keep the duration readout and live root aligned with optimistically patched clips. */
export function syncPreviewContentDuration(iframe: HTMLIFrameElement | null): void {
const end = furthestClipEndFromDocument(iframe?.contentDocument ?? null);
if (end > 0) {
@@ -55,14 +89,7 @@ export function syncPreviewContentDuration(iframe: HTMLIFrameElement | null): vo
}
}
-/**
- * Snapshot the store duration BEFORE an optimistic duration update
- * (extendRootDurationIfNeeded + syncPreviewContentDuration) and return a
- * rollback closure for the persist-failure path. The rollback restores BOTH
- * the store duration and the live root's `data-duration` — otherwise a failed
- * write leaves the readout/seek bar and the live root advertising a duration
- * the saved source never got. No-op when the duration never changed.
- */
+/** Restore both store and live-root duration when a timing persist fails. */
export function captureDurationRollback(iframe: HTMLIFrameElement | null): () => void {
const previousDuration = usePlayerStore.getState().duration;
return () => {
@@ -77,19 +104,38 @@ export function captureDurationRollback(iframe: HTMLIFrameElement | null): () =>
* `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.
+ * soft path can't scope) — the caller then full-reloads when `mutated`, or
+ * rebinds the runtime timing in place when nothing was rewritten (see
+ * syncTimingEditPreview).
*/
-export type GsapMutationStatus = { mutated: boolean; scriptText: string | null };
+export type GsapMutationStatus = {
+ mutated: boolean;
+ scriptText: string | null;
+ /** Atomic whole-file ownership pair returned by the mutation endpoint. */
+ before?: string;
+ after?: string;
+};
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 };
+ if (
+ !isRecord(value) ||
+ typeof value.mutated !== "boolean" ||
+ typeof value.before !== "string" ||
+ typeof value.after !== "string" ||
+ value.mutated !== (value.before !== value.after) ||
+ ("changed" in value && value.changed !== value.mutated)
+ ) {
+ throw new GsapOwnershipProtocolError("Invalid owned GSAP mutation response");
+ }
return {
- mutated: value.mutated === true || value.changed === true,
+ mutated: value.mutated,
scriptText: typeof value.scriptText === "string" ? value.scriptText : null,
+ before: value.before,
+ after: value.after,
};
}
@@ -98,6 +144,40 @@ function readMutationError(value: unknown, fallback: string): string {
return fallback;
}
+async function postGsapMutation(
+ projectId: string,
+ filePath: string,
+ mutation: Record<string, unknown>,
+ fallback: string,
+): Promise<GsapMutationStatus> {
+ let response: Response;
+ try {
+ response = await fetch(
+ `/api/projects/${encodeURIComponent(projectId)}/gsap-mutations/${encodeURIComponent(filePath)}`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(mutation),
+ },
+ );
+ } catch (error) {
+ throw new GsapPreviewConvergenceError(`${fallback}: mutation outcome unknown`, {
+ cause: error,
+ });
+ }
+ const body: unknown = await response.json().catch(() => null);
+ if (!response.ok) {
+ throw new GsapPreviewConvergenceError(readMutationError(body, fallback));
+ }
+ return readMutationStatus(body);
+}
+
+/** Re-derive live timing windows without re-executing composition scripts.
+ * Works for zero-GSAP compositions; false asks the caller to full-reload. */
+function rebindPreviewTiming(iframe: HTMLIFrameElement | null, currentTime: number): boolean {
+ return applySoftReloadFinalization(iframe, currentTime);
+}
+
/**
* Sync the live preview after a TIMING-ONLY edit (move / resize), preferring a
* soft reload over the full iframe reload that flashes every clip.
@@ -115,15 +195,34 @@ function readMutationError(value: unknown, fallback: string): string {
* 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.
+ * already applied the shift; a remount would re-flash for nothing.
+ *
+ * `mutated` is the canonical decision, regardless of whether the server echoes
+ * the unchanged script text:
+ * - `mutated: false` — nothing was rewritten because there was NOTHING TO
+ * REWRITE (the clip has no domId so no id-addressed tweens, the delta was
+ * zero, or the server confirmed a no-op). Every script is unchanged and the
+ * timing attributes are already live-patched, so (when `rebindWhenUnmutated`
+ * allows it) `rebindPreviewTiming` re-seeks + rebinds and the runtime
+ * re-derives the clip windows from the live DOM — no script re-execution,
+ * no full-reload blink. This covers comps with zero GSAP scripts too; only
+ * a missing iframe/runtime hook falls back to the full reload.
+ * - `mutated: true` with no script — the file on disk WAS rewritten but the
+ * server returned no script (older server, multi-script comp): the live
+ * script is now stale, so a rebind against it would show wrong positions →
+ * full-reload.
*/
function syncTimingEditPreview(
iframe: HTMLIFrameElement | null,
- outcome: Pick<GsapMutationStatus, "scriptText">,
+ outcome: GsapMutationStatus,
currentTime: number,
reloadPreview: () => void,
+ rebindWhenUnmutated: boolean,
): void {
+ if (!outcome.mutated && rebindWhenUnmutated) {
+ if (!rebindPreviewTiming(iframe, currentTime)) reloadPreview();
+ return;
+ }
if (!iframe || !outcome.scriptText) {
reloadPreview();
return;
@@ -140,6 +239,14 @@ async function finishTimelineTimingFallback(input: {
reloadPreview: () => void;
gsapMutation?: () => Promise<GsapMutationStatus>;
onGsapError: (error: unknown) => void;
+ /**
+ * When the mutation produced no rewrite (mutated:false, no scriptText),
+ * rebind the runtime timing in place (no script re-execution) instead of
+ * full-reloading (see syncTimingEditPreview). Callers pass false when a full
+ * reload is the only sync that reflects everything (e.g. a multi-file group
+ * edit).
+ */
+ rebindWhenUnmutated: boolean;
}): Promise<void> {
let outcome: GsapMutationStatus = { mutated: false, scriptText: null };
if (input.gsapMutation) {
@@ -147,6 +254,9 @@ async function finishTimelineTimingFallback(input: {
outcome = await input.gsapMutation();
} catch (error) {
input.onGsapError(error);
+ // Protocol and ownership conflicts mean the live iframe may no longer
+ // represent the bytes that won on disk. Converge explicitly by reloading.
+ if (error instanceof GsapPreviewConvergenceError) input.reloadPreview();
return;
}
}
@@ -155,6 +265,7 @@ async function finishTimelineTimingFallback(input: {
outcome,
usePlayerStore.getState().currentTime,
input.reloadPreview,
+ input.rebindWhenUnmutated,
);
}
@@ -162,44 +273,124 @@ async function finishTimelineTimingFallback(input: {
// outlast one GSAP server round-trip, never a real second edit.
const GSAP_HISTORY_COALESCE_MS = 10_000;
+type OwnedMutationStep = {
+ path: string;
+ before: string;
+ after: string;
+};
+
+type OwnedMutationRunner = (
+ path: string,
+ mutation: () => Promise<GsapMutationStatus> | null,
+) => Promise<GsapMutationStatus>;
+
/**
- * 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.
- *
- * Failure domains are separate: a MUTATION failure propagates (nothing was applied, so
- * the caller must skip the preview sync), but a failure in the history-FOLD step
- * (re-read / recordEdit) after a successful mutation is surfaced via `onFoldError` and
- * the mutation status is still returned — the server rewrite already landed on disk, so
- * the caller must still sync the preview or it shows stale GSAP positions.
+ * Restore successful mutation steps in reverse order through the server's
+ * atomic compare-and-restore endpoint. A conflict means a successor owns the
+ * file and is deliberately preserved. Conflicts and restore errors require a
+ * preview reload; errors are also reported through onError.
+ */
+async function rollbackMutatedFiles(
+ projectId: string,
+ ownedSteps: readonly OwnedMutationStep[],
+ onError: (error: unknown) => void,
+): Promise<"restored" | "convergence-required"> {
+ let convergenceRequired = false;
+ for (let index = ownedSteps.length - 1; index >= 0; index -= 1) {
+ const step = ownedSteps[index];
+ if (!step || step.before === step.after) continue;
+ try {
+ if (
+ (await rollbackOwnedMutation(projectId, step.path, step.after, step.before)) === "conflict"
+ ) {
+ convergenceRequired = true;
+ }
+ } catch (rollbackError) {
+ convergenceRequired = true;
+ onError(rollbackError);
+ }
+ }
+ return convergenceRequired ? "convergence-required" : "restored";
+}
+
+async function rollbackAfterFailure(
+ projectId: string,
+ ownedSteps: readonly OwnedMutationStep[],
+ onError: (error: unknown) => void,
+ originalError: unknown,
+): Promise<never> {
+ const outcome = await rollbackMutatedFiles(projectId, ownedSteps, onError);
+ if (outcome === "convergence-required") {
+ throw new GsapPreviewConvergenceError(
+ "GSAP rollback could not safely restore every owned write; preview reload required",
+ { cause: originalError },
+ );
+ }
+ throw originalError;
+}
+
+/**
+ * Fold server-owned GSAP rewrites into the preceding timing history entry.
+ * Every mutation contributes the atomic before/after pair returned by its
+ * endpoint; the first before and last after for each contiguous file chain are
+ * the only bytes this transaction may record or roll back.
*/
+// The ledger, reverse rollback, final ownership check, and history fold are one
+// transaction; extracting phases would obscure which function owns convergence.
+// fallow-ignore-next-line complexity
async function foldGsapMutationIntoHistory(input: {
projectId: string;
- paths: string[];
label: string;
coalesceKey?: string;
recordEdit: (edit: RecordEditInput) => Promise<void>;
- gsapMutation: () => Promise<GsapMutationStatus>;
- onFoldError: (error: unknown) => void;
+ gsapMutation: (runOwnedMutation: OwnedMutationRunner) => Promise<GsapMutationStatus>;
+ onRollbackError: (error: unknown) => void;
}): Promise<GsapMutationStatus> {
- const uniquePaths = [...new Set(input.paths)];
- const before = new Map<string, string>();
- // A `before`-snapshot failure propagates like a mutation failure: the mutation
- // has not run yet, so nothing landed on disk and skipping the sync is correct.
- for (const path of uniquePaths) {
- before.set(path, await readFileContent(input.projectId, path));
+ const ownedSteps: OwnedMutationStep[] = [];
+ const runOwnedMutation: OwnedMutationRunner = async (path, mutation) => {
+ const pending = mutation();
+ if (!pending) return { mutated: false, scriptText: null };
+ const status = await pending;
+ if (!status.mutated) return status;
+ if (status.before === undefined || status.after === undefined) {
+ throw new GsapOwnershipProtocolError(
+ `GSAP mutation returned no owned before/after pair for ${path}`,
+ );
+ }
+ const previous = [...ownedSteps].reverse().find((step) => step.path === path);
+ const step = { path, before: status.before, after: status.after };
+ ownedSteps.push(step);
+ // A foreign writer landed between two same-file mutation steps. The second
+ // step already wrote, so keep it in ownedSteps for reverse rollback, then
+ // fail rather than folding foreign bytes into this gesture's history.
+ if (previous && previous.after !== step.before) {
+ throw new Error(`GSAP mutation ownership chain broke for ${path}`);
+ }
+ return status;
+ };
+ let status: GsapMutationStatus;
+ try {
+ await requireGsapOwnershipProtocol(input.projectId);
+ status = await input.gsapMutation(runOwnedMutation);
+ } catch (error) {
+ return rollbackAfterFailure(input.projectId, ownedSteps, input.onRollbackError, error);
}
- const status = await input.gsapMutation();
if (status.mutated) {
try {
+ const ownershipByPath = new Map<string, { before: string; after: string }>();
+ for (const step of ownedSteps) {
+ const owned = ownershipByPath.get(step.path);
+ if (owned) owned.after = step.after;
+ else ownershipByPath.set(step.path, { before: step.before, after: step.after });
+ }
const files: Record<string, { before: string; after: string }> = {};
- for (const path of uniquePaths) {
- const priorContent = before.get(path);
+ for (const [path, owned] of ownershipByPath) {
const finalContent = await readFileContent(input.projectId, path);
- if (priorContent !== undefined && finalContent !== priorContent) {
- files[path] = { before: priorContent, after: finalContent };
+ if (finalContent !== owned.after) {
+ throw new Error(`GSAP mutation ownership lost for ${path}`);
+ }
+ if (owned.before !== owned.after) {
+ files[path] = owned;
}
}
if (Object.keys(files).length > 0) {
@@ -212,7 +403,7 @@ async function foldGsapMutationIntoHistory(input: {
});
}
} catch (error) {
- input.onFoldError(error);
+ return rollbackAfterFailure(input.projectId, ownedSteps, input.onRollbackError, error);
}
}
return status;
@@ -230,23 +421,16 @@ export async function shiftGsapPositions(
delta: number,
): Promise<GsapMutationStatus> {
if (delta === 0 || !elementId) return { mutated: false, scriptText: null };
- const res = await fetch(
- `/api/projects/${encodeURIComponent(projectId)}/gsap-mutations/${encodeURIComponent(filePath)}`,
+ return postGsapMutation(
+ projectId,
+ filePath,
{
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- type: "shift-positions",
- targetSelector: `#${elementId}`,
- delta,
- }),
+ type: "shift-positions",
+ targetSelector: `#${elementId}`,
+ delta,
},
+ "shift-positions failed",
);
- 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(
@@ -262,26 +446,19 @@ export async function scaleGsapPositions(
return { mutated: false, scriptText: null };
if (oldStart === newStart && oldDuration === newDuration)
return { mutated: false, scriptText: null };
- const res = await fetch(
- `/api/projects/${encodeURIComponent(projectId)}/gsap-mutations/${encodeURIComponent(filePath)}`,
+ return postGsapMutation(
+ projectId,
+ filePath,
{
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- type: "scale-positions",
- targetSelector: `#${elementId}`,
- oldStart,
- oldDuration,
- newStart,
- newDuration,
- }),
+ type: "scale-positions",
+ targetSelector: `#${elementId}`,
+ oldStart,
+ oldDuration,
+ newStart,
+ newDuration,
},
+ "scale-positions failed",
);
- 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. */
@@ -297,8 +474,11 @@ export type SingleClipGsapEdit =
* 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.
+ * the rewritten script. When there was nothing to rewrite (no domId — e.g. a
+ * selector-addressed caption clip — zero delta, or a server no-op) it rebinds
+ * the runtime timing in place instead of full-reloading; full reload remains
+ * for genuine rewrites without a returned script and for comps the soft path
+ * can't handle (see syncTimingEditPreview).
*/
export function finishClipTimingFallback(input: {
iframe: HTMLIFrameElement | null;
@@ -338,15 +518,16 @@ export function finishClipTimingFallback(input: {
? () =>
foldGsapMutationIntoHistory({
projectId,
- paths: [targetPath],
label: input.label,
coalesceKey: input.coalesceKey,
recordEdit: input.recordEdit,
- gsapMutation: () => runMutation(projectId, domId),
- onFoldError: onGsapError,
+ gsapMutation: (runOwnedMutation) =>
+ runOwnedMutation(targetPath, () => runMutation(projectId, domId)),
+ onRollbackError: onGsapError,
})
: undefined,
onGsapError,
+ rebindWhenUnmutated: true,
});
}
@@ -386,18 +567,17 @@ export async function finishGroupTimingGsapFallback<C extends { element: Timelin
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 () => {
+ gsapMutation: async (runOwnedMutation) => {
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;
+ const status = await runOwnedMutation(changePath, () =>
+ input.mutateChange(change, changePath),
+ );
mutated = mutated || status.mutated;
// The LAST mutation against the active comp carries the cumulative
// rewritten script for that file.
@@ -405,8 +585,13 @@ export async function finishGroupTimingGsapFallback<C extends { element: Timelin
}
return { mutated, scriptText: otherFileChanged ? null : scriptText };
},
- onFoldError: onGsapError,
+ onRollbackError: onGsapError,
}),
onGsapError,
+ // A batch where nothing needed rewriting (every change was zero-delta or
+ // no-domId, e.g. closing a gap over caption clips) still needs the runtime
+ // to re-derive clip windows — the in-place timing rebind covers that. But
+ // when another file changed, only a full reload reflects every file.
+ rebindWhenUnmutated: !otherFileChanged,
});
}
diff --git a/packages/studio/src/hooks/timelineTrackVisibility.test.ts b/packages/studio/src/hooks/timelineTrackVisibility.test.ts
index 7c0fe91c1b..221893286e 100644
--- a/packages/studio/src/hooks/timelineTrackVisibility.test.ts
+++ b/packages/studio/src/hooks/timelineTrackVisibility.test.ts
@@ -44,7 +44,9 @@ describe("toggleTimelineTrackHidden", () => {
if (iframe.contentDocument) {
iframe.contentDocument.body.innerHTML = `
<div id="hero"></div>
- <div id="subtitle"></div>
+ <div data-composition-id="scene" data-composition-file="scene.html">
+ <div id="subtitle"></div>
+ </div>
`;
}
diff --git a/packages/studio/src/hooks/timelineTrackVisibility.ts b/packages/studio/src/hooks/timelineTrackVisibility.ts
index db30f55ca9..b44a6a2027 100644
--- a/packages/studio/src/hooks/timelineTrackVisibility.ts
+++ b/packages/studio/src/hooks/timelineTrackVisibility.ts
@@ -82,9 +82,10 @@ function patchLiveHiddenState(
iframe: HTMLIFrameElement | null,
elements: readonly TimelineElement[],
hidden: boolean,
+ activeCompPath: string | null,
): void {
for (const element of elements) {
- const target = findTimelineElementInIframe(iframe, element);
+ const target = findTimelineElementInIframe(iframe, element, activeCompPath);
if (!target) continue;
if (hidden) {
target.setAttribute("data-hidden", "");
@@ -134,7 +135,7 @@ async function setElementsHidden({
}: SetElementsHiddenInput): Promise<string[]> {
if (elements.length === 0) return [];
- patchLiveHiddenState(previewIframe, elements, hidden);
+ patchLiveHiddenState(previewIframe, elements, hidden, activeCompPath);
reseekPreviewRuntime(previewIframe);
const hiddenOperation: PatchOperation = {
@@ -188,7 +189,7 @@ async function setElementsHidden({
// The optimistic live patch already ran; a patch-target/save failure here would
// otherwise leave the preview showing the wrong visibility until a reload. Revert
// the live DOM to the prior state so what's on screen matches what persisted.
- patchLiveHiddenState(previewIframe, elements, !hidden);
+ patchLiveHiddenState(previewIframe, elements, !hidden, activeCompPath);
reseekPreviewRuntime(previewIframe);
throw error;
}
diff --git a/packages/studio/src/hooks/useClipboard.ts b/packages/studio/src/hooks/useClipboard.ts
index 22f1a26644..e25f983cc5 100644
--- a/packages/studio/src/hooks/useClipboard.ts
+++ b/packages/studio/src/hooks/useClipboard.ts
@@ -8,6 +8,7 @@ import { insertTimelineAssetIntoSource } from "../utils/timelineAssetDrop";
import { saveProjectFilesWithHistory } from "../utils/studioFileHistory";
import type { EditHistoryKind } from "../utils/editHistory";
import { formatTimelineAttributeNumber } from "../player/components/timelineEditing";
+import { findElementForSelection } from "../components/editor/domEditingElement";
import { readFileContent } from "./timelineEditingHelpers";
interface RecordEditInput {
@@ -34,6 +35,7 @@ interface UseClipboardOptions {
function getElementOuterHtml(
iframeRef: React.MutableRefObject<HTMLIFrameElement | null>,
selection: DomEditSelection,
+ activeCompositionPath: string | null,
): string | null {
let doc: Document | null = null;
try {
@@ -43,15 +45,7 @@ function getElementOuterHtml(
}
if (!doc) return null;
- let el: Element | null = null;
- if (selection.id) {
- el = doc.getElementById(selection.id);
- }
- if (!el && selection.selector) {
- const matches = doc.querySelectorAll(selection.selector);
- el = matches[selection.selectorIndex ?? 0] ?? null;
- }
- return el && "outerHTML" in el ? (el as Element).outerHTML : null;
+ return findElementForSelection(doc, selection, activeCompositionPath)?.outerHTML ?? null;
}
export function useClipboard({
@@ -71,6 +65,9 @@ export function useClipboard({
const projectIdRef = useRef(projectId);
projectIdRef.current = projectId;
+ // The copy-mode branches predate this change; this diff only replaces its
+ // duplicated DOM lookup with the canonical composition-aware resolver.
+ // fallow-ignore-next-line complexity
const handleCopy = useCallback((): boolean => {
const { selectedElementId, elements } = usePlayerStore.getState();
@@ -84,13 +81,18 @@ export function useClipboard({
try {
const doc = previewIframeRef.current?.contentDocument;
if (doc) {
- let el: Element | null = null;
- if (element.domId) el = doc.getElementById(element.domId);
- if (!el && element.selector) {
- const matches = doc.querySelectorAll(element.selector);
- el = matches[element.selectorIndex ?? 0] ?? null;
- }
- if (el && "outerHTML" in el) html = (el as Element).outerHTML;
+ html =
+ findElementForSelection(
+ doc,
+ {
+ hfId: element.hfId,
+ id: element.domId,
+ selector: element.selector,
+ selectorIndex: element.selectorIndex,
+ sourceFile: targetPath,
+ },
+ activeCompPath,
+ )?.outerHTML ?? null;
}
} catch {
// cross-origin frame
@@ -110,7 +112,7 @@ export function useClipboard({
// DOM element copy
const domSelection = domEditSelectionRef.current;
if (domSelection) {
- const html = getElementOuterHtml(previewIframeRef, domSelection);
+ const html = getElementOuterHtml(previewIframeRef, domSelection, activeCompPath);
if (!html) {
showToast("Unable to copy this element.", "info");
return false;
diff --git a/packages/studio/src/hooks/useDomEditCommits.test.tsx b/packages/studio/src/hooks/useDomEditCommits.test.tsx
index 88bd5f0c14..00b181212e 100644
--- a/packages/studio/src/hooks/useDomEditCommits.test.tsx
+++ b/packages/studio/src/hooks/useDomEditCommits.test.tsx
@@ -276,18 +276,20 @@ describe("useDomEditCommits z-index reorder persistence", () => {
_init?: Parameters<typeof fetch>[1],
): Promise<Response> => {
const url = requestUrl(input);
- if (url.includes("/api/projects/p1/files/")) return jsonResponse({ content: original });
- if (url.includes("/file-mutations/patch-elements-batch/")) {
+ if (url.endsWith("/file-mutations/patch-element-batches")) {
return jsonResponse({
- ok: true,
- changed: true,
- matched: [true, true, true],
- content: after,
+ durable: true,
+ files: [
+ {
+ sourceFile: "index.html",
+ changed: true,
+ matched: [true, true, true],
+ before: original,
+ after,
+ },
+ ],
});
}
- if (url.includes("/file-mutations/patch-element/")) {
- return jsonResponse({ ok: true, changed: true, matched: true, content: after });
- }
throw new Error(`Unexpected fetch: ${url}`);
},
);
@@ -317,25 +319,34 @@ describe("useDomEditCommits z-index reorder persistence", () => {
});
const batchPosts = fetchMock.mock.calls.filter(([input]) =>
- requestUrl(input).includes("/file-mutations/patch-elements-batch/"),
+ requestUrl(input).endsWith("/file-mutations/patch-element-batches"),
);
const singlePosts = fetchMock.mock.calls.filter(([input]) =>
- requestUrl(input).includes("/file-mutations/patch-element/"),
+ requestUrl(input).includes("/file-mutations/patch-elements-batch/"),
);
expect(batchPosts).toHaveLength(1);
expect(singlePosts).toHaveLength(0);
expect(JSON.parse(String(batchPosts[0]?.[1]?.body))).toEqual({
- patches: expect.arrayContaining([
- expect.objectContaining({ target: expect.objectContaining({ id: "a" }) }),
- expect.objectContaining({ target: expect.objectContaining({ id: "b" }) }),
- expect.objectContaining({ target: expect.objectContaining({ id: "c" }) }),
- ]),
+ batches: [
+ {
+ sourceFile: "index.html",
+ patches: expect.arrayContaining([
+ expect.objectContaining({ target: expect.objectContaining({ id: "a" }) }),
+ expect.objectContaining({ target: expect.objectContaining({ id: "b" }) }),
+ expect.objectContaining({ target: expect.objectContaining({ id: "c" }) }),
+ ]),
+ },
+ ],
});
expect(rendered.recordEdit).toHaveBeenCalledTimes(1);
expect(rendered.recordEdit).toHaveBeenCalledWith({
label: "Reorder layers",
kind: "manual",
coalesceKey: "z-reorder:test",
+ // Unbounded per-gesture fold window (keys are unique per gesture):
+ // the z entry and its mirror/lane counterpart fold across the server
+ // round-trip that separates them.
+ coalesceMs: Number.POSITIVE_INFINITY,
files: { "index.html": { before: original, after } },
});
// FIX: a z-only reorder must NOT remount the preview iframe ("the blink").
@@ -354,9 +365,11 @@ describe("useDomEditCommits z-index reorder persistence", () => {
const after = '<div id="a" style="z-index: 2"></div>';
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: original });
- if (url.includes("/file-mutations/patch-elements-batch/")) {
- return jsonResponse({ ok: true, changed: true, content: after });
+ if (url.endsWith("/file-mutations/patch-element-batches")) {
+ return jsonResponse({
+ durable: true,
+ files: [{ sourceFile: "index.html", changed: true, before: original, after }],
+ });
}
throw new Error(`Unexpected fetch: ${url}`);
});
@@ -380,18 +393,26 @@ describe("useDomEditCommits z-index reorder persistence", () => {
});
it("warns and reports telemetry for unmatched batch patches without throwing", async () => {
- // The server reports per-patch matched[]: #b was not found in the source.
- // The matched subset persisted, so the commit must complete (no rollback of
- // applied state) while surfacing the partial failure. An unmatched target
- // also means the live DOM shows z-order the disk lacks, so the skip-reload
- // path must NOT engage — the reload reconverges the preview with disk.
+ // The server reports per-patch matched[]: #b was not found in the source,
+ // so it atomically refuses the whole multi-file gesture. The reload
+ // reconverges the preview with disk while the lifecycle owner rolls back
+ // both optimistic writes.
const original = '<div id="a" style="z-index: 1"></div>';
- const after = '<div id="a" style="z-index: 2"></div>';
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: original });
- if (url.includes("/file-mutations/patch-elements-batch/")) {
- return jsonResponse({ ok: true, changed: true, matched: [true, false], content: after });
+ if (url.endsWith("/file-mutations/patch-element-batches")) {
+ return jsonResponse({
+ durable: false,
+ files: [
+ {
+ sourceFile: "index.html",
+ changed: false,
+ matched: [true, false],
+ before: original,
+ after: original,
+ },
+ ],
+ });
}
throw new Error(`Unexpected fetch: ${url}`);
});
@@ -412,10 +433,10 @@ describe("useDomEditCommits z-index reorder persistence", () => {
]);
});
- // No throw: the applied live state stays, the matched subset is recorded.
- expect(element.style.zIndex).toBe("2");
- expect(second.style.zIndex).toBe("1");
- expect(rendered.recordEdit).toHaveBeenCalledTimes(1);
+ // No throw: incomplete durability rolls back both optimistic writes.
+ expect(element.style.zIndex).toBe("");
+ expect(second.style.zIndex).toBe("");
+ expect(rendered.recordEdit).not.toHaveBeenCalled();
expect(rendered.reloadPreview).toHaveBeenCalledTimes(1);
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining("could not match 1 patch target(s) in index.html"),
@@ -435,12 +456,125 @@ describe("useDomEditCommits z-index reorder persistence", () => {
}
});
- it("rolls back live state after a failed batch POST without a disk write-back", async () => {
- const original = '<div id="a" style="z-index: 7"></div><div id="b"></div>';
+ it("uses one atomic request and rolls back every file when one target is unmatched", async () => {
+ const indexOriginal = '<div id="a" style="z-index: 4"></div>';
+ const sceneOriginal = '<div id="b" style="z-index: 5"></div>';
+ const fetchMock = vi.fn(
+ async (
+ input: Parameters<typeof fetch>[0],
+ init?: Parameters<typeof fetch>[1],
+ ): Promise<Response> => {
+ const url = requestUrl(input);
+ if (url.endsWith("/file-mutations/patch-element-batches")) {
+ expect(JSON.parse(String(init?.body))).toEqual({
+ batches: [
+ expect.objectContaining({ sourceFile: "index.html" }),
+ expect.objectContaining({ sourceFile: "scene.html" }),
+ ],
+ });
+ return jsonResponse({
+ durable: false,
+ files: [
+ {
+ sourceFile: "index.html",
+ changed: false,
+ matched: [true],
+ before: indexOriginal,
+ after: indexOriginal,
+ },
+ {
+ sourceFile: "scene.html",
+ changed: false,
+ matched: [false],
+ before: sceneOriginal,
+ after: sceneOriginal,
+ },
+ ],
+ });
+ }
+ throw new Error(`Unexpected fetch: ${url}`);
+ },
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const { iframe, element } = createPreviewElement(
+ '<div data-hf-id="hf-card" style="z-index: 4"></div><div id="b" style="z-index: 5"></div>',
+ );
+ element.id = "a";
+ const second = iframe.contentDocument!.getElementById("b")!;
+ const rendered = renderDomEditCommits(createSelection(element), iframe);
+
+ try {
+ let result:
+ | Awaited<ReturnType<typeof rendered.hook.handleDomZIndexReorderCommit>>
+ | undefined;
+ await act(async () => {
+ result = await rendered.hook.handleDomZIndexReorderCommit([
+ { element, zIndex: 8, id: "a", sourceFile: "index.html" },
+ { element: second, zIndex: 9, id: "b", sourceFile: "scene.html" },
+ ]);
+ });
+
+ expect(result).toEqual({ durable: false, allMatched: false, changed: false });
+ expect(element.style.zIndex).toBe("4");
+ expect(second.style.zIndex).toBe("5");
+ expect(rendered.recordEdit).not.toHaveBeenCalled();
+ expect(rendered.reloadPreview).toHaveBeenCalledTimes(1);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ } finally {
+ warnSpy.mockRestore();
+ rendered.cleanup();
+ }
+ });
+
+ it("reloads and reports non-durable when an unmatched batch changes no bytes", async () => {
+ const original = '<div id="a" style="z-index: 1"></div>';
+ const fetchMock = vi.fn(async (input: Parameters<typeof fetch>[0]): Promise<Response> => {
+ const url = requestUrl(input);
+ if (url.endsWith("/file-mutations/patch-element-batches")) {
+ return jsonResponse({
+ durable: false,
+ files: [
+ {
+ sourceFile: "index.html",
+ changed: false,
+ matched: [false],
+ before: original,
+ after: original,
+ },
+ ],
+ });
+ }
+ throw new Error(`Unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ const { iframe, element } = createPreviewElement();
+ element.id = "a";
+ const rendered = renderDomEditCommits(createSelection(element), iframe);
+
+ try {
+ let result:
+ | Awaited<ReturnType<typeof rendered.hook.handleDomZIndexReorderCommit>>
+ | undefined;
+ await act(async () => {
+ result = await rendered.hook.handleDomZIndexReorderCommit([
+ { element, zIndex: 2, id: "missing", sourceFile: "index.html" },
+ ]);
+ });
+
+ expect(result).toEqual({ durable: false, allMatched: false, changed: false });
+ expect(element.style.zIndex).toBe("");
+ expect(rendered.recordEdit).not.toHaveBeenCalled();
+ expect(rendered.reloadPreview).toHaveBeenCalledTimes(1);
+ } finally {
+ rendered.cleanup();
+ }
+ });
+
+ it("rolls back and reloads after a rejected batch POST", 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: original });
- if (url.includes("/file-mutations/patch-elements-batch/")) {
+ if (url.endsWith("/file-mutations/patch-element-batches")) {
return jsonResponse({ error: "batch rejected" }, 500);
}
throw new Error(`Unexpected fetch: ${url}`);
@@ -485,10 +619,154 @@ describe("useDomEditCommits z-index reorder persistence", () => {
]);
expect(writeProjectFile).not.toHaveBeenCalled();
expect(rendered.recordEdit).not.toHaveBeenCalled();
- expect(rendered.reloadPreview).not.toHaveBeenCalled();
+ expect(rendered.reloadPreview).toHaveBeenCalledTimes(1);
+ expect(
+ fetchMock.mock.calls.filter(([input]) =>
+ requestUrl(input).endsWith("/file-mutations/patch-element-batches"),
+ ),
+ ).toHaveLength(1);
+ } finally {
+ rendered.cleanup();
+ }
+ });
+
+ it("reloads after the server commits but the aggregate response is lost", async () => {
+ const original = '<div data-hf-id="hf-card" id="a" style="z-index: 7"></div>';
+ const after = '<div data-hf-id="hf-card" id="a" style="z-index: 2"></div>';
+ let diskContent = original;
+ const fetchMock = vi.fn(async (input: Parameters<typeof fetch>[0]): Promise<Response> => {
+ const url = requestUrl(input);
+ if (url.endsWith("/file-mutations/patch-element-batches")) {
+ diskContent = after;
+ throw new TypeError("connection reset after commit");
+ }
+ throw new Error(`Unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ const { iframe, element } = createPreviewElement(original);
+ usePlayerStore.getState().setElements([
+ {
+ id: "a",
+ tag: "div",
+ start: 0,
+ duration: 1,
+ track: 0,
+ zIndex: 7,
+ hasExplicitZIndex: true,
+ },
+ ]);
+ const rendered = renderDomEditCommits(createSelection(element), iframe);
+
+ try {
+ let rejection: unknown;
+ await act(async () => {
+ try {
+ await rendered.hook.handleDomZIndexReorderCommit([
+ { element, zIndex: 2, id: "a", sourceFile: "index.html", key: "a" },
+ ]);
+ } catch (error) {
+ rejection = error;
+ }
+ });
+
+ expect(rejection).toBeInstanceOf(Error);
+ expect((rejection as Error).message).toContain("connection reset after commit");
+ expect(diskContent).toBe(after);
+ expect(element.style.zIndex).toBe("7");
+ expect(usePlayerStore.getState().elements[0]).toMatchObject({
+ zIndex: 7,
+ hasExplicitZIndex: true,
+ });
+ expect(rendered.recordEdit).not.toHaveBeenCalled();
+ expect(rendered.reloadPreview).toHaveBeenCalledTimes(1);
+ expect(
+ fetchMock.mock.calls.filter(([input]) =>
+ requestUrl(input).endsWith("/file-mutations/patch-element-batches"),
+ ),
+ ).toHaveLength(1);
+ } finally {
+ rendered.cleanup();
+ }
+ });
+
+ it.each([
+ [
+ "changed=false with different snapshots",
+ {
+ durable: true,
+ files: [
+ {
+ sourceFile: "index.html",
+ changed: false,
+ matched: [true],
+ before: '<div id="a" style="z-index: 1"></div>',
+ after: '<div id="a" style="z-index: 2"></div>',
+ },
+ ],
+ },
+ ],
+ [
+ "changed=true with identical snapshots",
+ {
+ durable: true,
+ files: [
+ {
+ sourceFile: "index.html",
+ changed: true,
+ matched: [true],
+ before: '<div id="a" style="z-index: 1"></div>',
+ after: '<div id="a" style="z-index: 1"></div>',
+ },
+ ],
+ },
+ ],
+ [
+ "durable=false with a changed file",
+ {
+ durable: false,
+ files: [
+ {
+ sourceFile: "index.html",
+ changed: true,
+ matched: [true],
+ before: '<div id="a" style="z-index: 1"></div>',
+ after: '<div id="a" style="z-index: 2"></div>',
+ },
+ ],
+ },
+ ],
+ ])("rejects and reloads for malformed 200 response: %s", async (_label, responseBody) => {
+ const fetchMock = vi.fn(async (input: Parameters<typeof fetch>[0]): Promise<Response> => {
+ const url = requestUrl(input);
+ if (url.endsWith("/file-mutations/patch-element-batches")) {
+ return jsonResponse(responseBody);
+ }
+ throw new Error(`Unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ const { iframe, element } = createPreviewElement();
+ element.id = "a";
+ const rendered = renderDomEditCommits(createSelection(element), iframe);
+
+ try {
+ let rejection: unknown;
+ await act(async () => {
+ try {
+ await rendered.hook.handleDomZIndexReorderCommit([
+ { element, zIndex: 2, id: "a", sourceFile: "index.html", key: "a" },
+ ]);
+ } catch (error) {
+ rejection = error;
+ }
+ });
+
+ expect(rejection).toBeInstanceOf(Error);
+ expect((rejection as Error).message).toBe("Invalid atomic element patch response");
+ expect(rendered.recordEdit).not.toHaveBeenCalled();
+ expect(rendered.reloadPreview).toHaveBeenCalledTimes(1);
expect(
fetchMock.mock.calls.filter(([input]) =>
- requestUrl(input).includes("/file-mutations/patch-elements-batch/"),
+ requestUrl(input).endsWith("/file-mutations/patch-element-batches"),
),
).toHaveLength(1);
} finally {
diff --git a/packages/studio/src/hooks/useDomEditCommits.ts b/packages/studio/src/hooks/useDomEditCommits.ts
index 3b88442071..8af3729b1a 100644
--- a/packages/studio/src/hooks/useDomEditCommits.ts
+++ b/packages/studio/src/hooks/useDomEditCommits.ts
@@ -28,7 +28,6 @@ import { useDomEditTextCommits } from "./useDomEditTextCommits";
import { useDomGeometryCommits } from "./useDomGeometryCommits";
import { useElementLifecycleOps } from "./useElementLifecycleOps";
import { formatFieldsSuffix } from "./gsapScriptCommitHelpers";
-import { readProjectFileContent } from "../utils/studioFileHistory";
// ── Helpers ──
@@ -67,9 +66,9 @@ function describeBatchPatchTarget(patch: DomEditPatchBatch["patches"][number]):
}
/**
- * Surface server-reported unmatched patches. The matched subset already
- * persisted, so this must NOT throw (a throw would roll back applied state) —
- * warn and emit save-failure telemetry with a distinct reason instead.
+ * Surface server-reported unmatched patches. The server atomically refuses the
+ * whole multi-file gesture; the caller uses `durable: false` to roll back and
+ * reload, so report the refusal without turning it into a second failure.
*/
function reportUnmatchedBatchPatches(batch: DomEditPatchBatch, matched: boolean[]): void {
const unmatchedIds = batch.patches
@@ -78,7 +77,7 @@ function reportUnmatchedBatchPatches(batch: DomEditPatchBatch, matched: boolean[
if (unmatchedIds.length === 0) return;
console.warn(
`[studio] z-index reorder: server could not match ${unmatchedIds.length} patch target(s) in ` +
- `${batch.sourceFile} (their z-order will revert on reload):`,
+ `${batch.sourceFile} (the whole z-order gesture will revert on reload):`,
unmatchedIds.join(", "),
);
trackStudioSaveFailure({
@@ -89,40 +88,95 @@ function reportUnmatchedBatchPatches(batch: DomEditPatchBatch, matched: boolean[
});
}
-async function patchElementBatch(projectId: string, batch: DomEditPatchBatch) {
- const before = await readProjectFileContent(projectId, batch.sourceFile);
- const response = await fetch(
- `/api/projects/${encodeURIComponent(projectId)}/file-mutations/patch-elements-batch/${encodeURIComponent(batch.sourceFile)}`,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ patches: batch.patches }),
- },
+interface AtomicElementPatchFile {
+ sourceFile: string;
+ changed: boolean;
+ matched?: boolean[];
+ before: string;
+ after: string;
+}
+
+class AtomicElementPatchConvergenceError extends Error {
+ constructor(message: string, options?: { cause?: unknown }) {
+ super(message, options);
+ this.name = "AtomicElementPatchConvergenceError";
+ }
+}
+
+// Keep the atomic response contract in one guard so callers do not compose validity.
+// fallow-ignore-next-line complexity
+function isAtomicElementPatchFile(value: unknown): value is AtomicElementPatchFile {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ "sourceFile" in value &&
+ typeof value.sourceFile === "string" &&
+ "changed" in value &&
+ typeof value.changed === "boolean" &&
+ (!("matched" in value) ||
+ (Array.isArray(value.matched) &&
+ value.matched.every((matched) => typeof matched === "boolean"))) &&
+ "before" in value &&
+ typeof value.before === "string" &&
+ "after" in value &&
+ typeof value.after === "string" &&
+ value.changed === (value.before !== value.after)
);
- if (!response.ok) {
- const rejection = await readErrorResponseBody(response);
- throw new StudioSaveHttpError(formatPatchRejectionMessage(rejection), response.status);
+}
+
+// This is the single client owner for dispatching and validating the aggregate
+// atomic endpoint. Splitting validation from the request would weaken that wire contract.
+// fallow-ignore-next-line complexity
+async function patchElementBatches(projectId: string, batches: DomEditPatchBatch[]) {
+ const body = JSON.stringify({ batches });
+ try {
+ const response = await fetch(
+ `/api/projects/${encodeURIComponent(projectId)}/file-mutations/patch-element-batches`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body,
+ },
+ );
+ if (!response.ok) {
+ const rejection = await readErrorResponseBody(response);
+ throw new StudioSaveHttpError(formatPatchRejectionMessage(rejection), response.status);
+ }
+ const result: unknown = await response.json().catch(() => null);
+ if (
+ typeof result !== "object" ||
+ result === null ||
+ !("durable" in result) ||
+ typeof result.durable !== "boolean" ||
+ !("files" in result) ||
+ !Array.isArray(result.files) ||
+ result.files.length !== batches.length ||
+ !result.files.every(isAtomicElementPatchFile) ||
+ (!result.durable && result.files.some((file) => file.changed))
+ ) {
+ throw new StudioSaveHttpError("Invalid atomic element patch response", 502);
+ }
+ const files = result.files.map((file, index) => {
+ const batch = batches[index];
+ const matched = file.matched ?? [];
+ if (
+ !batch ||
+ file.sourceFile !== batch.sourceFile ||
+ (matched.length !== 0 && matched.length !== batch.patches.length)
+ ) {
+ throw new StudioSaveHttpError("Invalid atomic element patch response", 502);
+ }
+ reportUnmatchedBatchPatches(batch, matched);
+ return {
+ ...file,
+ matched,
+ allMatched: matched.length === batch.patches.length && matched.every(Boolean),
+ };
+ });
+ return { durable: result.durable, files };
+ } catch (error) {
+ throw new AtomicElementPatchConvergenceError(getErrorDetail(error), { cause: error });
}
- const result = (await response.json()) as {
- changed?: boolean;
- matched?: boolean[];
- content?: string;
- };
- if (Array.isArray(result.matched)) reportUnmatchedBatchPatches(batch, result.matched);
- return {
- sourceFile: batch.sourceFile,
- changed: result.changed === true,
- // Skip-reload safety: the persist is only provably in sync with the live
- // DOM when the server confirmed EVERY patch target matched. A missing /
- // short matched[] is treated as unknown (false) so the caller falls back
- // to reloading rather than silently diverging from disk.
- allMatched:
- Array.isArray(result.matched) &&
- result.matched.length === batch.patches.length &&
- result.matched.every(Boolean),
- before,
- after: typeof result.content === "string" ? result.content : before,
- };
}
/**
@@ -142,7 +196,7 @@ export interface UseDomEditCommitsParams {
activeCompPath: string | null;
previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>;
showToast: (message: string, tone?: "error" | "info") => void;
- queueDomEditSave: (save: () => Promise<void>) => Promise<void>;
+ queueDomEditSave: <T>(save: () => Promise<T>) => Promise<T>;
writeProjectFile: (path: string, content: string) => Promise<void>;
domEditSaveTimestampRef: React.MutableRefObject<number>;
editHistory: { recordEdit: (entry: RecordEditInput) => Promise<void> };
@@ -382,48 +436,59 @@ export function useDomEditCommits({
const commitDomEditPatchBatches: CommitDomEditPatchBatches = useCallback(
(batches, options) =>
- queueDomEditSave(async () => {
- const pid = projectIdRef.current;
- if (!pid) throw new Error("No active project");
- const unsafeFields = batches.flatMap((batch) =>
- batch.patches.flatMap((patch) => findUnsafeDomPatchValues(patch)),
- );
- if (unsafeFields.length > 0) {
- showToast("Couldn't save edit because it contains invalid layout values", "error");
- throw new DomEditPersistUnsafeValueError(
- `DOM patch contains unsafe values: ${formatUnsafeFieldList(unsafeFields)}`,
- { alreadyToasted: true },
+ queueDomEditSave(
+ // One queued transaction owns validation, persistence, history, reload,
+ // and its durable result; splitting those phases risks partial commits.
+ // fallow-ignore-next-line complexity
+ async () => {
+ const pid = projectIdRef.current;
+ if (!pid) throw new Error("No active project");
+ const unsafeFields = batches.flatMap((batch) =>
+ batch.patches.flatMap((patch) => findUnsafeDomPatchValues(patch)),
);
- }
+ if (unsafeFields.length > 0) {
+ showToast("Couldn't save edit because it contains invalid layout values", "error");
+ throw new DomEditPersistUnsafeValueError(
+ `DOM patch contains unsafe values: ${formatUnsafeFieldList(unsafeFields)}`,
+ { alreadyToasted: true },
+ );
+ }
- domEditSaveTimestampRef.current = Date.now();
- const results = await Promise.all(batches.map((batch) => patchElementBatch(pid, batch)));
- const files = Object.fromEntries(
- results
- .filter((result) => result.changed)
- .map((result) => [result.sourceFile, { before: result.before, after: result.after }]),
- );
- if (Object.keys(files).length === 0) return;
- await editHistory.recordEdit({
- label: options.label,
- kind: "manual",
- coalesceKey: options.coalesceKey,
- files,
- });
- forceReloadSdkSession?.();
- // A z-only reorder already applied its inline styles to the live iframe
- // DOM (and the store) synchronously, so remounting the iframe here only
- // produces a visible blink. Skip the reload when the caller asked for it
- // AND the persist is provably in sync: style-only ops, every target
- // matched. Any unmatched patch means the live DOM now shows state disk
- // doesn't hold — reload so the preview reconverges. (The SSE/file-watcher
- // reload is independently suppressed by domEditSaveTimestampRef above.)
- const skipSafe =
- options.skipReload === true &&
- batchesAreInlineStyleOnly(batches) &&
- results.every((result) => result.allMatched);
- if (!skipSafe) reloadPreview();
- }).catch((error) => {
+ domEditSaveTimestampRef.current = Date.now();
+ const atomicResult = await patchElementBatches(pid, batches);
+ const allMatched =
+ atomicResult.durable && atomicResult.files.every((result) => result.allMatched);
+ const files = Object.fromEntries(
+ atomicResult.files
+ .filter((result) => result.changed)
+ .map((result) => [result.sourceFile, { before: result.before, after: result.after }]),
+ );
+ const changed = Object.keys(files).length > 0;
+ if (changed) {
+ await editHistory.recordEdit({
+ label: options.label,
+ kind: "manual",
+ coalesceKey: options.coalesceKey,
+ coalesceMs: options.coalesceMs,
+ files,
+ });
+ forceReloadSdkSession?.();
+ }
+ const durable = allMatched;
+ // A z-only reorder already applied its inline styles to the live iframe
+ // DOM (and the store) synchronously, so remounting the iframe here only
+ // produces a visible blink. Skip the reload when the caller asked for it
+ // AND the persist is provably in sync: style-only ops, every target
+ // matched. Any unmatched patch means the live DOM now shows state disk
+ // doesn't hold — reload so the preview reconverges. (The SSE/file-watcher
+ // reload is independently suppressed by domEditSaveTimestampRef above.)
+ const skipSafe =
+ options.skipReload === true && batchesAreInlineStyleOnly(batches) && durable;
+ if (!durable || (changed && !skipSafe)) reloadPreview();
+ return { durable, allMatched, changed };
+ },
+ ).catch((error) => {
+ if (error instanceof AtomicElementPatchConvergenceError) reloadPreview();
const alreadyToasted =
(error instanceof StudioSaveHttpError ||
error instanceof DomEditPersistUnsafeValueError) &&
diff --git a/packages/studio/src/hooks/useDomEditSession.test.tsx b/packages/studio/src/hooks/useDomEditSession.test.tsx
index 4a70a3f0d0..57b4751f42 100644
--- a/packages/studio/src/hooks/useDomEditSession.test.tsx
+++ b/packages/studio/src/hooks/useDomEditSession.test.tsx
@@ -231,7 +231,9 @@ describe("onReorderShadow source filter", () => {
setRightPanelTab: vi.fn(),
showToast: vi.fn(),
refreshPreviewDocumentVersion: vi.fn(),
- queueDomEditSave: vi.fn(async (save: () => Promise<void>) => save()),
+ queueDomEditSave: vi.fn(async <T,>(save: () => Promise<T>) => save()) as <T>(
+ save: () => Promise<T>,
+ ) => Promise<T>,
readProjectFile,
writeProjectFile: vi.fn(async () => {}),
updateEditingFileContent: vi.fn(),
diff --git a/packages/studio/src/hooks/useDomEditSession.ts b/packages/studio/src/hooks/useDomEditSession.ts
index f8cba7f987..4d94ddd355 100644
--- a/packages/studio/src/hooks/useDomEditSession.ts
+++ b/packages/studio/src/hooks/useDomEditSession.ts
@@ -43,7 +43,7 @@ export interface UseDomEditSessionParams {
setRightPanelTab: (tab: RightPanelTab) => void;
showToast: (message: string, tone?: "error" | "info") => void;
refreshPreviewDocumentVersion: () => void;
- queueDomEditSave: (save: () => Promise<void>) => Promise<void>;
+ queueDomEditSave: <T>(save: () => Promise<T>) => Promise<T>;
readProjectFile: (path: string) => Promise<string>;
writeProjectFile: (path: string, content: string) => Promise<void>;
updateEditingFileContent: (path: string, content: string) => void;
diff --git a/packages/studio/src/hooks/useElementLifecycleOps.test.tsx b/packages/studio/src/hooks/useElementLifecycleOps.test.tsx
index 979cdea6c9..d740894154 100644
--- a/packages/studio/src/hooks/useElementLifecycleOps.test.tsx
+++ b/packages/studio/src/hooks/useElementLifecycleOps.test.tsx
@@ -3,9 +3,22 @@
import React, { act } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { usePlayerStore } from "../player";
-import type { DomEditPatchBatch } from "./domEditCommitTypes";
+import {
+ LAYER_REVEAL_PRIOR_POSITION_ATTR,
+ LAYER_REVEAL_PRIOR_Z_ATTR,
+} from "../player/lib/timelineElementHelpers";
+import {
+ LAYER_REVEAL_LIFT_Z,
+ LAYER_REVEAL_PENDING_COMMIT_ATTR,
+ liftElementToTop,
+ restoreLiftedElement,
+ useLayerRevealOverride,
+} from "../components/editor/useLayerRevealOverride";
+import type { DomEditPatchBatch, DomEditPatchBatchesResult } from "./domEditCommitTypes";
import { useElementLifecycleOps } from "./useElementLifecycleOps";
+import { makeLifecycleOpsParams } from "./elementLifecycleOpsTestUtils";
import { mountReactHarness } from "./domSelectionTestHarness";
+import { runZLaneGesture } from "../components/nle/zLaneGesture";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -13,11 +26,13 @@ afterEach(() => {
document.body.innerHTML = "";
usePlayerStore.getState().setElements([]);
vi.unstubAllGlobals();
+ vi.useRealTimers();
});
interface BatchOptions {
label: string;
coalesceKey: string;
+ coalesceMs?: number;
skipReload?: boolean;
}
@@ -38,26 +53,21 @@ type ReorderCommit = (
}>,
coalesceKeyOverride?: string,
actionKind?: string,
-) => Promise<void>;
+) => Promise<DomEditPatchBatchesResult | undefined | void>;
function renderReorderHook(
capturedCalls: CapturedBatchCall[],
onReady: (commit: ReorderCommit) => void,
) {
function Harness() {
- const { handleDomZIndexReorderCommit } = useElementLifecycleOps({
- activeCompPath: "index.html",
- showToast: vi.fn(),
- writeProjectFile: vi.fn(async () => {}),
- domEditSaveTimestampRef: { current: 0 },
- editHistory: { recordEdit: vi.fn(async () => {}) },
- projectIdRef: { current: null },
- reloadPreview: vi.fn(),
- clearDomSelection: vi.fn(),
- commitDomEditPatchBatches: async (batches, options) => {
- capturedCalls.push({ batches, options });
- },
- });
+ const { handleDomZIndexReorderCommit } = useElementLifecycleOps(
+ makeLifecycleOpsParams({
+ commitDomEditPatchBatches: async (batches, options) => {
+ capturedCalls.push({ batches, options });
+ return { durable: true, allMatched: true, changed: true };
+ },
+ }),
+ );
onReady(handleDomZIndexReorderCommit);
return null;
}
@@ -219,10 +229,15 @@ describe("useElementLifecycleOps — z-index reorder payload", () => {
});
// Same element set, different actions — the keys must differ so the two
- // edits never coalesce into one undo step within the coalesce window.
+ // edits never coalesce into one undo step. Each key also carries a fresh
+ // gesture sequence, which is what makes the commit's unbounded per-gesture
+ // coalesce window safe (see zReorderCoalesceKey).
expect(captured).toHaveLength(2);
- expect(captured[0]?.options.coalesceKey).toBe("z-reorder:bring-forward:clip-a");
- expect(captured[1]?.options.coalesceKey).toBe("z-reorder:send-backward:clip-a");
+ expect(captured[0]?.options.coalesceKey).toMatch(/^z-reorder:bring-forward:clip-a:g\d+$/);
+ expect(captured[1]?.options.coalesceKey).toMatch(/^z-reorder:send-backward:clip-a:g\d+$/);
+ expect(captured[0]?.options.coalesceKey).not.toBe(captured[1]?.options.coalesceKey);
+ // The two-phase gesture fold rides an unbounded window on both records.
+ expect(captured[0]?.options.coalesceMs).toBe(Number.POSITIVE_INFINITY);
act(() => root.unmount());
});
@@ -245,26 +260,22 @@ describe("useElementLifecycleOps — z-index reorder payload", () => {
let commit: ReorderCommit | undefined;
let resolveBatch: (() => void) | undefined;
+ const batchResult = { durable: true, allMatched: true, changed: true };
function Harness() {
- const { handleDomZIndexReorderCommit } = useElementLifecycleOps({
- activeCompPath: "index.html",
- showToast: vi.fn(),
- writeProjectFile: vi.fn(async () => {}),
- domEditSaveTimestampRef: { current: 0 },
- editHistory: { recordEdit: vi.fn(async () => {}) },
- projectIdRef: { current: null },
- reloadPreview: vi.fn(),
- clearDomSelection: vi.fn(),
- // Persist stays pending so the assertion below can only be satisfied
- // by the SYNCHRONOUS store update (the lane-sync path's requirement).
- commitDomEditPatchBatches: () => new Promise((resolve) => (resolveBatch = resolve)),
- });
+ const { handleDomZIndexReorderCommit } = useElementLifecycleOps(
+ makeLifecycleOpsParams({
+ // Persist stays pending so the assertion below can only be satisfied
+ // by the SYNCHRONOUS store update (the lane-sync path's requirement).
+ commitDomEditPatchBatches: () =>
+ new Promise((resolve) => (resolveBatch = () => resolve(batchResult))),
+ }),
+ );
commit = handleDomZIndexReorderCommit;
return null;
}
const root = mountReactHarness(<Harness />);
- let pending: Promise<void> | undefined;
+ let pending: Promise<unknown> | undefined;
act(() => {
pending = commit!([
{
@@ -301,22 +312,16 @@ describe("useElementLifecycleOps — z-index reorder payload", () => {
let commit: ReorderCommit | undefined;
function Harness() {
- const { handleDomZIndexReorderCommit } = useElementLifecycleOps({
- activeCompPath: "index.html",
- showToast: vi.fn(),
- writeProjectFile: vi.fn(async () => {}),
- domEditSaveTimestampRef: { current: 0 },
- editHistory: { recordEdit: vi.fn(async () => {}) },
- projectIdRef: { current: null },
- reloadPreview: vi.fn(),
- clearDomSelection: vi.fn(),
- commitDomEditPatchBatches: vi.fn(async () => {
- // The live styles were applied by the hook before persist ran.
- expect(el.style.zIndex).toBe("2");
- expect(el.style.position).toBe("relative");
- throw failure;
+ const { handleDomZIndexReorderCommit } = useElementLifecycleOps(
+ makeLifecycleOpsParams({
+ commitDomEditPatchBatches: vi.fn(async () => {
+ // The live styles were applied by the hook before persist ran.
+ expect(el.style.zIndex).toBe("2");
+ expect(el.style.position).toBe("relative");
+ throw failure;
+ }),
}),
- });
+ );
commit = handleDomZIndexReorderCommit;
return null;
}
@@ -341,6 +346,370 @@ describe("useElementLifecycleOps — z-index reorder payload", () => {
act(() => root.unmount());
});
+ it("returns an active reveal lift and its original styles to their owner on failure", async () => {
+ const el = document.createElement("div");
+ el.id = "clip-a";
+ el.style.zIndex = "4";
+ el.style.position = "static";
+ document.body.appendChild(el);
+ const lift = liftElementToTop(el)!;
+ const failure = new Error("persist failed");
+
+ expect(el.style.zIndex).toBe(LAYER_REVEAL_LIFT_Z);
+ expect(el.style.position).toBe("relative");
+ expect(el.getAttribute(LAYER_REVEAL_PRIOR_Z_ATTR)).toBe("4");
+ expect(el.getAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR)).toBe("static");
+ expect(el.hasAttribute(LAYER_REVEAL_PENDING_COMMIT_ATTR)).toBe(false);
+
+ let commit: ReorderCommit | undefined;
+ function Harness() {
+ const { handleDomZIndexReorderCommit } = useElementLifecycleOps(
+ makeLifecycleOpsParams({
+ commitDomEditPatchBatches: vi.fn(async () => {
+ expect(el.style.zIndex).toBe("8");
+ expect(el.hasAttribute(LAYER_REVEAL_PRIOR_Z_ATTR)).toBe(false);
+ expect(el.hasAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR)).toBe(false);
+ throw failure;
+ }),
+ }),
+ );
+ commit = handleDomZIndexReorderCommit;
+ return null;
+ }
+ const root = mountReactHarness(<Harness />);
+
+ let rejection: unknown;
+ await act(async () => {
+ try {
+ await commit!([{ element: el, zIndex: 8, id: "clip-a", sourceFile: "index.html" }]);
+ } catch (error) {
+ rejection = error;
+ }
+ });
+ expect(rejection).toBe(failure);
+
+ // The failed optimistic commit must put the still-active lift back exactly
+ // as it found it, including the metadata that lets reveal cleanup restore
+ // the authored z/position rather than abandoning the temporary lift.
+ expect(el.style.zIndex).toBe(LAYER_REVEAL_LIFT_Z);
+ expect(el.style.position).toBe("relative");
+ expect(el.getAttribute(LAYER_REVEAL_PRIOR_Z_ATTR)).toBe("4");
+ expect(el.getAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR)).toBe("static");
+ expect(el.hasAttribute(LAYER_REVEAL_PENDING_COMMIT_ATTR)).toBe(false);
+
+ restoreLiftedElement(el, lift);
+ expect(el.style.zIndex).toBe("4");
+ expect(el.style.position).toBe("static");
+ act(() => root.unmount());
+ });
+
+ it("reconciles live, store, and reveal state when no patch target matched", async () => {
+ const el = document.createElement("div");
+ el.id = "clip-a";
+ el.style.zIndex = "4";
+ el.style.position = "static";
+ document.body.appendChild(el);
+ usePlayerStore.getState().setElements([
+ {
+ id: "clip-a",
+ tag: "div",
+ start: 0,
+ duration: 1,
+ track: 0,
+ zIndex: 4,
+ hasExplicitZIndex: true,
+ },
+ ]);
+ const lift = liftElementToTop(el)!;
+ const unmatched = { durable: false, allMatched: false, changed: false };
+ let commit: ReorderCommit | undefined;
+
+ function Harness() {
+ ({ handleDomZIndexReorderCommit: commit } = useElementLifecycleOps(
+ makeLifecycleOpsParams({
+ commitDomEditPatchBatches: vi.fn(async () => unmatched),
+ }),
+ ));
+ return null;
+ }
+ const root = mountReactHarness(<Harness />);
+
+ let result: unknown;
+ await act(async () => {
+ result = await commit!([
+ {
+ element: el,
+ zIndex: 8,
+ id: "clip-a",
+ sourceFile: "index.html",
+ key: "clip-a",
+ },
+ ]);
+ });
+
+ expect(result).toEqual(unmatched);
+ expect(el.style.zIndex).toBe(LAYER_REVEAL_LIFT_Z);
+ expect(el.style.position).toBe("relative");
+ expect(el.getAttribute(LAYER_REVEAL_PRIOR_Z_ATTR)).toBe("4");
+ expect(el.getAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR)).toBe("static");
+ expect(el.hasAttribute(LAYER_REVEAL_PENDING_COMMIT_ATTR)).toBe(false);
+ expect(usePlayerStore.getState().elements[0]).toMatchObject({
+ zIndex: 4,
+ hasExplicitZIndex: true,
+ });
+
+ restoreLiftedElement(el, lift);
+ expect(el.style.zIndex).toBe("4");
+ expect(el.style.position).toBe("static");
+ act(() => root.unmount());
+ });
+
+ it.each(["rejection", "unmatched"] as const)(
+ "defers a delayed reveal until a pending z commit finishes with %s",
+ async (outcome) => {
+ vi.useFakeTimers();
+ const el = document.createElement("div");
+ el.id = "clip-a";
+ el.style.zIndex = "4";
+ el.style.position = "absolute";
+ document.body.appendChild(el);
+ usePlayerStore.getState().setElements([
+ {
+ id: "clip-a",
+ tag: "div",
+ start: 0,
+ duration: 1,
+ track: 0,
+ zIndex: 4,
+ hasExplicitZIndex: true,
+ },
+ ]);
+ let resolvePersist: ((result: DomEditPatchBatchesResult) => void) | undefined;
+ let rejectPersist: ((error: Error) => void) | undefined;
+ const persist = vi.fn(
+ () =>
+ new Promise<DomEditPatchBatchesResult>((resolve, reject) => {
+ resolvePersist = resolve;
+ rejectPersist = reject;
+ }),
+ );
+ let commit: ReorderCommit | undefined;
+ let scheduleReveal: ((element: HTMLElement, delayMs: number) => void) | undefined;
+
+ function Harness() {
+ ({ scheduleReveal } = useLayerRevealOverride({
+ isPlaying: false,
+ selectedElement: el,
+ }));
+ ({ handleDomZIndexReorderCommit: commit } = useElementLifecycleOps(
+ makeLifecycleOpsParams({ commitDomEditPatchBatches: persist }),
+ ));
+ return null;
+ }
+ const root = mountReactHarness(<Harness />);
+
+ let pending: Promise<unknown> | undefined;
+ act(() => {
+ scheduleReveal!(el, 10);
+ pending = commit!([
+ { element: el, zIndex: 8, id: "clip-a", sourceFile: "index.html", key: "clip-a" },
+ ]);
+ vi.advanceTimersByTime(10);
+ });
+
+ // The timer elapsed, but it must not capture optimistic z=8 as authored.
+ expect(el.style.zIndex).toBe("8");
+ expect(el.hasAttribute(LAYER_REVEAL_PRIOR_Z_ATTR)).toBe(false);
+
+ let rejection: unknown;
+ await act(async () => {
+ if (outcome === "rejection") rejectPersist!(new Error("save failed"));
+ else resolvePersist!({ durable: false, allMatched: false, changed: false });
+ try {
+ await pending;
+ } catch (error) {
+ rejection = error;
+ }
+ });
+ if (outcome === "rejection") expect(rejection).toBeInstanceOf(Error);
+
+ act(() => vi.advanceTimersByTime(16));
+ expect(el.style.zIndex).toBe(LAYER_REVEAL_LIFT_Z);
+ expect(el.getAttribute(LAYER_REVEAL_PRIOR_Z_ATTR)).toBe("4");
+ expect(usePlayerStore.getState().elements[0]?.zIndex).toBe(4);
+ act(() => root.unmount());
+ },
+ );
+
+ it("serializes overlapping commits through the shared gesture owner", async () => {
+ const el = document.createElement("div");
+ el.id = "clip-a";
+ el.style.zIndex = "1";
+ document.body.appendChild(el);
+ usePlayerStore.getState().setElements([
+ {
+ id: "clip-a",
+ tag: "div",
+ start: 0,
+ duration: 1,
+ track: 0,
+ zIndex: 1,
+ hasExplicitZIndex: true,
+ },
+ ]);
+ const firstFailure = new Error("first persist failed");
+ let rejectFirst: ((error: Error) => void) | undefined;
+ let resolveSecond: (() => void) | undefined;
+ const persist = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise<never>((_resolve, reject) => {
+ rejectFirst = reject;
+ }),
+ )
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveSecond = () => resolve({ durable: true, allMatched: true, changed: true });
+ }),
+ );
+ let commit: ReorderCommit | undefined;
+
+ function Harness() {
+ ({ handleDomZIndexReorderCommit: commit } = useElementLifecycleOps(
+ makeLifecycleOpsParams({ commitDomEditPatchBatches: persist }),
+ ));
+ return null;
+ }
+ const root = mountReactHarness(<Harness />);
+
+ let firstPending: Promise<unknown> | undefined;
+ let secondPending: Promise<unknown> | undefined;
+ act(() => {
+ firstPending = runZLaneGesture({
+ commitZ: () =>
+ commit!([
+ { element: el, zIndex: 2, id: "clip-a", sourceFile: "index.html", key: "clip-a" },
+ ]),
+ mirror: async () => true,
+ });
+ secondPending = runZLaneGesture({
+ commitZ: () =>
+ commit!([
+ { element: el, zIndex: 3, id: "clip-a", sourceFile: "index.html", key: "clip-a" },
+ ]),
+ mirror: async () => true,
+ });
+ });
+
+ expect(persist).toHaveBeenCalledTimes(1);
+ expect(el.style.zIndex).toBe("2");
+ expect(usePlayerStore.getState().elements[0]?.zIndex).toBe(2);
+
+ let rejection: unknown;
+ await act(async () => {
+ rejectFirst!(firstFailure);
+ try {
+ await firstPending;
+ } catch (error) {
+ rejection = error;
+ }
+ await Promise.resolve();
+ });
+
+ expect(rejection).toBe(firstFailure);
+ expect(persist).toHaveBeenCalledTimes(2);
+ expect(el.style.zIndex).toBe("3");
+ expect(usePlayerStore.getState().elements[0]?.zIndex).toBe(3);
+
+ await act(async () => {
+ resolveSecond!();
+ await secondPending;
+ });
+ expect(el.style.zIndex).toBe("3");
+ expect(usePlayerStore.getState().elements[0]?.zIndex).toBe(3);
+ act(() => root.unmount());
+ });
+
+ it.each(["deselection", "playback"] as const)(
+ "does not resurrect a reveal released by %s while persistence is pending",
+ async (releaseBy) => {
+ vi.useFakeTimers();
+ const el = document.createElement("div");
+ el.id = "clip-a";
+ el.style.zIndex = "4";
+ el.style.position = "static";
+ const other = document.createElement("div");
+ document.body.append(el, other);
+ const failure = new Error("persist failed");
+ let rejectPersist: ((error: Error) => void) | undefined;
+ const persist = vi.fn(
+ () =>
+ new Promise<never>((_resolve, reject) => {
+ rejectPersist = reject;
+ }),
+ );
+ let commit: ReorderCommit | undefined;
+ let scheduleReveal: ((element: HTMLElement, delayMs: number) => void) | undefined;
+
+ function Harness({
+ selectedElement,
+ isPlaying,
+ }: {
+ selectedElement: HTMLElement | null;
+ isPlaying: boolean;
+ }) {
+ ({ scheduleReveal } = useLayerRevealOverride({ isPlaying, selectedElement }));
+ ({ handleDomZIndexReorderCommit: commit } = useElementLifecycleOps(
+ makeLifecycleOpsParams({ commitDomEditPatchBatches: persist }),
+ ));
+ return null;
+ }
+
+ const root = mountReactHarness(<Harness selectedElement={el} isPlaying={false} />);
+ act(() => {
+ scheduleReveal!(el, 0);
+ vi.advanceTimersByTime(0);
+ });
+ expect(el.style.zIndex).toBe(LAYER_REVEAL_LIFT_Z);
+
+ let pending: Promise<unknown> | undefined;
+ act(() => {
+ pending = commit!([{ element: el, zIndex: 8, id: el.id, sourceFile: "index.html" }]);
+ });
+ expect(el.style.zIndex).toBe("8");
+ expect(el.hasAttribute(LAYER_REVEAL_PENDING_COMMIT_ATTR)).toBe(true);
+
+ act(() => {
+ root.render(
+ <Harness
+ selectedElement={releaseBy === "deselection" ? other : el}
+ isPlaying={releaseBy === "playback"}
+ />,
+ );
+ });
+
+ let rejection: unknown;
+ await act(async () => {
+ rejectPersist!(failure);
+ try {
+ await pending;
+ } catch (error) {
+ rejection = error;
+ }
+ });
+
+ expect(rejection).toBe(failure);
+ expect(el.style.zIndex).toBe("4");
+ expect(el.style.position).toBe("static");
+ expect(el.hasAttribute(LAYER_REVEAL_PRIOR_Z_ATTR)).toBe(false);
+ expect(el.hasAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR)).toBe(false);
+ expect(el.hasAttribute(LAYER_REVEAL_PENDING_COMMIT_ATTR)).toBe(false);
+ act(() => root.unmount());
+ },
+ );
+
it("rolls back only live and store state after an atomic reorder failure", async () => {
const writeProjectFile = vi.fn(async () => {});
const recordEdit = vi.fn(async () => {});
@@ -367,20 +736,17 @@ describe("useElementLifecycleOps — z-index reorder payload", () => {
let commit: ReorderCommit | undefined;
function Harness() {
- const { handleDomZIndexReorderCommit } = useElementLifecycleOps({
- activeCompPath: "index.html",
- showToast: vi.fn(),
- writeProjectFile,
- domEditSaveTimestampRef: { current: 0 },
- editHistory: { recordEdit },
- projectIdRef: { current: "demo" },
- reloadPreview: vi.fn(),
- clearDomSelection: vi.fn(),
- forceReloadSdkSession,
- commitDomEditPatchBatches: vi.fn(async () => {
- throw originalError;
+ const { handleDomZIndexReorderCommit } = useElementLifecycleOps(
+ makeLifecycleOpsParams({
+ writeProjectFile,
+ editHistory: { recordEdit },
+ projectIdRef: { current: "demo" },
+ forceReloadSdkSession,
+ commitDomEditPatchBatches: vi.fn(async () => {
+ throw originalError;
+ }),
}),
- });
+ );
commit = handleDomZIndexReorderCommit;
return null;
}
diff --git a/packages/studio/src/hooks/useElementLifecycleOps.ts b/packages/studio/src/hooks/useElementLifecycleOps.ts
index f8ac938d73..4eb8110c96 100644
--- a/packages/studio/src/hooks/useElementLifecycleOps.ts
+++ b/packages/studio/src/hooks/useElementLifecycleOps.ts
@@ -11,6 +11,14 @@ import {
readHfId,
type DomEditSelection,
} from "../components/editor/domEditing";
+import { LAYER_REVEAL_PRIOR_POSITION_ATTR } from "../player/lib/timelineElementHelpers";
+import {
+ beginLayerRevealCommit,
+ beginLayerZPersist,
+ completeLayerRevealCommit,
+ rollbackLayerRevealCommit,
+ type LayerRevealCommitOwnership,
+} from "../components/editor/useLayerRevealOverride";
import type { CommitDomEditPatchBatches, DomEditPatchBatch } from "./domEditCommitTypes";
interface UseElementLifecycleOpsParams extends DomEditCommitBaseParams {
@@ -25,6 +33,36 @@ interface UseElementLifecycleOpsParams extends DomEditCommitBaseParams {
onElementDeleted?: (selection: DomEditSelection) => void;
}
+// One coalesce key per z-reorder gesture. A monotonic counter — NOT Date.now()
+// / Math.random(), which the determinism rules forbid — matches the
+// laneChangeGestureSeq precedent in timelineClipDragCommit.ts: the key only has
+// to be unique per gesture and identical across the gesture's records.
+let zReorderGestureSeq = 0;
+
+/**
+ * Undo coalesce key for ONE z-reorder gesture — unique per call. The key
+ * carries the action kind + element ids for debuggability, plus a gesture
+ * sequence so two SEPARATE user actions (even the same action on the same
+ * selection) never share a key. That uniqueness is what makes the unbounded
+ * per-gesture coalesce window (see handleDomZIndexReorderCommit) safe: the
+ * fold can only ever merge records of the SAME gesture.
+ *
+ * Exported as THE single implementation of the key: the canvas z-order wiring
+ * (PreviewOverlays) mints it once per gesture and passes the same instance to
+ * both the z persist and the timeline lane mirror (useCanvasZOrderTimelineMirror)
+ * so editHistory folds the z write and the track write into one undo entry —
+ * recomputing the key per record would silently split the undo.
+ */
+export function zReorderCoalesceKey(
+ entries: ReadonlyArray<{ element: HTMLElement; id?: string; selector?: string }>,
+ actionKind?: string,
+): string {
+ const ids = entries
+ .map((e) => e.id ?? e.selector ?? e.element.getAttribute("data-hf-id") ?? "el")
+ .join(":");
+ return `z-reorder:${actionKind ?? "reorder"}:${ids}:g${zReorderGestureSeq++}`;
+}
+
export function useElementLifecycleOps({
activeCompPath,
showToast,
@@ -130,11 +168,11 @@ export function useElementLifecycleOps({
],
);
- // ponytail: z-index reorder folds every element patch for a source file in memory and sends
- // one patch-elements-batch request, so each file is persisted with one atomic disk write.
+ // Z-index reorder folds patches by source file, then sends one aggregate cross-file
+ // patch-element-batches request. The server refuses the whole gesture on any unmatched
+ // target and rolls back earlier file writes if a later write fails.
// No SDK reorder/reparent op exists; DOM sibling order stays server-authoritative if ever needed.
const handleDomZIndexReorderCommit = useCallback(
- // fallow-ignore-next-line complexity
(
entries: Array<{
element: HTMLElement;
@@ -149,88 +187,143 @@ export function useElementLifecycleOps({
actionKind?: string,
) => {
if (entries.length === 0) return Promise.resolve();
- // Resolver shadow (telemetry-only, decoupled from cutover): record whether
- // the SDK resolves each reordered element — the reorderElements op's targets.
- onReorderShadow?.(
- entries.map((e) => readHfId(e.element)).filter((id): id is string => id != null),
- );
- // The default key carries the action kind so two DIFFERENT actions on the
- // same element set (e.g. "bring-forward" then "send-backward" within the
- // coalesce window) never merge into one undo step. Callers that share a
- // gesture (lane moves) pass an explicit gestureCoalesceKey instead.
- const coalesceKey =
- gestureCoalesceKey ??
- `z-reorder:${actionKind ?? "reorder"}:${entries.map((e) => e.id ?? e.selector ?? e.element.getAttribute("data-hf-id") ?? "el").join(":")}`;
- const patchesBySourceFile = new Map<string, DomEditPatchBatch["patches"]>();
- const rollbacks: Array<() => void> = [];
- for (const entry of entries) {
- const priorZIndex = entry.element.style.zIndex;
- const priorPosition = entry.element.style.position;
- const priorStoreEntry = entry.key
- ? usePlayerStore.getState().elements.find((el) => (el.key ?? el.id) === entry.key)
- : undefined;
- let positionChanged = false;
- entry.element.style.zIndex = String(entry.zIndex);
- const patches: Array<{ type: "inline-style"; property: string; value: string }> = [
- { type: "inline-style", property: "z-index", value: String(entry.zIndex) },
- ];
+ // One async owner must bracket reveal tokens, optimistic DOM/store state,
+ // atomic persistence, rollback, and the final persistence-count release.
+ // Splitting those phases would make transaction ownership less explicit.
+ // fallow-ignore-next-line complexity
+ return (async () => {
+ const releaseZPersists = entries.map((entry) => beginLayerZPersist(entry.element));
try {
- const win = entry.element.ownerDocument?.defaultView;
- if (win && win.getComputedStyle(entry.element).position === "static") {
- entry.element.style.position = "relative";
- positionChanged = true;
- patches.push({ type: "inline-style", property: "position", value: "relative" });
+ // Resolver shadow (telemetry-only, decoupled from cutover): record whether
+ // the SDK resolves each reordered element — the reorderElements op's targets.
+ onReorderShadow?.(
+ entries.map((e) => readHfId(e.element)).filter((id): id is string => id != null),
+ );
+ // The default key carries the action kind so two DIFFERENT actions on the
+ // same element set (e.g. "bring-forward" then "send-backward" within the
+ // coalesce window) never merge into one undo step. Callers that share a
+ // gesture (lane moves) pass an explicit gestureCoalesceKey instead.
+ const coalesceKey = gestureCoalesceKey ?? zReorderCoalesceKey(entries, actionKind);
+ const patchesBySourceFile = new Map<string, DomEditPatchBatch["patches"]>();
+ const rollbacks: Array<() => void> = [];
+ const revealCommits: Array<{
+ element: HTMLElement;
+ ownership: LayerRevealCommitOwnership;
+ }> = [];
+ for (const entry of entries) {
+ const priorZIndex = entry.element.style.zIndex;
+ const priorPosition = entry.element.style.position;
+ const priorStoreEntry = entry.key
+ ? usePlayerStore.getState().elements.find((el) => (el.key ?? el.id) === entry.key)
+ : undefined;
+ let positionChanged = false;
+ // An active Layers-panel reveal lift on this element is consumed by
+ // this commit: the new z is the truth. Read the parked TRUE position
+ // for the static check below (the lift set a temporary
+ // position:relative that would otherwise mask the need to persist
+ // one), then drop the lift attributes so z readers stop reporting the
+ // stale prior (see useLayerRevealOverride / readLayerRevealPriorZ).
+ const liftPriorPosition = entry.element.getAttribute(LAYER_REVEAL_PRIOR_POSITION_ATTR);
+ const revealOwnership = beginLayerRevealCommit(entry.element);
+ if (revealOwnership) {
+ revealCommits.push({ element: entry.element, ownership: revealOwnership });
+ }
+ entry.element.style.zIndex = String(entry.zIndex);
+ const patches: Array<{ type: "inline-style"; property: string; value: string }> = [
+ { type: "inline-style", property: "z-index", value: String(entry.zIndex) },
+ ];
+ try {
+ const win = entry.element.ownerDocument?.defaultView;
+ const effectivePosition =
+ liftPriorPosition ??
+ (win ? win.getComputedStyle(entry.element).position : undefined);
+ if (effectivePosition === "static") {
+ entry.element.style.position = "relative";
+ positionChanged = true;
+ patches.push({ type: "inline-style", property: "position", value: "relative" });
+ }
+ } catch {
+ /* cross-origin or detached — skip */
+ }
+ if (entry.key) {
+ usePlayerStore
+ .getState()
+ .updateElement(entry.key, { zIndex: entry.zIndex, hasExplicitZIndex: true });
+ }
+ rollbacks.push(() => {
+ if (revealOwnership) {
+ rollbackLayerRevealCommit(entry.element, revealOwnership);
+ } else {
+ entry.element.style.zIndex = priorZIndex;
+ if (positionChanged) entry.element.style.position = priorPosition;
+ }
+ if (entry.key && priorStoreEntry) {
+ usePlayerStore.getState().updateElement(entry.key, {
+ zIndex: priorStoreEntry.zIndex,
+ hasExplicitZIndex: priorStoreEntry.hasExplicitZIndex,
+ });
+ }
+ });
+ const filePatches = patchesBySourceFile.get(entry.sourceFile) ?? [];
+ filePatches.push({
+ target: buildDomEditPatchTarget({
+ id: entry.id,
+ hfId: readHfId(entry.element),
+ selector: entry.selector,
+ selectorIndex: entry.selectorIndex,
+ }),
+ operations: patches,
+ });
+ patchesBySourceFile.set(entry.sourceFile, filePatches);
}
- } catch {
- /* cross-origin or detached — skip */
- }
- if (entry.key) {
- usePlayerStore
- .getState()
- .updateElement(entry.key, { zIndex: entry.zIndex, hasExplicitZIndex: true });
- }
- rollbacks.push(() => {
- entry.element.style.zIndex = priorZIndex;
- if (positionChanged) entry.element.style.position = priorPosition;
- if (entry.key && priorStoreEntry) {
- usePlayerStore.getState().updateElement(entry.key, {
- zIndex: priorStoreEntry.zIndex,
- hasExplicitZIndex: priorStoreEntry.hasExplicitZIndex,
+ const batches = [...patchesBySourceFile].map(([sourceFile, patches]) => ({
+ sourceFile,
+ patches,
+ }));
+ // Live z state changed with NO reload coming (skipReload below) — nudge
+ // DOM-derived views (Layers panel z-sort) to re-read the iframe.
+ usePlayerStore.getState().bumpZEditVersion();
+ const rollbackOptimisticState = () => {
+ for (const rollback of rollbacks) rollback();
+ usePlayerStore.getState().bumpZEditVersion();
+ };
+ // Resolves once every source-file batch is persisted so a same-file timing write
+ // can be ordered after it (see applyTimelineStackingReorder callers).
+ //
+ // skipReload: the live iframe DOM and the player store already hold the
+ // final z state (applied synchronously above), and the persisted patch is
+ // inline-style-only — a full iframe remount would only blink the preview.
+ // commitDomEditPatchBatches still falls back to reloading whenever the
+ // server reports an unmatched patch target (live DOM ≠ disk).
+ try {
+ const result = await commitDomEditPatchBatches(batches, {
+ label: "Reorder layers",
+ coalesceKey,
+ // Unbounded window: every key this commit records under is unique per
+ // gesture (zReorderCoalesceKey's gesture seq, or the lane drag's
+ // clip-lane-move:<seq>), so the fold can only merge records of the SAME
+ // gesture — and those records are separated by a server round-trip
+ // (move→z on a lane drag, z→lane-mirror on a canvas action), which
+ // under real network latency exceeds the 300ms default window.
+ coalesceMs: Number.POSITIVE_INFINITY,
+ skipReload: true,
});
+ if (!result.durable) {
+ rollbackOptimisticState();
+ return result;
+ }
+ for (const { element, ownership } of revealCommits) {
+ completeLayerRevealCommit(element, ownership);
+ }
+ return result;
+ } catch (error) {
+ rollbackOptimisticState();
+ throw error;
}
- });
- const filePatches = patchesBySourceFile.get(entry.sourceFile) ?? [];
- filePatches.push({
- target: buildDomEditPatchTarget({
- id: entry.id,
- hfId: readHfId(entry.element),
- selector: entry.selector,
- selectorIndex: entry.selectorIndex,
- }),
- operations: patches,
- });
- patchesBySourceFile.set(entry.sourceFile, filePatches);
- }
- const batches = [...patchesBySourceFile].map(([sourceFile, patches]) => ({
- sourceFile,
- patches,
- }));
- // Resolves once every source-file batch is persisted so a same-file timing write
- // can be ordered after it (see applyTimelineStackingReorder callers).
- //
- // skipReload: the live iframe DOM and the player store already hold the
- // final z state (applied synchronously above), and the persisted patch is
- // inline-style-only — a full iframe remount would only blink the preview.
- // commitDomEditPatchBatches still falls back to reloading whenever the
- // server reports an unmatched patch target (live DOM ≠ disk).
- return commitDomEditPatchBatches(batches, {
- label: "Reorder layers",
- coalesceKey,
- skipReload: true,
- }).catch((error) => {
- for (const rollback of rollbacks) rollback();
- throw error;
- });
+ } finally {
+ for (const release of releaseZPersists) release();
+ }
+ })();
},
[commitDomEditPatchBatches, onReorderShadow],
);
diff --git a/packages/studio/src/hooks/usePreviewPersistence.ts b/packages/studio/src/hooks/usePreviewPersistence.ts
index b6759485b9..0fbb50a5ec 100644
--- a/packages/studio/src/hooks/usePreviewPersistence.ts
+++ b/packages/studio/src/hooks/usePreviewPersistence.ts
@@ -10,7 +10,7 @@ import type { EditHistoryKind } from "../utils/editHistory";
import { createDomEditSaveQueue } from "../utils/domEditSaveQueue";
import { flushStudioPendingEdits } from "../utils/studioPendingEdits";
import { trackStudioEvent } from "../utils/studioTelemetry";
-import { applyUndoRestoreToPreview, type UndoRestoreFile } from "../utils/gsapSoftReload";
+import { applyUndoRestoreToPreview, type UndoRestoreFile } from "../utils/gsapUndoRestore";
import { usePlayerStore } from "../player";
/** The restore payload the undo/redo preview-sync consumes (from the history store). */
@@ -156,7 +156,7 @@ export function usePreviewPersistence({
// ── Queue / drain helpers ──
- const queueDomEditSave = useCallback((save: () => Promise<void>) => {
+ const queueDomEditSave = useCallback(<T>(save: () => Promise<T>): Promise<T> => {
return domEditSaveQueueRef.current?.enqueue(save) ?? save();
}, []);
diff --git a/packages/studio/src/hooks/useTimelineEditing.test.tsx b/packages/studio/src/hooks/useTimelineEditing.test.tsx
index 449d143bc3..491d13f071 100644
--- a/packages/studio/src/hooks/useTimelineEditing.test.tsx
+++ b/packages/studio/src/hooks/useTimelineEditing.test.tsx
@@ -5,6 +5,7 @@ import { createRoot } from "react-dom/client";
import { openComposition } from "@hyperframes/sdk";
import { afterEach, describe, expect, it, vi } from "vitest";
import { usePlayerStore, type TimelineElement } from "../player";
+import { jsonResponse, requestUrl } from "./fetchStubTestUtils";
import { useElementLifecycleOps } from "./useElementLifecycleOps";
import { useTimelineEditing } from "./useTimelineEditing";
@@ -165,7 +166,11 @@ type TimelineRecordEdit = NonNullable<
function renderTimelineEditingHookWithLifecycle(input: {
timelineElements: TimelineElement[];
iframe: HTMLIFrameElement;
- commitDomEditPatchBatches: ReturnType<typeof vi.fn<(...args: unknown[]) => Promise<void>>>;
+ commitDomEditPatchBatches: ReturnType<
+ typeof vi.fn<
+ (...args: unknown[]) => Promise<{ durable: boolean; allMatched: boolean; changed: boolean }>
+ >
+ >;
}): {
move: ReturnType<typeof useTimelineEditing>["handleTimelineElementMove"];
unmount: () => void;
@@ -209,19 +214,6 @@ function renderTimelineEditingHookWithLifecycle(input: {
return { move, unmount };
}
-function jsonResponse(body: unknown): Response {
- return new Response(JSON.stringify(body), {
- status: 200,
- headers: { "content-type": "application/json" },
- });
-}
-
-function requestUrl(input: Parameters<typeof fetch>[0]): string {
- if (typeof input === "string") return input;
- if (input instanceof URL) return input.toString();
- return input.url;
-}
-
async function flushAsyncWork(): Promise<void> {
for (let i = 0; i < 8; i += 1) {
await Promise.resolve();
@@ -233,24 +225,99 @@ async function flushAsyncWork(): Promise<void> {
* 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 },
-) {
+function stubProjectFetch(files: string | Record<string, string>, gsapBody?: unknown) {
+ // Keep this test server's capability, file-read, and mutation routes together;
+ // splitting the fixture would obscure the request sequence asserted by callers.
+ // fallow-ignore-next-line complexity
const fetchMock = vi.fn(async (input: Parameters<typeof fetch>[0]): Promise<Response> => {
const url = requestUrl(input);
+ if (url.includes("/api/projects/p1/gsap-mutation-capabilities")) {
+ return jsonResponse({ atomicOwnershipPairs: true });
+ }
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);
+ if (url.includes("/api/projects/p1/gsap-mutations/")) {
+ const path = decodeURIComponent(url.split("/gsap-mutations/")[1] ?? "index.html");
+ const content = typeof files === "string" ? files : (files[path] ?? "");
+ return jsonResponse(
+ gsapBody ?? { mutated: false, scriptText: null, before: content, after: content },
+ );
+ }
throw new Error(`Unexpected fetch: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
return fetchMock;
}
+/**
+ * One clip on track 0 + the editing hook wired to project "p1" — shared setup
+ * for the single-clip move-path tests (horizontal, vertical-only, track-only,
+ * diagonal) so their arrange blocks aren't clones of each other.
+ */
+function setupSingleClipHarness(options?: {
+ source?: string;
+ clipStyle?: string;
+ onZIndexCommit?: (entries: ZIndexEntry[]) => Promise<void>;
+}) {
+ const iframe = createPreviewIframe([{ id: "clip", track: 0, style: options?.clipStyle }]);
+ const clip = timelineElement({ id: "clip", track: 0, zIndex: 0 });
+ const commit =
+ options?.onZIndexCommit ??
+ vi.fn<(entries: ZIndexEntry[]) => Promise<void>>().mockResolvedValue(undefined);
+ const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
+ const reloadPreview = vi.fn();
+ const fetchMock = stubProjectFetch(
+ options?.source ?? '<div id="clip" data-start="0" data-track-index="0"></div>',
+ );
+ const hook = renderTimelineEditingHook({
+ timelineElements: [clip],
+ iframe,
+ onZIndexCommit: commit,
+ projectId: "p1",
+ writeProjectFile,
+ recordEdit: vi.fn(async () => {}),
+ reloadPreview,
+ });
+ return { iframe, clip, commit, writeProjectFile, reloadPreview, fetchMock, ...hook };
+}
+
+/** Assert a lane write landed in both the live iframe DOM and the persisted file. */
+function expectLanePersisted(
+ iframe: HTMLIFrameElement,
+ writeProjectFile: { mock: { calls: unknown[][] } },
+ track: string,
+): void {
+ const doc = iframe.contentDocument;
+ if (!doc) throw new Error("Expected iframe document");
+ expect(doc.getElementById("clip")?.getAttribute("data-track-index")).toBe(track);
+ expect(writeProjectFile.mock.calls[0]![1]).toContain(`data-track-index="${track}"`);
+}
+
+/**
+ * Two 1s clips — a@0s on track 0, b@1s on track 1 — plus the matching iframe.
+ * Shared by the group-move tests; `bSourceFile` puts b in its own file for the
+ * cross-file partition test.
+ */
+function makeTwoClipPair(bSourceFile?: string) {
+ const iframe = createPreviewIframe([
+ { id: "a", track: 0 },
+ { id: "b", track: 1 },
+ ]);
+ const a = timelineElement({ id: "a", track: 0, zIndex: 0, start: 0, duration: 1 });
+ const b = timelineElement({
+ id: "b",
+ track: 1,
+ zIndex: 0,
+ start: 1,
+ duration: 1,
+ sourceFile: bSourceFile,
+ });
+ return { iframe, a, b };
+}
+
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>`,
@@ -270,7 +337,12 @@ async function setupRootDurationFallback() {
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 });
+ stubProjectFetch(ROOT_DURATION_FALLBACK_SOURCE, {
+ mutated: false,
+ scriptText: null,
+ before: ROOT_DURATION_FALLBACK_SOURCE,
+ after: ROOT_DURATION_FALLBACK_SOURCE,
+ });
usePlayerStore.getState().setDuration(4);
const hook = renderTimelineEditingHook({
timelineElements: [clip],
@@ -457,7 +529,9 @@ describe("useTimelineEditing timeline z-index reorder", () => {
]);
const front = timelineElement({ id: "front", track: 0, zIndex: 0 });
const back = timelineElement({ id: "back", track: 1, zIndex: 0 });
- const commitDomEditPatchBatches = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
+ const commitDomEditPatchBatches = vi.fn<
+ (...args: unknown[]) => Promise<{ durable: boolean; allMatched: boolean; changed: boolean }>
+ >(async () => ({ durable: true, allMatched: true, changed: true }));
const { move, unmount } = renderTimelineEditingHookWithLifecycle({
timelineElements: [front, back],
iframe,
@@ -502,7 +576,9 @@ describe("useTimelineEditing timeline z-index reorder", () => {
]);
const saveError = new Error("save failed");
const commitDomEditPatchBatches = vi
- .fn<(...args: unknown[]) => Promise<void>>()
+ .fn<
+ (...args: unknown[]) => Promise<{ durable: boolean; allMatched: boolean; changed: boolean }>
+ >()
.mockRejectedValueOnce(saveError);
const { move, unmount } = renderTimelineEditingHookWithLifecycle({
timelineElements: [front, back],
@@ -566,8 +642,12 @@ describe("useTimelineEditing timeline z-index reorder", () => {
releaseBatch = resolve;
});
const commitDomEditPatchBatches = vi
- .fn<(...args: unknown[]) => Promise<void>>()
- .mockReturnValueOnce(batchSave);
+ .fn<
+ (...args: unknown[]) => Promise<{ durable: boolean; allMatched: boolean; changed: boolean }>
+ >()
+ .mockReturnValueOnce(
+ batchSave.then(() => ({ durable: true, allMatched: true, changed: true })),
+ );
const { move, unmount } = renderTimelineEditingHookWithLifecycle({
timelineElements: [front, back],
iframe,
@@ -608,98 +688,59 @@ describe("useTimelineEditing timeline z-index reorder", () => {
});
it("keeps horizontal-only drag on the timing and GSAP shift path without z-index writes", async () => {
- const iframe = createPreviewIframe([{ id: "clip", track: 0 }]);
- const clip = timelineElement({ id: "clip", track: 0, zIndex: 0 });
- const commit = vi.fn<(entries: ZIndexEntry[]) => Promise<void>>().mockResolvedValue(undefined);
- const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
- const recordEdit = vi.fn<TimelineRecordEdit>(async (_entry) => {});
- const reloadPreview = vi.fn();
- const fetchMock = stubProjectFetch('<div id="clip" data-start="0" data-track-index="0"></div>');
- const { move, unmount } = renderTimelineEditingHook({
- timelineElements: [clip],
- iframe,
- onZIndexCommit: commit,
- projectId: "p1",
- writeProjectFile,
- recordEdit,
- reloadPreview,
- });
+ const h = setupSingleClipHarness();
await act(async () => {
- await move(clip, { start: 1.25, track: clip.track });
+ await h.move(h.clip, { start: 1.25, track: h.clip.track });
});
- const doc = iframe.contentDocument;
+ const doc = h.iframe.contentDocument;
if (!doc) throw new Error("Expected iframe document");
expect(doc.getElementById("clip")?.getAttribute("data-start")).toBe("1.25");
expect(doc.getElementById("clip")?.getAttribute("data-track-index")).toBe("0");
- expect(commit).not.toHaveBeenCalled();
- expect(writeProjectFile.mock.calls[0]![1]).toContain('data-start="1.25"');
- expect(writeProjectFile.mock.calls[0]![1]).toContain('data-track-index="0"');
- expect(writeProjectFile.mock.calls[0]![1]).not.toContain("z-index");
+ expect(h.commit).not.toHaveBeenCalled();
+ expect(h.writeProjectFile.mock.calls[0]![1]).toContain('data-start="1.25"');
+ expect(h.writeProjectFile.mock.calls[0]![1]).toContain('data-track-index="0"');
+ expect(h.writeProjectFile.mock.calls[0]![1]).not.toContain("z-index");
expect(
- fetchMock.mock.calls.some((call) => requestUrl(call[0]).includes("gsap-mutations")),
+ h.fetchMock.mock.calls.some((call) => requestUrl(call[0]).includes("gsap-mutations")),
).toBe(true);
- unmount();
+ h.unmount();
});
it("persists a vertical-only lane move (start unchanged) through the single-element fallback", async () => {
// Regression: `if (!startChanged) return` ran BEFORE the file persist, so a
// pure lane change routed through onMoveElement (no onMoveElements wired)
// wrote NOTHING — the lane snapped back on the next reload.
- const iframe = createPreviewIframe([{ id: "clip", track: 0 }]);
- const clip = timelineElement({ id: "clip", track: 0, zIndex: 0 });
- const commit = vi.fn<(entries: ZIndexEntry[]) => Promise<void>>().mockResolvedValue(undefined);
- const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
- stubProjectFetch('<div id="clip" data-start="0" data-track-index="0"></div>');
- const { move, unmount } = renderTimelineEditingHook({
- timelineElements: [clip],
- iframe,
- onZIndexCommit: commit,
- projectId: "p1",
- writeProjectFile,
- recordEdit: vi.fn(async () => {}),
- });
+ const h = setupSingleClipHarness();
await act(async () => {
// Vertical-only: same start, new track (already authored-space on this path).
- await move(clip, { start: clip.start, track: 2 });
+ await h.move(h.clip, { start: h.clip.start, track: 2 });
});
- const doc = iframe.contentDocument;
- if (!doc) throw new Error("Expected iframe document");
- // Live DOM patched so a pre-reload re-discovery doesn't snap the lane back...
- expect(doc.getElementById("clip")?.getAttribute("data-track-index")).toBe("2");
- // ...and the file write carries the new data-track-index with start intact.
- expect(writeProjectFile).toHaveBeenCalled();
- expect(writeProjectFile.mock.calls[0]![1]).toContain('data-track-index="2"');
- expect(writeProjectFile.mock.calls[0]![1]).toContain('data-start="0"');
+ // Live DOM patched (no pre-reload lane snap-back) and the file write
+ // carries the new data-track-index with start intact.
+ expectLanePersisted(h.iframe, h.writeProjectFile, "2");
+ expect(h.writeProjectFile.mock.calls[0]![1]).toContain('data-start="0"');
- unmount();
+ h.unmount();
});
it("orders the timing write after the z-index commit so a diagonal drag can't clobber the restack", async () => {
- const iframe = createPreviewIframe([
- { id: "clip", track: 0, style: "position: relative; z-index: 0" },
- ]);
- const clip = timelineElement({ id: "clip", track: 0, zIndex: 0 });
// Gate the z-index commit so we can observe whether the timing write waits.
let releaseCommit!: () => void;
const commitGate = new Promise<void>((resolve) => {
releaseCommit = resolve;
});
- const commit = vi.fn<(entries: ZIndexEntry[]) => Promise<void>>().mockReturnValue(commitGate);
- const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
- stubProjectFetch('<div id="clip" data-start="0" data-track-index="0"></div>');
- const { move, unmount } = renderTimelineEditingHook({
- timelineElements: [clip],
- iframe,
- onZIndexCommit: commit,
- projectId: "p1",
- writeProjectFile,
- recordEdit: vi.fn(async () => {}),
+ const h = setupSingleClipHarness({
+ clipStyle: "position: relative; z-index: 0",
+ onZIndexCommit: vi
+ .fn<(entries: ZIndexEntry[]) => Promise<void>>()
+ .mockReturnValue(commitGate),
});
+ const { clip, commit, writeProjectFile, move, unmount } = h;
// Diagonal drag: both a time move (start change) and a restack (z-index change).
let movePromise!: Promise<unknown>;
@@ -784,19 +825,7 @@ describe("useTimelineEditing timeline z-index reorder", () => {
"index.html": '<div id="a" data-start="0" data-duration="1"></div>',
"scene.html": '<div id="b" data-start="1" data-duration="1"></div>',
};
- const iframe = createPreviewIframe([
- { id: "a", track: 0 },
- { id: "b", track: 1 },
- ]);
- const a = timelineElement({ id: "a", track: 0, zIndex: 0, start: 0, duration: 1 });
- const b = timelineElement({
- id: "b",
- track: 1,
- zIndex: 0,
- start: 1,
- duration: 1,
- sourceFile: "scene.html",
- });
+ const { iframe, a, b } = makeTwoClipPair("scene.html");
const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
const recordEdit = vi.fn<TimelineRecordEdit>(async (_entry) => {});
stubProjectFetch(files);
@@ -867,6 +896,148 @@ describe("useTimelineEditing timeline z-index reorder", () => {
unmount();
});
+ it("skips the GSAP fallback and reload for a TRACK-ONLY group move (z-mirror lane move)", async () => {
+ // The mirrored z-order lane move persists {start: unchanged, track: new}.
+ // Nothing timing-related changed — data-track-index is never read by the
+ // renderer — so the persist must NOT be followed by the GSAP round-trip or
+ // the full preview reload (the reload is what blinked the canvas).
+ const h = setupSingleClipHarness({
+ source: '<div id="clip" data-start="0" data-duration="2" data-track-index="0"></div>',
+ });
+
+ await act(async () => {
+ await h.groupMove([{ element: h.clip, start: h.clip.start, track: 2 }]);
+ await flushAsyncWork();
+ });
+
+ // The lane write still persisted (live DOM + file)...
+ expectLanePersisted(h.iframe, h.writeProjectFile, "2");
+ expect(h.writeProjectFile).toHaveBeenCalledTimes(1);
+ // ...but no GSAP mutation ran and the preview was NOT reloaded.
+ expect(
+ h.fetchMock.mock.calls.some((call) => requestUrl(call[0]).includes("gsap-mutations")),
+ ).toBe(false);
+ expect(h.reloadPreview).not.toHaveBeenCalled();
+
+ h.unmount();
+ });
+
+ it("rebinds the preview in place (no blink) for a time-move of a no-domId clip", async () => {
+ // The gap-close blink path: "Close gap" issues pure TIME moves through
+ // handleTimelineGroupMove. A selector-addressed clip (no domId — e.g. a
+ // .sub caption) has no id-addressed GSAP tweens, so the mutation step has
+ // nothing to rewrite and used to fall through to a full reloadPreview().
+ // The sync must instead rebind the runtime timing in place — seek + rebind
+ // re-derive the clip windows from the already-patched DOM — WITHOUT
+ // re-executing any script (a comp's init-style scripts, e.g. a three.js
+ // setup, must never run twice) and without the full-reload blink.
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ const doc = iframe.contentDocument;
+ if (!doc) throw new Error("Expected iframe document");
+ doc.body.innerHTML =
+ '<div class="cap" data-start="2" data-duration="1" data-track-index="0"></div>';
+ const liveScript = doc.createElement("script");
+ liveScript.textContent =
+ 'window.__timelines = window.__timelines || {}; window.__timelines["root"] = { kill: function () {} };';
+ doc.body.appendChild(liveScript);
+ const win = iframe.contentWindow as unknown as Record<string, unknown>;
+ win.gsap = { timeline: vi.fn(), set: vi.fn() };
+ win.__timelines = { root: { kill: vi.fn() } };
+ win.__hfForceTimelineRebind = vi.fn();
+ win.__player = { getTime: () => 0, seek: vi.fn() };
+
+ const cap: TimelineElement = {
+ ...timelineElement({ id: "cap", track: 0, zIndex: 0, start: 2, duration: 1 }),
+ domId: undefined,
+ selector: ".cap",
+ selectorIndex: 0,
+ };
+ const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
+ const reloadPreview = vi.fn();
+ const fetchMock = stubProjectFetch(
+ '<div class="cap" data-hf-id="hf-cap" data-start="2" data-duration="1" data-track-index="0"></div>',
+ );
+ const { groupMove, unmount } = renderTimelineEditingHook({
+ timelineElements: [cap],
+ iframe,
+ onZIndexCommit: vi.fn().mockResolvedValue(undefined),
+ projectId: "p1",
+ writeProjectFile,
+ recordEdit: vi.fn(async () => {}),
+ reloadPreview,
+ });
+
+ await act(async () => {
+ // Mirror timelineGapCommit: a pure time move keeping the current lane.
+ await groupMove([{ element: cap, start: 1, track: cap.track }]);
+ await flushAsyncWork();
+ });
+
+ // The move persisted (live DOM + file)...
+ expect(doc.querySelector(".cap")?.getAttribute("data-start")).toBe("1");
+ expect(writeProjectFile.mock.calls[0]![1]).toContain('data-start="1"');
+ // ...no GSAP mutation ran (nothing id-addressed to rewrite)...
+ expect(
+ fetchMock.mock.calls.some((call) => requestUrl(call[0]).includes("gsap-mutations")),
+ ).toBe(false);
+ // ...and the preview was rebound in place, NOT full-reloaded (blink),
+ // with the live script element left untouched (no re-execution).
+ expect(reloadPreview).not.toHaveBeenCalled();
+ expect(win.__hfForceTimelineRebind).toHaveBeenCalledTimes(1);
+ expect(doc.body.contains(liveScript)).toBe(true);
+ expect(doc.querySelectorAll("script")).toHaveLength(1);
+
+ unmount();
+ });
+
+ it("keeps the GSAP fallback + reload for a MIXED batch (any start change)", async () => {
+ // One clip changes lane only, the other shifts in time — the batch is not
+ // track-only, so the existing behavior (GSAP shift + full reload when no
+ // rewritten scriptText comes back — this stub iframe has no runtime rebind
+ // hook, so the in-place rebind can't apply) must be preserved.
+ const source = [
+ '<div id="a" data-start="0" data-duration="1" data-track-index="0"></div>',
+ '<div id="b" data-start="1" data-duration="1" data-track-index="1"></div>',
+ ].join("\n");
+ const { iframe, a, b } = makeTwoClipPair();
+ const writeProjectFile = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
+ const reloadPreview = vi.fn();
+ const fetchMock = stubProjectFetch(source, {
+ mutated: false,
+ scriptText: null,
+ before: source,
+ after: source,
+ });
+ const { groupMove, unmount } = renderTimelineEditingHook({
+ timelineElements: [a, b],
+ iframe,
+ onZIndexCommit: vi.fn().mockResolvedValue(undefined),
+ projectId: "p1",
+ writeProjectFile,
+ recordEdit: vi.fn(async () => {}),
+ reloadPreview,
+ });
+
+ await act(async () => {
+ await groupMove([
+ { element: a, start: a.start, track: 2 },
+ { element: b, start: 1.5, track: b.track },
+ ]);
+ await flushAsyncWork();
+ });
+
+ expect(writeProjectFile).toHaveBeenCalledTimes(1);
+ // The time-shifted clip still goes through the GSAP shift endpoint...
+ expect(
+ fetchMock.mock.calls.some((call) => requestUrl(call[0]).includes("gsap-mutations")),
+ ).toBe(true);
+ // ...and with no rewritten scriptText the sync escalates to one full reload.
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+
+ unmount();
+ });
+
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 });
@@ -949,79 +1120,56 @@ describe("useTimelineEditing duration rollback on failed persist", () => {
return { iframe, clip, hook, writeError };
}
- it("rolls back the store duration and live root when a move persist fails", async () => {
- const { iframe, clip, hook, writeError } = setupFailedPersist();
-
+ /**
+ * Run a persist that must reject with the harness's writeError, then assert
+ * the store duration AND the live root rolled back to the pre-edit 4s —
+ * the shared act/assert core of the four failed-persist tests below.
+ */
+ async function expectPersistRollback(
+ ctx: ReturnType<typeof setupFailedPersist>,
+ run: () => Promise<unknown>,
+ ): Promise<void> {
let rejection: unknown;
await act(async () => {
- // Move past the end: the optimistic sync grows the readout to 5s.
- await hook.move(clip, { start: 3, track: clip.track }).catch((error) => {
+ await run().catch((error) => {
rejection = error;
});
await flushAsyncWork();
});
-
- expect(rejection).toBe(writeError);
+ expect(rejection).toBe(ctx.writeError);
expect(usePlayerStore.getState().duration).toBe(4);
- expect(rootDurationAttr(iframe)).toBe("4");
+ expect(rootDurationAttr(ctx.iframe)).toBe("4");
+ }
- hook.unmount();
+ it("rolls back the store duration and live root when a move persist fails", async () => {
+ const ctx = setupFailedPersist();
+ // Move past the end: the optimistic sync grows the readout to 5s.
+ await expectPersistRollback(ctx, () =>
+ ctx.hook.move(ctx.clip, { start: 3, track: ctx.clip.track }),
+ );
+ ctx.hook.unmount();
});
it("rolls back the store duration and live root when a resize persist fails", async () => {
- const { iframe, clip, hook, writeError } = setupFailedPersist();
-
- let rejection: unknown;
- await act(async () => {
- await hook
- .resize(clip, { start: 0, duration: 6, playbackStart: undefined })
- .catch((error) => {
- rejection = error;
- });
- await flushAsyncWork();
- });
-
- expect(rejection).toBe(writeError);
- expect(usePlayerStore.getState().duration).toBe(4);
- expect(rootDurationAttr(iframe)).toBe("4");
-
- hook.unmount();
+ const ctx = setupFailedPersist();
+ await expectPersistRollback(ctx, () =>
+ ctx.hook.resize(ctx.clip, { start: 0, duration: 6, playbackStart: undefined }),
+ );
+ ctx.hook.unmount();
});
it("rolls back the store duration and live root when a group move persist fails", async () => {
- const { iframe, clip, hook, writeError } = setupFailedPersist();
-
- let rejection: unknown;
- await act(async () => {
- await hook.groupMove([{ element: clip, start: 3.5 }]).catch((error) => {
- rejection = error;
- });
- await flushAsyncWork();
- });
-
- expect(rejection).toBe(writeError);
- expect(usePlayerStore.getState().duration).toBe(4);
- expect(rootDurationAttr(iframe)).toBe("4");
-
- hook.unmount();
+ const ctx = setupFailedPersist();
+ await expectPersistRollback(ctx, () => ctx.hook.groupMove([{ element: ctx.clip, start: 3.5 }]));
+ ctx.hook.unmount();
});
it("rolls back the store duration and live root when a group resize persist fails", async () => {
- const { iframe, clip, hook, writeError } = setupFailedPersist();
-
- let rejection: unknown;
- await act(async () => {
- await hook.groupResize([{ element: clip, start: 0, duration: 7 }]).catch((error) => {
- rejection = error;
- });
- await flushAsyncWork();
- });
-
- expect(rejection).toBe(writeError);
- expect(usePlayerStore.getState().duration).toBe(4);
- expect(rootDurationAttr(iframe)).toBe("4");
-
- hook.unmount();
+ const ctx = setupFailedPersist();
+ await expectPersistRollback(ctx, () =>
+ ctx.hook.groupResize([{ element: ctx.clip, start: 0, duration: 7 }]),
+ );
+ ctx.hook.unmount();
});
it("rolls back the store duration and live root when a delete persist fails", async () => {
diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.ts
index 1727521dbd..44b680af69 100644
--- a/packages/studio/src/hooks/useTimelineEditing.ts
+++ b/packages/studio/src/hooks/useTimelineEditing.ts
@@ -31,6 +31,7 @@ import {
useTimelineTrackVisibilityEditing,
} from "./timelineTrackVisibility";
import { useTimelineGroupEditing } from "./useTimelineGroupEditing";
+import { serializeZLaneGesture } from "../components/nle/zLaneGesture";
import { sdkTimingPersist } from "../utils/sdkCutover";
import type { UseTimelineEditingOptions } from "./useTimelineEditingTypes";
@@ -127,105 +128,108 @@ export function useTimelineEditing({
const handleTimelineElementMove = useCallback(
// fallow-ignore-next-line complexity
(element: TimelineElement, updates: TimelineMoveUpdates) => {
- const targetPath = element.sourceFile || activeCompPath || "index.html";
- const startChanged = updates.start !== element.start;
- // A vertical-only lane move arrives with start unchanged but track changed
- // (on this single-element path the drag commit has already folded the
- // AUTHORED persist track into updates.track). It must persist like any
- // other move — early-returning on !startChanged alone silently dropped
- // the file write, so the lane snapped back on reload.
- const trackChanged = updates.track !== element.track;
+ const commitMove = () => {
+ const targetPath = element.sourceFile || activeCompPath || "index.html";
+ const startChanged = updates.start !== element.start;
+ // A vertical-only lane move arrives with start unchanged but track changed
+ // (on this single-element path the drag commit has already folded the
+ // AUTHORED persist track into updates.track). It must persist like any
+ // other move — early-returning on !startChanged alone silently dropped
+ // the file write, so the lane snapped back on reload.
+ const trackChanged = updates.track !== element.track;
- if (startChanged || trackChanged) {
- const liveAttrs: Array<[string, string]> = [];
- if (startChanged) {
- liveAttrs.push(["data-start", formatTimelineAttributeNumber(updates.start)]);
- }
- if (trackChanged) {
- liveAttrs.push(["data-track-index", formatTimelineAttributeNumber(updates.track)]);
+ if (startChanged || trackChanged) {
+ const liveAttrs: Array<[string, string]> = [];
+ if (startChanged) {
+ liveAttrs.push(["data-start", formatTimelineAttributeNumber(updates.start)]);
+ }
+ if (trackChanged) {
+ liveAttrs.push(["data-track-index", formatTimelineAttributeNumber(updates.track)]);
+ }
+ patchIframeDomTiming(previewIframeRef.current, element, liveAttrs, activeCompPath);
}
- patchIframeDomTiming(previewIframeRef.current, element, liveAttrs);
- }
- const reorderDone = applyTimelineStackingReorder({
- element,
- stackingReorder: updates.stackingReorder,
- timelineElements,
- iframe: previewIframeRef.current,
- activeCompPath,
- commit: handleDomZIndexReorderCommitRef?.current,
- });
+ const reorderDone = applyTimelineStackingReorder({
+ element,
+ stackingReorder: updates.stackingReorder,
+ timelineElements,
+ iframe: previewIframeRef.current,
+ activeCompPath,
+ commit: handleDomZIndexReorderCommitRef?.current,
+ });
- if (!startChanged && !trackChanged) return reorderDone;
+ if (!startChanged && !trackChanged) return reorderDone;
- // Snapshot the duration BEFORE the optimistic updates below so a failed
- // persist can roll the readout + live root back (see captureDurationRollback).
- const rollbackDuration = captureDurationRollback(previewIframeRef.current);
- // 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), from the just-patched live DOM. See syncPreviewContentDuration.
- syncPreviewContentDuration(previewIframeRef.current);
+ // Snapshot the duration BEFORE the optimistic updates below so a failed
+ // persist can roll the readout + live root back (see captureDurationRollback).
+ const rollbackDuration = captureDurationRollback(previewIframeRef.current);
+ // 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), from the just-patched live DOM. See syncPreviewContentDuration.
+ syncPreviewContentDuration(previewIframeRef.current);
- const buildMovePatches: PersistTimelineEditInput["buildPatches"] = (original, target) => {
- // Persist lane changes too — data-start-only writes let reload snap the lane back.
- const track = trackChanged ? updates.track : undefined;
- return buildTimelineMoveTimingPatch(
- original,
- target,
- updates.start,
- element.duration,
- track,
- );
- };
- const coalesceKey = `timeline-move:${element.hfId ?? element.id}`;
- const moveFallback = () =>
- enqueueEdit(element, "Move timeline clip", buildMovePatches, coalesceKey).then(() =>
- // Soft-reload with the server's rewritten GSAP script — the timing-only move already patched
- // DOM + store, so swapping the script avoids the all-clips flash; falls back to reloadPreview().
- finishClipTimingFallback({
- iframe: previewIframeRef.current,
- reloadPreview,
- projectId: projectIdRef.current,
- targetPath,
- domId: element.domId,
- label: "Move timeline clip",
- coalesceKey,
- recordEdit,
- edit: { kind: "shift", delta: updates.start - element.start },
- }),
- );
- return reorderDone
- .then(() => {
- // The SDK setTiming path writes start only — a lane change must take
- // the fallback, whose patch builder writes data-track-index too.
- if (sdkSession && element.hfId && !needsExtension && !trackChanged) {
- return sdkTimingPersist(
- element.hfId,
+ const buildMovePatches: PersistTimelineEditInput["buildPatches"] = (original, target) => {
+ // Persist lane changes too — data-start-only writes let reload snap the lane back.
+ const track = trackChanged ? updates.track : undefined;
+ return buildTimelineMoveTimingPatch(
+ original,
+ target,
+ updates.start,
+ element.duration,
+ track,
+ );
+ };
+ const coalesceKey = `timeline-move:${element.hfId ?? element.id}`;
+ const moveFallback = () =>
+ enqueueEdit(element, "Move timeline clip", buildMovePatches, coalesceKey).then(() =>
+ // Soft-reload with the server's rewritten GSAP script — the timing-only move already patched
+ // DOM + store, so swapping the script avoids the all-clips flash; falls back to reloadPreview().
+ finishClipTimingFallback({
+ iframe: previewIframeRef.current,
+ reloadPreview,
+ projectId: projectIdRef.current,
targetPath,
- { start: updates.start },
- sdkSession,
- {
- editHistory: { recordEdit },
- writeProjectFile,
- reloadPreview,
- domEditSaveTimestampRef,
- compositionPath: activeCompPath,
- // Capture on-disk bytes as the undo `before` so undoing a timing move
- // restores the file verbatim, not a normalized full-DOM re-emit.
- readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path),
- },
- { label: "Move timeline clip", coalesceKey },
- ).then((handled) => {
- if (!handled) return moveFallback();
- });
- }
- return moveFallback();
- })
- .catch((error) => {
- // Failed persist: revert the optimistic duration readout + live root.
- rollbackDuration();
- throw error;
- });
+ domId: element.domId,
+ label: "Move timeline clip",
+ coalesceKey,
+ recordEdit,
+ edit: { kind: "shift", delta: updates.start - element.start },
+ }),
+ );
+ return reorderDone
+ .then(() => {
+ // The SDK setTiming path writes start only — a lane change must take
+ // the fallback, whose patch builder writes data-track-index too.
+ if (sdkSession && element.hfId && !needsExtension && !trackChanged) {
+ return sdkTimingPersist(
+ element.hfId,
+ targetPath,
+ { start: updates.start },
+ sdkSession,
+ {
+ editHistory: { recordEdit },
+ writeProjectFile,
+ reloadPreview,
+ domEditSaveTimestampRef,
+ compositionPath: activeCompPath,
+ // Capture on-disk bytes as the undo `before` so undoing a timing move
+ // restores the file verbatim, not a normalized full-DOM re-emit.
+ readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path),
+ },
+ { label: "Move timeline clip", coalesceKey },
+ ).then((handled) => {
+ if (!handled) return moveFallback();
+ });
+ }
+ return moveFallback();
+ })
+ .catch((error) => {
+ // Failed persist: revert the optimistic duration readout + live root.
+ rollbackDuration();
+ throw error;
+ });
+ };
+ return updates.stackingReorder ? serializeZLaneGesture(commitMove) : commitMove();
},
[
previewIframeRef,
@@ -261,7 +265,7 @@ export function useTimelineEditing({
: "data-media-start";
liveAttrs.push([liveAttr, formatTimelineAttributeNumber(updates.playbackStart)]);
}
- patchIframeDomTiming(previewIframeRef.current, element, liveAttrs);
+ patchIframeDomTiming(previewIframeRef.current, element, liveAttrs, activeCompPath);
// Snapshot the duration BEFORE the optimistic updates below so a failed
// persist can roll the readout + live root back (see captureDurationRollback).
const rollbackDuration = captureDurationRollback(previewIframeRef.current);
diff --git a/packages/studio/src/hooks/useTimelineEditingTypes.ts b/packages/studio/src/hooks/useTimelineEditingTypes.ts
index 6689169a8d..a8660cc707 100644
--- a/packages/studio/src/hooks/useTimelineEditingTypes.ts
+++ b/packages/studio/src/hooks/useTimelineEditingTypes.ts
@@ -23,7 +23,7 @@ export type TimelineZIndexReorderCommit = (
key?: string;
}>,
coalesceKey?: string,
-) => Promise<void>;
+) => Promise<import("./domEditCommitTypes").DomEditPatchBatchesResult | undefined | void>;
export interface UseTimelineEditingOptions {
projectId: string | null;
diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.ts
index 3dace0f6f6..71e37a5616 100644
--- a/packages/studio/src/hooks/useTimelineGroupEditing.ts
+++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts
@@ -37,6 +37,8 @@ export interface TimelineGroupResizeChange {
export interface TimelineGroupCommitOptions {
beforeTiming?: Promise<void>;
coalesceKey?: string;
+ /** Per-entry undo coalesce window override (ms) — see EditHistoryEntry.coalesceMs. */
+ coalesceMs?: number;
}
interface UseTimelineGroupEditingOptions {
@@ -137,6 +139,7 @@ export function useTimelineGroupEditing({
label: string,
batchChanges: PersistTimelineBatchChange[],
coalesceKey: string,
+ coalesceMs?: number,
) => {
await persistTimelineBatchEdit({
projectId,
@@ -148,6 +151,7 @@ export function useTimelineGroupEditing({
domEditSaveTimestampRef,
pendingTimelineEditPathRef,
coalesceKey,
+ coalesceMs,
});
forceReloadSdkSession?.();
},
@@ -176,6 +180,7 @@ export function useTimelineGroupEditing({
needsExtension: boolean;
label: string;
coalesceKey: string;
+ coalesceMs?: number;
}): Promise<boolean> => {
const sharedPath = allChangesSharePath(input.changes, activeCompPath);
const canUseSdk =
@@ -196,7 +201,7 @@ export function useTimelineGroupEditing({
compositionPath: activeCompPath,
readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path),
},
- { label: input.label, coalesceKey: input.coalesceKey },
+ { label: input.label, coalesceKey: input.coalesceKey, coalesceMs: input.coalesceMs },
);
},
[
@@ -220,20 +225,38 @@ export function useTimelineGroupEditing({
if (change.track != null) {
attrs.push(["data-track-index", formatTimelineAttributeNumber(change.track)]);
}
- patchIframeDomTiming(previewIframeRef.current, change.element, attrs);
+ patchIframeDomTiming(previewIframeRef.current, change.element, attrs, activeCompPath);
}
+ // TRACK-ONLY batch: every change keeps its start (moves never carry a
+ // duration change), so nothing timing-related changed — the batch only
+ // rewrites data-track-index, which the renderer never reads (documented
+ // in core runtime/timeline.ts; track is a studio lane concept). The live
+ // DOM patch above + the gesture owner's optimistic store update fully
+ // cover the UI, so after the persist there is nothing to GSAP-shift and
+ // nothing for the preview to recompute: skip the fallback below entirely.
+ // Running it anyway is what made the mirrored z-order lane move blink —
+ // a zero-delta batch yields no scriptText, and finishGroupTimingGsapFallback
+ // used to full-reload the iframe when there was no script to soft-swap
+ // (it now rebinds the runtime timing in place, but a track-only batch
+ // needs NO preview sync at all, so the skip stays).
+ const trackOnly = changes.every((change) => change.start === change.element.start);
+
const maxEnd = Math.max(...changes.map((change) => change.start + change.element.duration));
// Snapshot the duration BEFORE the optimistic updates below so a failed
// persist can roll the readout + live root back (see captureDurationRollback).
const rollbackDuration = captureDurationRollback(previewIframeRef.current);
// needsExtension gates the SDK path (setTiming can't grow the root duration),
// so read the store BEFORE the readout sync below optimistically updates it.
+ // Track-only batches leave every clip end unchanged, so both this and the
+ // readout sync below are provable no-ops there — kept unconditional so the
+ // duration machinery stays on one code path.
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);
+ const coalesceMs = options?.coalesceMs;
return enqueueGroupOperation("Move timeline clips", async (projectId) => {
await options?.beforeTiming;
const handledBySdk = await trySdkBatchPersist({
@@ -243,6 +266,7 @@ export function useTimelineGroupEditing({
needsExtension,
label: "Move timeline clips",
coalesceKey,
+ coalesceMs,
});
if (handledBySdk) return;
@@ -261,7 +285,12 @@ export function useTimelineGroupEditing({
),
})),
coalesceKey,
+ coalesceMs,
);
+ // Track-only: no timing delta → no GSAP positions to shift and no
+ // reload (see the trackOnly doc above). Mixed batches (any start
+ // change) keep the full fallback below.
+ if (trackOnly) return;
await finishGroupTimingGsapFallback({
projectId,
iframe: previewIframeRef.current,
@@ -313,7 +342,7 @@ export function useTimelineGroupEditing({
: "data-media-start";
liveAttrs.push([liveAttr, formatTimelineAttributeNumber(change.playbackStart)]);
}
- patchIframeDomTiming(previewIframeRef.current, change.element, liveAttrs);
+ patchIframeDomTiming(previewIframeRef.current, change.element, liveAttrs, activeCompPath);
}
const maxEnd = Math.max(...changes.map((change) => change.start + change.duration));
@@ -327,6 +356,7 @@ export function useTimelineGroupEditing({
// the just-patched live DOM. See syncPreviewContentDuration.
syncPreviewContentDuration(previewIframeRef.current);
const coalesceKey = options?.coalesceKey ?? resizeCoalesceKey(changes);
+ const coalesceMs = options?.coalesceMs;
return enqueueGroupOperation("Resize timeline clips", async (projectId) => {
await options?.beforeTiming;
const handledBySdk = await trySdkBatchPersist({
@@ -339,6 +369,7 @@ export function useTimelineGroupEditing({
needsExtension,
label: "Resize timeline clips",
coalesceKey,
+ coalesceMs,
});
if (handledBySdk) return;
@@ -355,6 +386,7 @@ export function useTimelineGroupEditing({
}),
})),
coalesceKey,
+ coalesceMs,
);
await finishGroupTimingGsapFallback({
projectId,
diff --git a/packages/studio/src/player/components/Timeline.test.ts b/packages/studio/src/player/components/Timeline.test.ts
index 8926060c74..e3db29f4a3 100644
--- a/packages/studio/src/player/components/Timeline.test.ts
+++ b/packages/studio/src/player/components/Timeline.test.ts
@@ -25,6 +25,7 @@ import {
PLAYHEAD_HEAD_W,
RULER_H,
TRACK_H,
+ TRACKS_LEFT_PAD,
getTimelineDisplayContentWidth,
getTimelineFitPps,
} from "./timelineLayout";
@@ -152,7 +153,8 @@ describe("Timeline provider boundary", () => {
});
const row = button.parentElement?.parentElement;
- const trackContent = row?.children.item(1);
+ // Row children: [sticky gutter, TRACKS_LEFT_PAD spacer, time-mapped content].
+ const trackContent = row?.children.item(2);
expect(onToggleTrackHidden).toHaveBeenCalledWith(0, false);
expect(trackContent).toBeInstanceOf(HTMLElement);
if (!(trackContent instanceof HTMLElement)) {
@@ -454,27 +456,27 @@ describe("shouldAutoScrollTimeline", () => {
});
describe("getTimelineFitPps (min 60s extent + fit headroom)", () => {
- const viewport = 632; // usable width = 632 - GUTTER - 2 = 598
+ const viewport = 632; // usable width = 632 - GUTTER - TRACKS_LEFT_PAD - 2
it("computes fit pps against the 60s floor for short compositions", () => {
// A 10s comp maps 60s onto the viewport → the comp takes ~1/6 of the width.
// (10 * 1.2 = 12s of headroom-padded content is still under the 60s floor.)
const pps = getTimelineFitPps(viewport, 10);
- expect(pps).toBeCloseTo((viewport - GUTTER - 2) / MIN_TIMELINE_EXTENT_S);
- expect(10 * pps).toBeCloseTo((viewport - GUTTER - 2) / 6);
+ expect(pps).toBeCloseTo((viewport - GUTTER - TRACKS_LEFT_PAD - 2) / MIN_TIMELINE_EXTENT_S);
+ expect(10 * pps).toBeCloseTo((viewport - GUTTER - TRACKS_LEFT_PAD - 2) / 6);
});
it("fits duration * FIT_ZOOM_HEADROOM (not the bare duration) for long compositions", () => {
expect(getTimelineFitPps(viewport, 60)).toBeCloseTo(
- (viewport - GUTTER - 2) / (60 * FIT_ZOOM_HEADROOM),
+ (viewport - GUTTER - TRACKS_LEFT_PAD - 2) / (60 * FIT_ZOOM_HEADROOM),
);
expect(getTimelineFitPps(viewport, 120)).toBeCloseTo(
- (viewport - GUTTER - 2) / (120 * FIT_ZOOM_HEADROOM),
+ (viewport - GUTTER - TRACKS_LEFT_PAD - 2) / (120 * FIT_ZOOM_HEADROOM),
);
});
it("leaves CapCut-style trailing headroom: the comp ends at 1/1.2 of the usable width", () => {
- const usable = viewport - GUTTER - 2;
+ const usable = viewport - GUTTER - TRACKS_LEFT_PAD - 2;
const pps = getTimelineFitPps(viewport, 120);
// Composition content occupies usable/1.2 px; the remaining ~17% is empty
// droppable ruler/lane surface past the end.
@@ -484,16 +486,16 @@ describe("getTimelineFitPps (min 60s extent + fit headroom)", () => {
it("falls back to 100 pps before the viewport is measured", () => {
expect(getTimelineFitPps(0, 10)).toBe(100);
- expect(getTimelineFitPps(GUTTER, 10)).toBe(100);
+ expect(getTimelineFitPps(GUTTER + TRACKS_LEFT_PAD, 10)).toBe(100);
expect(getTimelineFitPps(Number.NaN, 10)).toBe(100);
});
it("uses the floor for zero/invalid durations", () => {
expect(getTimelineFitPps(viewport, 0)).toBeCloseTo(
- (viewport - GUTTER - 2) / MIN_TIMELINE_EXTENT_S,
+ (viewport - GUTTER - TRACKS_LEFT_PAD - 2) / MIN_TIMELINE_EXTENT_S,
);
expect(getTimelineFitPps(viewport, Number.NaN)).toBeCloseTo(
- (viewport - GUTTER - 2) / MIN_TIMELINE_EXTENT_S,
+ (viewport - GUTTER - TRACKS_LEFT_PAD - 2) / MIN_TIMELINE_EXTENT_S,
);
});
});
@@ -509,7 +511,7 @@ describe("getTimelineDisplayContentWidth", () => {
it("still fills the viewport when that is larger than the 60s floor", () => {
expect(
getTimelineDisplayContentWidth({ trackContentWidth: 200, viewportWidth: 2000, pps: 5 }),
- ).toBe(2000 - GUTTER - 2);
+ ).toBe(2000 - GUTTER - TRACKS_LEFT_PAD - 2);
});
it("tracks a drag ghost past every other bound (drag-to-extend)", () => {
@@ -599,20 +601,28 @@ describe("getTimelineScrollLeftForZoomAnchor", () => {
});
describe("getTimelinePlayheadLeft", () => {
- it("offsets the wrapper by half the head width so the line CENTER = GUTTER + t*pps", () => {
+ it("offsets the wrapper by half the head width so the line CENTER = GUTTER + TRACKS_LEFT_PAD + t*pps", () => {
// Wrapper left + PLAYHEAD_HEAD_W/2 (where the 1px line is centered) must
- // equal GUTTER + t*pps at any zoom.
- expect(getTimelinePlayheadLeft(4, 20) + PLAYHEAD_HEAD_W / 2).toBe(GUTTER + 4 * 20);
- expect(getTimelinePlayheadLeft(10, 7.5) + PLAYHEAD_HEAD_W / 2).toBe(GUTTER + 75);
+ // equal GUTTER + TRACKS_LEFT_PAD + t*pps at any zoom.
+ expect(getTimelinePlayheadLeft(4, 20) + PLAYHEAD_HEAD_W / 2).toBe(
+ GUTTER + TRACKS_LEFT_PAD + 4 * 20,
+ );
+ expect(getTimelinePlayheadLeft(10, 7.5) + PLAYHEAD_HEAD_W / 2).toBe(
+ GUTTER + TRACKS_LEFT_PAD + 75,
+ );
});
- it("centers the line exactly on the gutter (the 00:00 tick) at t = 0", () => {
- expect(getTimelinePlayheadLeft(0, 20) + PLAYHEAD_HEAD_W / 2).toBe(GUTTER);
+ it("centers the line exactly on the left pad's end (the 00:00 tick) at t = 0", () => {
+ expect(getTimelinePlayheadLeft(0, 20) + PLAYHEAD_HEAD_W / 2).toBe(GUTTER + TRACKS_LEFT_PAD);
});
it("guards invalid input", () => {
- expect(getTimelinePlayheadLeft(Number.NaN, 20)).toBe(GUTTER - PLAYHEAD_HEAD_W / 2);
- expect(getTimelinePlayheadLeft(4, Number.NaN)).toBe(GUTTER - PLAYHEAD_HEAD_W / 2);
+ expect(getTimelinePlayheadLeft(Number.NaN, 20)).toBe(
+ GUTTER + TRACKS_LEFT_PAD - PLAYHEAD_HEAD_W / 2,
+ );
+ expect(getTimelinePlayheadLeft(4, Number.NaN)).toBe(
+ GUTTER + TRACKS_LEFT_PAD - PLAYHEAD_HEAD_W / 2,
+ );
});
});
@@ -681,7 +691,7 @@ describe("resolveTimelineAssetDrop", () => {
trackHeight: 72,
trackOrder: [0, 3, 7],
},
- 432,
+ 480, // rectLeft(100) + GUTTER + TRACKS_LEFT_PAD + 3s*100pps
// clientY updated for TRACKS_TOP_PAD=72: rectTop(200) + RULER_H(24) +
// TRACKS_TOP_PAD(72) + TRACK_H(48) + TRACK_H/2(24) = 368 → row 1 → track 3.
368,
@@ -702,7 +712,7 @@ describe("resolveTimelineAssetDrop", () => {
trackHeight: 72,
trackOrder: [0, 3, 7],
},
- 250,
+ 250 + TRACKS_LEFT_PAD,
600,
),
).toEqual({ start: 1.18, track: 8 });
diff --git a/packages/studio/src/player/components/Timeline.tsx b/packages/studio/src/player/components/Timeline.tsx
index 8bd838e3ce..2e215381f6 100644
--- a/packages/studio/src/player/components/Timeline.tsx
+++ b/packages/studio/src/player/components/Timeline.tsx
@@ -9,7 +9,7 @@ import { defaultTimelineTheme } from "./timelineTheme";
import { useTimelineRangeSelection } from "./useTimelineRangeSelection";
import { useTimelinePlayhead } from "./useTimelinePlayhead";
import { useTimelineActiveClips } from "./useTimelineActiveClips";
-import { type TrackVisualStyle, getTrackStyle } from "./timelineIcons";
+import { getTrackStyle } from "./timelineIcons";
import { useTimelineZoom } from "./useTimelineZoom";
import { useTimelineAssetDrop } from "./timelineDragDrop";
import { TimelineEmptyState } from "./TimelineEmptyState";
@@ -20,15 +20,14 @@ import { TimelineOverlays } from "./TimelineOverlays";
import { useTimelineEditPinning } from "./useTimelineEditPinning";
import { useTimelineStackingSync } from "./useTimelineStackingSync";
import { useTimelineGeometry } from "./useTimelineGeometry";
-import {
- GUTTER,
- generateTicks,
- getTimelineCanvasHeight,
- shouldShowTimelineShortcutHint,
-} from "./timelineLayout";
+import { useTimelineTrackDerivations } from "./useTimelineTrackDerivations";
+import { GUTTER, TRACKS_LEFT_PAD, generateTicks, getTimelineCanvasHeight } from "./timelineLayout";
+import { useTimelineScrollViewport } from "./useTimelineScrollViewport";
import { STUDIO_PREVIEW_FPS } from "../lib/time";
import { useResolvedTimelineEditCallbacks } from "./useResolvedTimelineEditCallbacks";
import type { TimelineProps } from "./TimelineTypes";
+import { useTrackGapMenu } from "./useTrackGapMenu";
+import { useTimelineGapHighlights } from "./useTimelineGapHighlights";
// Re-export pure utilities so existing imports from "./Timeline" still resolve.
export {
@@ -114,106 +113,41 @@ export const Timeline = memo(function Timeline({
const [razorGuideX, setRazorGuideX] = useState<number | null>(null);
useMountEffect(() => {
- const down = (e: KeyboardEvent) => e.key === "Shift" && setShiftHeld(true);
- const up = (e: KeyboardEvent) => e.key === "Shift" && setShiftHeld(false);
+ const key = (e: KeyboardEvent) => e.key === "Shift" && setShiftHeld(e.type === "keydown");
const blur = () => setShiftHeld(false);
- window.addEventListener("keydown", down);
- window.addEventListener("keyup", up);
+ window.addEventListener("keydown", key);
+ window.addEventListener("keyup", key);
window.addEventListener("blur", blur);
return () => {
- window.removeEventListener("keydown", down);
- window.removeEventListener("keyup", up);
+ window.removeEventListener("keydown", key);
+ window.removeEventListener("keyup", key);
window.removeEventListener("blur", blur);
};
});
const [showPopover, setShowPopover] = useState(false);
- const [showShortcutHint, setShowShortcutHint] = useState(true);
const [kfContextMenu, setKfContextMenu] = useState<KeyframeDiamondContextMenuState | null>(null);
const [clipContextMenu, setClipContextMenu] = useState<{
x: number;
y: number;
element: TimelineElement;
} | null>(null);
- const [viewportWidth, setViewportWidth] = useState(0);
- const roRef = useRef<ResizeObserver | null>(null);
- const shortcutHintRafRef = useRef(0);
-
- const syncShortcutHintVisibility = useCallback(() => {
- const scroll = scrollRef.current;
- setShowShortcutHint(
- scroll ? shouldShowTimelineShortcutHint(scroll.scrollHeight, scroll.clientHeight) : true,
- );
- }, []);
-
- const scheduleShortcutHintVisibilitySync = useCallback(() => {
- if (shortcutHintRafRef.current) cancelAnimationFrame(shortcutHintRafRef.current);
- shortcutHintRafRef.current = requestAnimationFrame(() => {
- shortcutHintRafRef.current = 0;
- syncShortcutHintVisibility();
- });
- }, [syncShortcutHintVisibility]);
const setContainerRef = useCallback((el: HTMLDivElement | null) => {
containerRef.current = el;
}, []);
- // Last horizontal scroll offset, RESTORED across the post-edit iframe reload (which clamps into
- // a scroll jump); with the pinned zoom this keeps the user parked at the same spot after edits.
+ // Last horizontal scroll offset, restored across the post-edit iframe reload (pinned zoom).
const lastScrollLeftRef = useRef(0);
- const setScrollRef = useCallback(
- (el: HTMLDivElement | null) => {
- if (roRef.current) {
- roRef.current.disconnect();
- roRef.current = null;
- }
- scrollRef.current = el;
- if (!el) return;
-
- const syncScrollViewport = () => {
- setViewportWidth(el.clientWidth);
- scheduleShortcutHintVisibilitySync();
- };
-
- syncScrollViewport();
- roRef.current = new ResizeObserver(syncScrollViewport);
- roRef.current.observe(el);
- },
- [scheduleShortcutHintVisibilitySync],
- );
-
- useMountEffect(() => () => {
- roRef.current?.disconnect();
- if (shortcutHintRafRef.current) cancelAnimationFrame(shortcutHintRafRef.current);
- });
const effectiveDuration = useMemo(() => {
const safeDur = Number.isFinite(duration) ? duration : 0;
if (rawElements.length === 0) return safeDur;
- const maxEnd = Math.max(...rawElements.map((el) => el.start + el.duration));
- const result = Math.max(safeDur, maxEnd);
+ const result = Math.max(safeDur, ...rawElements.map((el) => el.start + el.duration));
return Number.isFinite(result) ? result : safeDur;
}, [rawElements, duration]);
- const tracks = useMemo(() => {
- const map = new Map<number, typeof expandedElements>();
- for (const el of expandedElements) {
- const list = map.get(el.track) ?? [];
- list.push(el);
- map.set(el.track, list);
- }
- return Array.from(map.entries()).sort(([a], [b]) => a - b);
- }, [expandedElements]);
-
- const trackStyles = useMemo(() => {
- const map = new Map<number, TrackVisualStyle>();
- for (const [trackNum, els] of tracks) {
- map.set(trackNum, getTrackStyle(els[0]?.tag ?? ""));
- }
- return map;
- }, [tracks]);
-
- const trackOrder = useMemo(() => tracks.map(([trackNum]) => trackNum), [tracks]);
+ const { tracks, trackStyles, trackOrder } = useTimelineTrackDerivations(expandedElements);
const trackOrderRef = useRef(trackOrder);
trackOrderRef.current = trackOrder;
const expandedElementsRef = useRef(expandedElements);
@@ -222,8 +156,7 @@ export const Timeline = memo(function Timeline({
const ppsRef = useRef(100);
const durationRef = useRef(effectiveDuration);
durationRef.current = effectiveDuration;
- // Declared here (used before the fitPps derivation below) so the edit-pin
- // wrappers can close over it; `fitPpsRef.current` is refreshed each render.
+ // Declared before the fitPps derivation so the edit-pin wrappers can close over it.
const fitPpsRef = useRef(100);
const {
@@ -252,6 +185,22 @@ export const Timeline = memo(function Timeline({
expandedElementsRef,
});
+ const {
+ gapMenuModel,
+ gapHighlight,
+ setHoveredGapAction,
+ openGapMenu,
+ dismissGapMenu,
+ closeTrackGap,
+ closeAllTrackGaps,
+ } = useTrackGapMenu({
+ tracks,
+ expandedElementsRef,
+ trackOrderRef,
+ onMoveElement: pinnedOnMoveElement,
+ onMoveElements: pinnedOnMoveElements,
+ });
+
const {
draggedClip,
setDraggedClip,
@@ -293,6 +242,11 @@ export const Timeline = memo(function Timeline({
}, [draggedClip, trackOrder]);
const totalH = getTimelineCanvasHeight(displayTrackOrder.length);
+ const { viewportWidth, showShortcutHint, setScrollRef } = useTimelineScrollViewport(scrollRef, [
+ timelineReady,
+ expandedElements.length,
+ totalH,
+ ]);
const keyframeCache = usePlayerStore((s) => s.keyframeCache);
const selectedKeyframes = usePlayerStore((s) => s.selectedKeyframes);
const toggleSelectedKeyframe = usePlayerStore((s) => s.toggleSelectedKeyframe);
@@ -328,6 +282,16 @@ export const Timeline = memo(function Timeline({
lastScrollLeftRef,
});
+ const laneGapStrips = useTimelineGapHighlights({
+ gapHighlight,
+ tracks,
+ selectedElementId,
+ selectedElementIds,
+ expandedElements,
+ dragActive: draggedClip?.started === true || resizingClip != null,
+ displayDuration,
+ });
+
const { seekFromX, autoScrollDuringDrag, dragScrollRaf } = useTimelinePlayhead({
playheadRef,
scrollRef,
@@ -379,8 +343,7 @@ export const Timeline = memo(function Timeline({
trackOrderRef,
onSelectElement,
});
- // Wire setRangeSelection into the stable ref consumed by useTimelineClipDrag
- setRangeSelectionRef.current = setRangeSelection;
+ setRangeSelectionRef.current = setRangeSelection; // stable ref consumed by useTimelineClipDrag
const prevSelectedRef = useRef(selectedElementRef.current);
// eslint-disable-next-line no-restricted-syntax, react-hooks/exhaustive-deps
@@ -402,10 +365,6 @@ export const Timeline = memo(function Timeline({
);
const majorTickInterval = major.length >= 2 ? major[1] - major[0] : effectiveDuration;
- useEffect(() => {
- syncShortcutHintVisibility();
- }, [syncShortcutHintVisibility, timelineReady, expandedElements.length, totalH]);
-
const getPreviewElement = useCallback(
(element: TimelineElement): TimelineElement => {
if (
@@ -459,8 +418,7 @@ export const Timeline = memo(function Timeline({
tabIndex={-1}
className={`${zoomMode === "fit" ? "overflow-x-hidden" : "overflow-x-auto"} overflow-y-auto h-full outline-none`}
onScroll={(e) => {
- // Remember the live offset so it can be restored across a post-edit reload.
- lastScrollLeftRef.current = e.currentTarget.scrollLeft;
+ lastScrollLeftRef.current = e.currentTarget.scrollLeft; // restored across post-edit reload
}}
onDragOver={handleAssetDragOver}
onDragLeave={() => clearDropPreview()}
@@ -468,7 +426,8 @@ export const Timeline = memo(function Timeline({
onPointerDown={(e) => {
if (activeTool === "razor" && e.shiftKey && e.button === 0 && scrollRef.current) {
const rect = scrollRef.current.getBoundingClientRect();
- const x = e.clientX - rect.left + scrollRef.current.scrollLeft - GUTTER;
+ const x =
+ e.clientX - rect.left + scrollRef.current.scrollLeft - GUTTER - TRACKS_LEFT_PAD;
const splitTime = Math.max(0, x / pps);
onRazorSplitAll?.(splitTime);
return;
@@ -489,6 +448,7 @@ export const Timeline = memo(function Timeline({
majorTickInterval={majorTickInterval}
rangeSelection={rangeSelection}
marqueeRect={marqueeRect}
+ laneGapStrips={laneGapStrips}
theme={theme}
displayTrackOrder={displayTrackOrder}
trackOrder={trackOrder}
@@ -560,8 +520,14 @@ export const Timeline = memo(function Timeline({
e.preventDefault();
setSelectedElementId(el.key ?? el.id);
onSelectElement?.(el);
+ dismissGapMenu();
setClipContextMenu({ x: e.clientX, y: e.clientY, element: el });
}}
+ onContextMenuLane={(e, track, time) => {
+ if (draggedClip?.started || resizingClip) return;
+ setClipContextMenu(null);
+ openGapMenu({ x: e.clientX, y: e.clientY, track, time });
+ }}
/>
{activeTool === "razor" && razorGuideX !== null && (
<div
@@ -594,6 +560,11 @@ export const Timeline = memo(function Timeline({
onSplitElement={onSplitElement}
pinZoomBeforeEdit={pinZoomBeforeEdit}
onDeleteElement={_onDeleteElement}
+ gapContextMenu={gapMenuModel}
+ onDismissGapContextMenu={dismissGapMenu}
+ onCloseTrackGap={closeTrackGap}
+ onCloseAllTrackGaps={closeAllTrackGaps}
+ onHoverGapAction={setHoveredGapAction}
/>
</div>
);
diff --git a/packages/studio/src/player/components/TimelineCanvas.tsx b/packages/studio/src/player/components/TimelineCanvas.tsx
index f706088da9..462acc2885 100644
--- a/packages/studio/src/player/components/TimelineCanvas.tsx
+++ b/packages/studio/src/player/components/TimelineCanvas.tsx
@@ -10,6 +10,7 @@ import {
CLIP_Y,
TRACKS_TOP_PAD,
TRACKS_BOTTOM_PAD,
+ TRACKS_LEFT_PAD,
PLAYHEAD_HEAD_W,
getTimelinePlayheadLeft,
getTimelineRowTop,
@@ -23,6 +24,7 @@ import { TimelineClip } from "./TimelineClip";
import { TimelineLanes, type TimelineLaneBaseProps } from "./TimelineLanes";
import { renderClipChildren } from "./timelineClipChildren";
import { useTimelineRevealClip } from "./useTimelineRevealClip";
+import type { TimelineLaneGapStrips } from "./useTimelineGapHighlights";
interface TimelineCanvasProps extends TimelineLaneBaseProps {
major: number[];
@@ -37,6 +39,8 @@ interface TimelineCanvasProps extends TimelineLaneBaseProps {
/** Playhead is being actively scrubbed — fills the grab-handle head. */
isScrubbing: boolean;
playheadRef: React.RefObject<HTMLDivElement | null>;
+ /** Gap strips: loud on gap-menu-row hover, quiet on the selected clip's lane. */
+ laneGapStrips: TimelineLaneGapStrips[];
}
export const TimelineCanvas = memo(function TimelineCanvas(props: TimelineCanvasProps) {
@@ -97,7 +101,7 @@ export const TimelineCanvas = memo(function TimelineCanvas(props: TimelineCanvas
return (
<div
className="relative"
- style={{ height: props.totalH, width: GUTTER + props.trackContentWidth }}
+ style={{ height: props.totalH, width: GUTTER + TRACKS_LEFT_PAD + props.trackContentWidth }}
>
<TimelineRuler
major={props.major}
@@ -131,6 +135,31 @@ export const TimelineCanvas = memo(function TimelineCanvas(props: TimelineCanvas
new bottom track comfortably (see TRACKS_BOTTOM_PAD / getTimelineCanvasHeight). */}
<div aria-hidden="true" style={{ height: TRACKS_BOTTOM_PAD }} />
+ {/* Gap strips — loud dashed fill for the gap(s) a hovered "Close gap(s)"
+ menu row would collapse; a quiet tint for every gap on the selected
+ clip's lane. Geometry mirrors the drop placeholder (row top + clip
+ inset) so strips sit exactly where a clip body would. */}
+ {props.laneGapStrips.map((strip) => {
+ const rowIndex = displayTrackOrder.indexOf(strip.track);
+ if (rowIndex < 0) return null;
+ const loud = strip.kind === "hover";
+ return strip.intervals.map((gap) => (
+ <div
+ key={`gap-${strip.kind}-${strip.track}-${gap.start}`}
+ className="pointer-events-none absolute"
+ style={{
+ top: getTimelineRowTop(rowIndex) + CLIP_Y,
+ left: GUTTER + TRACKS_LEFT_PAD + gap.start * props.pps,
+ width: Math.max((gap.end - gap.start) * props.pps, 2),
+ height: TRACK_H - CLIP_Y * 2,
+ background: loud ? "rgba(60,230,172,0.18)" : "rgba(60,230,172,0.055)",
+ borderRadius: 4,
+ zIndex: 25,
+ }}
+ />
+ ));
+ })}
+
{/* Drop placeholder — a clip-sized slot at the exact landing spot (target
lane + snapped start), parallel to the ghost. Hidden in insert mode. */}
{draggedClip?.started && draggedClip.insertRow == null && draggedRowIndex >= 0 && (
@@ -138,7 +167,7 @@ export const TimelineCanvas = memo(function TimelineCanvas(props: TimelineCanvas
className="absolute pointer-events-none"
style={{
top: getTimelineRowTop(draggedRowIndex) + CLIP_Y,
- left: GUTTER + draggedClip.previewStart * props.pps,
+ left: GUTTER + TRACKS_LEFT_PAD + draggedClip.previewStart * props.pps,
width: Math.max(draggedClip.element.duration * props.pps, 4),
height: TRACK_H - CLIP_Y * 2,
border: "1px solid rgba(60,230,172,0.55)",
@@ -156,7 +185,7 @@ export const TimelineCanvas = memo(function TimelineCanvas(props: TimelineCanvas
className="absolute pointer-events-none"
style={{
top: getTimelineRowTop(draggedClip.insertRow) - 0.5,
- left: GUTTER,
+ left: GUTTER + TRACKS_LEFT_PAD,
width: props.trackContentWidth,
height: 1,
background: "#3CE6AC",
@@ -171,7 +200,7 @@ export const TimelineCanvas = memo(function TimelineCanvas(props: TimelineCanvas
<div
className="absolute pointer-events-none"
style={{
- left: GUTTER + draggedClip.snapTime * props.pps,
+ left: GUTTER + TRACKS_LEFT_PAD + draggedClip.snapTime * props.pps,
top: RULER_H,
bottom: 0,
width: 1,
@@ -251,7 +280,9 @@ export const TimelineCanvas = memo(function TimelineCanvas(props: TimelineCanvas
className="absolute pointer-events-none"
style={{
left:
- GUTTER + Math.min(props.rangeSelection.start, props.rangeSelection.end) * props.pps,
+ GUTTER +
+ TRACKS_LEFT_PAD +
+ Math.min(props.rangeSelection.start, props.rangeSelection.end) * props.pps,
width: Math.abs(props.rangeSelection.end - props.rangeSelection.start) * props.pps,
top: RULER_H,
bottom: 0,
diff --git a/packages/studio/src/player/components/TimelineLanes.tsx b/packages/studio/src/player/components/TimelineLanes.tsx
index 9a2078a48b..75069c1a0b 100644
--- a/packages/studio/src/player/components/TimelineLanes.tsx
+++ b/packages/studio/src/player/components/TimelineLanes.tsx
@@ -6,7 +6,7 @@ import { TimelineClipDiamonds } from "./TimelineClipDiamonds";
import type { MusicBeatAnalysis } from "@hyperframes/core/beats";
import { getTimelineEditCapabilities, resolveBlockedTimelineEditIntent } from "./timelineEditing";
import type { TimelineTheme } from "./timelineTheme";
-import { GUTTER, TRACK_H, CLIP_Y, CLIP_HANDLE_W } from "./timelineLayout";
+import { GUTTER, TRACK_H, TRACKS_LEFT_PAD, CLIP_Y, CLIP_HANDLE_W } from "./timelineLayout";
import {
usePlayerStore,
type TimelineElement,
@@ -80,6 +80,12 @@ export interface TimelineLaneBaseProps {
toClipPercentage: number,
) => void;
onContextMenuClip?: (e: React.MouseEvent, element: TimelineElement) => void;
+ /**
+ * Right-click on EMPTY lane space (not on a clip — those preventDefault
+ * before this fires — not the gutter/ruler, not below the lanes). `time` is
+ * the timeline time (seconds) under the pointer on that lane.
+ */
+ onContextMenuLane?: (e: React.MouseEvent, track: number, time: number) => void;
beatAnalysis?: MusicBeatAnalysis | null;
}
@@ -133,6 +139,7 @@ export function TimelineLanes({
onContextMenuKeyframe,
onMoveKeyframe,
onContextMenuClip,
+ onContextMenuLane,
beatAnalysis,
onToggleTrackHidden,
onResizeElement,
@@ -167,21 +174,14 @@ export function TimelineLanes({
const isTrackHidden = els.length > 0 && els.every((element) => element.hidden === true);
const isAudioTrack = els.length > 0 && els.some(isAudioTimelineElement);
return (
- <div
- key={trackNum}
- className="relative flex"
- style={{
- height: TRACK_H,
- background: rowBackground,
- borderBottom: `1px solid ${theme.rowBorder}`,
- }}
- >
+ <div key={trackNum} className="relative flex" style={{ height: TRACK_H }}>
<div
className="sticky left-0 z-[12] flex-shrink-0 flex flex-col items-center justify-center gap-0.5"
style={{
width: GUTTER,
background: theme.gutterBackground,
borderRight: `1px solid ${theme.gutterBorder}`,
+ borderBottom: `1px solid ${theme.rowBorder}`,
}}
>
{isAudioTrack && (
@@ -211,13 +211,35 @@ export function TimelineLanes({
)}
</button>
</div>
+ {/* Left breathing pad — empty lane surface before t=0, scrolling
+ with the content (the horizontal TRACKS_TOP_PAD). Sits OUTSIDE
+ the time-mapped content div so clip/beat/menu math stays
+ content-relative (clip left = t·pps). */}
+ <div
+ aria-hidden="true"
+ className="flex-shrink-0"
+ style={{ width: TRACKS_LEFT_PAD }}
+ />
<div
style={{
width: trackContentWidth,
+ background: rowBackground,
+ borderBottom: `1px solid ${theme.rowBorder}`,
opacity: isTrackHidden ? 0.35 : 1,
transition: "opacity 120ms ease",
}}
className="relative"
+ onContextMenu={(e: React.MouseEvent) => {
+ // Clip / keyframe-diamond context menus preventDefault at the
+ // target before this bubble handler runs — respect them so a
+ // right-click on a clip never also opens the gap menu.
+ if (e.defaultPrevented || !onContextMenuLane) return;
+ const rect = e.currentTarget.getBoundingClientRect();
+ const time = (e.clientX - rect.left) / pps;
+ if (time < 0) return;
+ e.preventDefault();
+ onContextMenuLane(e, trackNum, time);
+ }}
>
{/* Faint beat lines in every track's background (behind the clips);
the active move-snap target is highlighted. */}
diff --git a/packages/studio/src/player/components/TimelineOverlays.tsx b/packages/studio/src/player/components/TimelineOverlays.tsx
index 0f0efcb73d..bd0896e0be 100644
--- a/packages/studio/src/player/components/TimelineOverlays.tsx
+++ b/packages/studio/src/player/components/TimelineOverlays.tsx
@@ -8,6 +8,7 @@ import {
type KeyframeDiamondContextMenuState,
} from "./KeyframeDiamondContextMenu";
import { ClipContextMenu } from "./ClipContextMenu";
+import { TrackGapContextMenu } from "./TrackGapContextMenu";
import { TimelineShortcutHint } from "./TimelineShortcutHint";
interface ClipContextMenuState {
@@ -16,6 +17,16 @@ interface ClipContextMenuState {
element: TimelineElement;
}
+/** Resolved model for the empty-lane-space (track gap) context menu. */
+interface TrackGapContextMenuState {
+ x: number;
+ y: number;
+ gapWidth: number | null;
+ canCloseGap: boolean;
+ canCloseAllGaps: boolean;
+ hasAnyGaps: boolean;
+}
+
interface TimelineOverlaysProps {
theme: TimelineTheme;
showShortcutHint: boolean;
@@ -36,6 +47,11 @@ interface TimelineOverlaysProps {
onSplitElement: TimelineEditCallbacks["onSplitElement"];
pinZoomBeforeEdit: () => void;
onDeleteElement?: (element: TimelineElement) => Promise<void> | void;
+ gapContextMenu: TrackGapContextMenuState | null;
+ onDismissGapContextMenu: () => void;
+ onCloseTrackGap: () => void;
+ onCloseAllTrackGaps: () => void;
+ onHoverGapAction: (action: "close-gap" | "close-all" | null) => void;
}
// The timeline's floating overlays, rendered as siblings above the scroll area:
@@ -61,6 +77,11 @@ export function TimelineOverlays({
onSplitElement,
pinZoomBeforeEdit,
onDeleteElement,
+ gapContextMenu,
+ onDismissGapContextMenu,
+ onCloseTrackGap,
+ onCloseAllTrackGaps,
+ onHoverGapAction,
}: TimelineOverlaysProps) {
return (
<>
@@ -117,6 +138,21 @@ export function TimelineOverlays({
}}
/>
)}
+
+ {gapContextMenu && (
+ <TrackGapContextMenu
+ x={gapContextMenu.x}
+ y={gapContextMenu.y}
+ gapWidth={gapContextMenu.gapWidth}
+ canCloseGap={gapContextMenu.canCloseGap}
+ canCloseAllGaps={gapContextMenu.canCloseAllGaps}
+ hasAnyGaps={gapContextMenu.hasAnyGaps}
+ onClose={onDismissGapContextMenu}
+ onCloseGap={onCloseTrackGap}
+ onCloseAllGaps={onCloseAllTrackGaps}
+ onHoverAction={onHoverGapAction}
+ />
+ )}
</>
);
}
diff --git a/packages/studio/src/player/components/TimelineRuler.tsx b/packages/studio/src/player/components/TimelineRuler.tsx
index d40b61237e..fe8fac5f18 100644
--- a/packages/studio/src/player/components/TimelineRuler.tsx
+++ b/packages/studio/src/player/components/TimelineRuler.tsx
@@ -1,6 +1,6 @@
import { memo } from "react";
import type { TimelineTheme } from "./timelineTheme";
-import { GUTTER, RULER_H, formatTimelineTickLabel } from "./timelineLayout";
+import { GUTTER, RULER_H, TRACKS_LEFT_PAD, formatTimelineTickLabel } from "./timelineLayout";
import { usePlayerStore } from "../store/playerStore";
import { secondsToFrame } from "../lib/time";
import type { MusicBeatAnalysis } from "@hyperframes/core/beats";
@@ -45,7 +45,7 @@ export const TimelineRuler = memo(function TimelineRuler({
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 }}
+ style={{ left: GUTTER + TRACKS_LEFT_PAD, width: trackContentWidth, zIndex: 0 }}
height={totalH}
>
{showBeats &&
@@ -74,17 +74,30 @@ export const TimelineRuler = memo(function TimelineRuler({
rows and drag overlays but below the playhead (z 100). */}
<div
className="sticky top-0 flex"
- style={{ height: RULER_H, width: GUTTER + trackContentWidth, zIndex: 70 }}
+ style={{
+ height: RULER_H,
+ width: GUTTER + TRACKS_LEFT_PAD + trackContentWidth,
+ zIndex: 70,
+ }}
>
<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.
+ // Ruler corner uses the panel surface — same as the ruler strip
+ // itself, and NO right border: the ruler band stays completely
+ // clean until 00:00 (the header-boundary line belongs to the track
+ // rows below, not the ruler).
background: theme.shellBackground,
- borderRight: `1px solid ${theme.gutterBorder}`,
}}
/>
+ {/* Left breathing pad — scrolls with the content, so 00:00 starts a
+ beat right of the gutter (see TRACKS_LEFT_PAD). */}
+ <div
+ aria-hidden="true"
+ className="flex-shrink-0"
+ style={{ width: TRACKS_LEFT_PAD, background: theme.shellBackground }}
+ />
<div
className="relative overflow-hidden"
style={{
diff --git a/packages/studio/src/player/components/TrackGapContextMenu.tsx b/packages/studio/src/player/components/TrackGapContextMenu.tsx
new file mode 100644
index 0000000000..5808890817
--- /dev/null
+++ b/packages/studio/src/player/components/TrackGapContextMenu.tsx
@@ -0,0 +1,116 @@
+import { memo } from "react";
+import { createPortal } from "react-dom";
+import { useContextMenuDismiss } from "../../hooks/useContextMenuDismiss";
+
+interface TrackGapContextMenuProps {
+ x: number;
+ y: number;
+ /** Width (seconds) of the gap under the pointer, or null when no clip exists to the right. */
+ gapWidth: number | null;
+ /** "Close gap" actionable: a gap exists AND every clip that must shift is movable. */
+ canCloseGap: boolean;
+ /** "Close all gaps" actionable: the lane has gaps AND every shifting clip is movable. */
+ canCloseAllGaps: boolean;
+ /** The lane has at least one gap (distinguishes the two disabled reasons). */
+ hasAnyGaps: boolean;
+ onClose: () => void;
+ onCloseGap: () => void;
+ onCloseAllGaps: () => void;
+ /** Hover state for the gap-strip highlight overlay (null = nothing hovered).
+ * Only reported for ACTIONABLE rows — a disabled row closes nothing, so
+ * highlighting from it would promise an action that can't happen. */
+ onHoverAction: (action: "close-gap" | "close-all" | null) => void;
+}
+
+/**
+ * Context menu for right-clicking EMPTY space on a timeline lane
+ * (CapCut/Premiere-style). Offers "Close gap" (collapse the clicked gap by
+ * shifting the following clips on that lane left) and "Close all gaps"
+ * (compact the whole lane contiguous from 0). Both rows are ALWAYS present —
+ * an inapplicable action dims with a tooltip explaining why, rather than
+ * vanishing into a one-item menu. Hovering an actionable row highlights the
+ * gap strip(s) it would close (via onHoverAction → TimelineCanvas overlay).
+ * Styling mirrors ClipContextMenu.
+ */
+export const TrackGapContextMenu = memo(function TrackGapContextMenu({
+ x,
+ y,
+ gapWidth,
+ canCloseGap,
+ canCloseAllGaps,
+ hasAnyGaps,
+ onClose,
+ onCloseGap,
+ onCloseAllGaps,
+ onHoverAction,
+}: TrackGapContextMenuProps) {
+ const menuRef = useContextMenuDismiss(onClose);
+
+ const menuWidth = 200;
+ const menuHeight = 68;
+ const overflowY = y + menuHeight - window.innerHeight;
+ const adjustedX = x + menuWidth > window.innerWidth ? x - menuWidth : x;
+ const adjustedY = overflowY > 0 ? y - overflowY - 8 : y;
+
+ const itemClass = (enabled: boolean) =>
+ `w-full flex items-center justify-between px-3 py-1.5 text-xs text-left ${
+ enabled
+ ? "text-neutral-300 hover:bg-neutral-800 cursor-pointer"
+ : "text-neutral-600 cursor-not-allowed"
+ }`;
+
+ // Disabled reasons: no gap under the pointer beats the lock reason — a
+ // pointer not on a gap has nothing to close regardless of movability.
+ const closeGapTitle = canCloseGap
+ ? undefined
+ : gapWidth == null
+ ? "No gap here"
+ : "A clip on this track can't be moved";
+ const closeAllTitle = canCloseAllGaps
+ ? undefined
+ : hasAnyGaps
+ ? "A clip on this track can't be moved"
+ : "No gaps on this track";
+
+ return createPortal(
+ <div
+ ref={menuRef}
+ className="fixed z-50 bg-neutral-900 border border-neutral-700 rounded-md shadow-lg py-1 min-w-[180px]"
+ style={{ left: adjustedX, top: adjustedY }}
+ onPointerLeave={() => onHoverAction(null)}
+ >
+ <button
+ type="button"
+ className={itemClass(canCloseGap)}
+ disabled={!canCloseGap}
+ title={closeGapTitle}
+ onPointerEnter={() => onHoverAction(canCloseGap ? "close-gap" : null)}
+ onClick={() => {
+ if (!canCloseGap) return;
+ onCloseGap();
+ onClose();
+ }}
+ >
+ <span>Close gap</span>
+ {gapWidth != null && (
+ <span className="text-neutral-500 text-[10px] ml-3">{gapWidth.toFixed(2)}s</span>
+ )}
+ </button>
+ <button
+ type="button"
+ className={itemClass(canCloseAllGaps)}
+ disabled={!canCloseAllGaps}
+ title={closeAllTitle}
+ onPointerEnter={() => onHoverAction(canCloseAllGaps ? "close-all" : null)}
+ onClick={() => {
+ if (!canCloseAllGaps) return;
+ onCloseAllGaps();
+ onClose();
+ }}
+ >
+ <span>Close all gaps</span>
+ </button>
+ </div>,
+ document.body,
+ );
+});
diff --git a/packages/studio/src/player/components/timelineCallbacks.ts b/packages/studio/src/player/components/timelineCallbacks.ts
index 033b3ecb56..26d1e4bd77 100644
--- a/packages/studio/src/player/components/timelineCallbacks.ts
+++ b/packages/studio/src/player/components/timelineCallbacks.ts
@@ -31,11 +31,14 @@ export interface TimelineEditCallbacks {
) => Promise<void> | void;
/** Atomic multi-clip move (single undo) for main-track ripple + track-insert.
* `coalesceKey` (drag-commit gesture id) merges the move history entry with a
- * lane change's follow-up z-reorder entry into one undo step. */
+ * lane change's follow-up z-reorder entry into one undo step; `coalesceMs`
+ * widens that entry's fold window when a server round-trip separates the
+ * gesture's records (per-gesture-unique keys keep the fold gesture-scoped). */
onMoveElements?: (
edits: Array<{ element: TimelineElement; updates: Pick<TimelineElement, "start" | "track"> }>,
coalesceKey?: string,
operation?: TimelineMoveOperation,
+ coalesceMs?: number,
) => Promise<void> | void;
onResizeElement?: (
element: TimelineElement,
diff --git a/packages/studio/src/player/components/timelineClipDragCommit.test.ts b/packages/studio/src/player/components/timelineClipDragCommit.test.ts
index a09c4e25d1..a08fca0d6d 100644
--- a/packages/studio/src/player/components/timelineClipDragCommit.test.ts
+++ b/packages/studio/src/player/components/timelineClipDragCommit.test.ts
@@ -3,6 +3,7 @@ import type { TimelineElement } from "../store/playerStore";
import type { DraggedClipState } from "./useTimelineClipDrag";
import {
commitDraggedClipMove,
+ commitZMirrorLaneMove,
type DragCommitDeps,
type TimelineMoveEdit,
} from "./timelineClipDragCommit";
@@ -12,6 +13,7 @@ import {
pushEditHistoryEntry,
} from "../../utils/editHistory";
import { normalizeToZones } from "./timelineZones";
+import { resolveZMirrorLaneMove } from "./timelineZMirror";
import type { StackingPatch } from "./timelineStackingSync";
function el(
@@ -29,9 +31,7 @@ function el(
/** Flush the microtask chain: the z-sync now fires only after the move persist
* promise resolves (serialized), so tests asserting on it must await. */
async function flushMicrotasks(): Promise<void> {
- await Promise.resolve();
- await Promise.resolve();
- await Promise.resolve();
+ for (let step = 0; step < 8; step += 1) await Promise.resolve();
}
function drag(
@@ -370,6 +370,73 @@ describe("commitDraggedClipMove", () => {
expect(map.b.track).toBe(2); // at/below the insert → +1 shift
});
+ it("a selected audio passenger moves in time during a visual insert without being renumbered", () => {
+ const a = { ...el("a", 0, 0, 5), sourceFile: "scene.html" };
+ const b = { ...el("b", 1, 10, 5), sourceFile: "scene.html" };
+ const t = { ...el("t", 1, 0, 5), sourceFile: "scene.html" };
+ const audio = {
+ ...el("audio", 2, 4, 20, "audio"),
+ sourceFile: "scene.html",
+ authoredTrack: 7,
+ };
+
+ const { onMoveElements } = runClipMove(
+ drag(t, { previewStart: 5, previewTrack: 1, insertRow: 1 }),
+ {
+ elements: [a, b, t, audio],
+ trackOrder: [0, 1, 2],
+ selectedKeys: new Set(["t", "audio"]),
+ },
+ );
+
+ const map = editMap(onMoveElements.mock.calls[0][0]);
+ expect(map.audio).toEqual({ start: 9, track: 7 });
+ });
+
+ it("an audio insert persists zone-local tracks without rewriting visual lanes", () => {
+ const v0 = el("v0", 0, 0, 5);
+ const v1 = el("v1", 1, 0, 5);
+ const a = { ...el("a", 2, 0, 5, "audio"), authoredTrack: 0 };
+ const b = { ...el("b", 3, 10, 5, "audio"), authoredTrack: 1 };
+ const t = { ...el("t", 3, 0, 5, "audio"), authoredTrack: 1 };
+
+ const { onMoveElements } = runClipMove(
+ drag(t, { previewStart: 0, previewTrack: 3, insertRow: 3 }),
+ { elements: [v0, v1, a, b, t], trackOrder: [0, 1, 2, 3] },
+ );
+
+ expect(editMap(onMoveElements.mock.calls[0][0])).toEqual({
+ a: { start: 0, track: 0 },
+ t: { start: 0, track: 1 },
+ b: { start: 10, track: 2 },
+ });
+ });
+
+ it("refuses an audio insert when it would renumber a locked authored row", () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const visual = el("visual", 0, 0, 5);
+ const locked = {
+ ...el("locked", 1, 0, 5, "audio"),
+ authoredTrack: 0,
+ timelineLocked: true,
+ };
+ const target = { ...el("target", 2, 0, 5, "audio"), authoredTrack: 1 };
+
+ try {
+ const { onMoveElements } = runClipMove(
+ drag(target, { previewStart: 0, previewTrack: 2, insertRow: 1 }),
+ { elements: [visual, locked, target], trackOrder: [0, 1, 2] },
+ );
+
+ expect(onMoveElements).not.toHaveBeenCalled();
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("locked clip locked would need renumbering"),
+ );
+ } finally {
+ warnSpy.mockRestore();
+ }
+ });
+
describe("lane ↔ stacking sync", () => {
it("lane change raises the edited clip's z above a time-overlapping lower-lane clip", async () => {
// a & b overlap in time. Elements carry their authored z (as real discovery
@@ -1024,3 +1091,212 @@ describe("commitDraggedClipMove", () => {
});
});
});
+
+describe("commitZMirrorLaneMove", () => {
+ const mirrorDeps = (elements: TimelineElement[], trackOrder: number[]) => {
+ const updateElement = vi.fn();
+ const onMoveElements = vi.fn();
+ return {
+ updateElement,
+ onMoveElements,
+ deps: { elements, trackOrder, updateElement, onMoveElements } as DragCommitDeps,
+ };
+ };
+
+ it("kind:move persists start + display lane with the persistTrack override (same shape as a lane drag)", async () => {
+ // t sits at lane 2 in a sparse file (authored 7); the mirror lands it on
+ // lane 0 whose authored track is 3.
+ const t = { ...el("t", 2, 0, 10), authoredTrack: 7 };
+ const elements = [{ ...el("a", 0, 20, 5), authoredTrack: 3 }, el("b", 1, 0, 10), t];
+ const { updateElement, onMoveElements, deps } = mirrorDeps(elements, [0, 1, 2]);
+ const moved = await commitZMirrorLaneMove(
+ t,
+ { kind: "move", displayTrack: 0, persistTrack: 3 },
+ deps,
+ "z-reorder:bring-forward:t",
+ );
+ expect(moved).toBe(true);
+ // Optimistic store update: DISPLAY lane + the written authoredTrack mirror.
+ expect(updateElement).toHaveBeenCalledWith("t", {
+ start: 0,
+ track: 0,
+ authoredTrack: 3,
+ });
+ // Persist: authored-space track, the z persist's coalesce key, lane-reorder op.
+ expect(onMoveElements).toHaveBeenCalledTimes(1);
+ const [persistEdits, coalesceKey, operation] = onMoveElements.mock.calls[0];
+ expect(editMap(persistEdits)).toEqual({ t: { start: 0, track: 3 } });
+ expect(coalesceKey).toBe("z-reorder:bring-forward:t");
+ expect(operation).toBe("lane-reorder");
+ });
+
+ it("kind:insert reuses the track-insert renumber core (+1 shift below the new lane)", async () => {
+ // a,b,c mutually overlapping on lanes 0/1/2. Mirror-insert c at row 1: c
+ // lands on the new lane, b (at/below) shifts down — identical to the drag
+ // insert test above, proving the shared core (no duplicated renumber logic).
+ const elements = [el("a", 0, 0, 5), el("b", 1, 0, 5), el("c", 2, 0, 5)];
+ const { onMoveElements, deps } = mirrorDeps(elements, [0, 1, 2]);
+ const moved = await commitZMirrorLaneMove(
+ elements[2],
+ { kind: "insert", insertRow: 1 },
+ deps,
+ "z-reorder:bring-forward:c",
+ );
+ expect(moved).toBe(true);
+ expect(onMoveElements).toHaveBeenCalledTimes(1);
+ expect(onMoveElements.mock.calls[0][1]).toBe("z-reorder:bring-forward:c");
+ expect(onMoveElements.mock.calls[0][2]).toBe("track-insert");
+ const map = editMap(onMoveElements.mock.calls[0][0]);
+ expect(map.a.track).toBe(0);
+ expect(map.c.track).toBe(1);
+ expect(map.b.track).toBe(2);
+ });
+
+ it("visual mirror inserts never persist or renumber same-file audio", async () => {
+ // b and t share a visual lane because they do not overlap. Inserting t between
+ // a and b creates one extra visual lane, so whole-timeline normalization moves
+ // audio from display lane 2 to 3. That display-only shift must not be written.
+ const a = { ...el("a", 0, 0, 5), sourceFile: "scene.html" };
+ const b = { ...el("b", 1, 10, 5), sourceFile: "scene.html" };
+ const t = { ...el("t", 1, 0, 5), sourceFile: "scene.html" };
+ const audio = { ...el("audio", 2, 0, 20, "audio"), sourceFile: "scene.html" };
+ const { onMoveElements, deps } = mirrorDeps([a, b, t, audio], [0, 1, 2]);
+
+ const moved = await commitZMirrorLaneMove(
+ t,
+ { kind: "insert", insertRow: 1 },
+ deps,
+ "z-reorder:bring-forward:t",
+ );
+
+ expect(moved).toBe(true);
+ const map = editMap(onMoveElements.mock.calls[0][0]);
+ expect(map.audio).toBeUndefined();
+ expect(map).toEqual({
+ a: { start: 0, track: 0 },
+ b: { start: 10, track: 2 },
+ t: { start: 0, track: 1 },
+ });
+ });
+
+ it("foreign expanded rows never distort the root-file insert topology", async () => {
+ const host = { ...el("host", 0, 0, 5), sourceFile: "index.html" };
+ const child1 = {
+ ...el("child-1", 0.25, 0, 5),
+ sourceFile: "scene.html",
+ expandedParentStart: 0,
+ };
+ const child2 = {
+ ...el("child-2", 0.5, 0, 5),
+ sourceFile: "scene.html",
+ expandedParentStart: 0,
+ };
+ const b = { ...el("b", 1, 0, 5), sourceFile: "index.html" };
+ const t = { ...el("t", 2, 0, 5), sourceFile: "index.html" };
+ const elements = [host, child1, child2, b, t];
+ const { onMoveElements, deps } = mirrorDeps(elements, [0, 0.25, 0.5, 1, 2]);
+
+ const moved = await commitZMirrorLaneMove(
+ t,
+ { kind: "insert", insertRow: 1 },
+ deps,
+ "z-reorder:bring-forward:t",
+ );
+
+ expect(moved).toBe(true);
+ expect(editMap(onMoveElements.mock.calls[0][0])).toEqual({
+ host: { start: 0, track: 0 },
+ t: { start: 0, track: 1 },
+ b: { start: 0, track: 2 },
+ });
+ });
+
+ it("never triggers the lane→z stacking sync (it would fight the just-set z values)", async () => {
+ // Even with BOTH z-sync deps supplied (the drag paths would engage them for
+ // a vertical move like this), the mirror commit must not emit stacking
+ // patches — the z values were just written by the user's menu action.
+ const t = el("t", 2, 0, 10);
+ const elements = [el("a", 0, 20, 5), el("b", 1, 0, 10), t];
+ const { deps } = mirrorDeps(elements, [0, 1, 2]);
+ const onStackingPatches = vi.fn();
+ const moved = await commitZMirrorLaneMove(
+ t,
+ { kind: "move", displayTrack: 0, persistTrack: 0 },
+ { ...deps, readZIndex: () => 0, onStackingPatches },
+ "z-reorder:bring-forward:t",
+ );
+ await flushMicrotasks();
+ expect(moved).toBe(true);
+ expect(onStackingPatches).not.toHaveBeenCalled();
+ });
+
+ it("resolves false and rolls the store back when the persist rejects", async () => {
+ const t = el("t", 1, 0, 10);
+ const elements = [el("a", 0, 20, 5), t];
+ const updateElement = vi.fn();
+ const onMoveElements = vi.fn().mockRejectedValue(new Error("boom"));
+ const moved = await commitZMirrorLaneMove(
+ t,
+ { kind: "move", displayTrack: 0, persistTrack: 0 },
+ { elements, trackOrder: [0, 1], updateElement, onMoveElements },
+ "z-reorder:send-backward:t",
+ );
+ expect(moved).toBe(false);
+ // Optimistic write then rollback to the original lane.
+ expect(updateElement).toHaveBeenLastCalledWith("t", {
+ start: 0,
+ track: 1,
+ authoredTrack: undefined,
+ });
+ });
+
+ it("END-TO-END one-element step: resolver insertRow renumbers the clip strictly between the two neighbors", async () => {
+ // 3 stacked back-to-back clips + a free lane beyond the far one. Send t
+ // (top) backward past b: the resolver must bound at c and produce the
+ // insert row IMMEDIATELY below b, and commitZMirrorLaneMove's renumber must
+ // land t strictly between b and c — never on the farther free lane 3.
+ const t = el("t", 0, 0, 10);
+ const b = el("b", 1, 0, 10);
+ const c = el("c", 2, 0, 10);
+ const far = el("far", 3, 20, 5); // free over t's span, beyond c
+ const elements = [t, b, c, far];
+ const move = resolveZMirrorLaneMove({
+ action: "send-backward",
+ element: t,
+ elements,
+ crossedKey: "b",
+ });
+ expect(move).toEqual({ kind: "insert", insertRow: 2 });
+ const { onMoveElements, deps } = mirrorDeps(elements, [0, 1, 2, 3]);
+ const moved = await commitZMirrorLaneMove(t, move!, deps, "z-reorder:send-backward:t");
+ expect(moved).toBe(true);
+ const map = editMap(onMoveElements.mock.calls[0][0]);
+ // The renumber compacts t's vacated top lane, so the whole set shifts up by
+ // one while t lands on the b/c boundary — strictly between the two.
+ expect(map).toEqual({
+ b: { start: 0, track: 0 },
+ t: { start: 0, track: 1 },
+ c: { start: 0, track: 2 },
+ far: { start: 20, track: 3 },
+ });
+ expect(map.b.track).toBeLessThan(map.t.track);
+ expect(map.t.track).toBeLessThan(map.c.track);
+ });
+
+ it("resolves false for a refused insert (locked clip would need renumbering)", async () => {
+ // b is locked and sits at/below the insert row, so the whole-set renumber
+ // is refused — no persist call.
+ const a = el("a", 0, 0, 5);
+ const b: TimelineElement = { ...el("b", 1, 0, 5), timelineLocked: true };
+ const c = el("c", 2, 0, 5);
+ const { onMoveElements, deps } = mirrorDeps([a, b, c], [0, 1, 2]);
+ const moved = await commitZMirrorLaneMove(
+ c,
+ { kind: "insert", insertRow: 1 },
+ deps,
+ "z-reorder:bring-forward:c",
+ );
+ expect(moved).toBe(false);
+ expect(onMoveElements).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/studio/src/player/components/timelineClipDragCommit.ts b/packages/studio/src/player/components/timelineClipDragCommit.ts
index d84982cb3b..cce89f586b 100644
--- a/packages/studio/src/player/components/timelineClipDragCommit.ts
+++ b/packages/studio/src/player/components/timelineClipDragCommit.ts
@@ -1,5 +1,8 @@
import type { TimelineElement } from "../store/playerStore";
import type { DraggedClipState } from "./useTimelineClipDrag";
+// Type-only: erased at runtime, so the timelineZMirror → timelineClipDragCommit
+// value-import edge stays acyclic.
+import type { ZMirrorLaneMove } from "./timelineZMirror";
import { classifyZone, normalizeToZones } from "./timelineZones";
import { computeStackingPatches, type StackingPatch } from "./timelineStackingSync";
import { getTimelineEditCapabilities } from "./timelineEditing";
@@ -8,6 +11,7 @@ import {
beginTimelineOptimisticGesture,
isLatestTimelineOptimisticGesture,
} from "./timelineOptimisticRevision";
+import { runLaneZGesture } from "../../components/nle/zLaneGesture";
type StartTrack = Pick<TimelineElement, "start" | "track">;
export interface TimelineMoveEdit {
@@ -31,11 +35,14 @@ export interface DragCommitDeps {
/** Atomic multi-clip persist (single undo) for lane changes + track inserts.
* `coalesceKey`, when supplied, tags the resulting "Move timeline clips"
* history entry so it merges with the lane change's z-reorder entry (see the
- * lane-change branch below). */
+ * lane-change branch below). `coalesceMs` widens that entry's fold window
+ * (per-gesture-unique keys make an unbounded window safe) — required when a
+ * server round-trip sits between the gesture's two records. */
onMoveElements?: (
edits: TimelineMoveEdit[],
coalesceKey?: string,
operation?: TimelineMoveOperation,
+ coalesceMs?: number,
) => Promise<void> | void;
/**
* The current multi-selection (store.selectedElementIds). When the dragged
@@ -60,18 +67,13 @@ export interface DragCommitDeps {
* the canvas z-order commit uses (handleDomZIndexReorderCommit). Documented in
* research/STAGE3-NEEDED-WIRING.md.
*/
- onStackingPatches?: (patches: StackingPatch[], coalesceKey?: string) => void;
+ onStackingPatches?: (patches: StackingPatch[], coalesceKey?: string) => Promise<unknown> | void;
}
const keyOf = (e: TimelineElement) => e.key ?? e.id;
const round3 = (v: number) => Math.round(v * 1000) / 1000;
-// One coalesce key per lane-change gesture, shared by the move-persist history
-// entry ("Move timeline clips") and the follow-up z-reorder entry ("Reorder
-// layers") so editHistory (pushEditHistoryEntry) folds the two consecutive
-// records into a single undo step. A monotonic counter — NOT Date.now() /
-// Math.random(), which the determinism rules forbid — suffices: the key only has
-// to be unique per gesture and identical across the gesture's two records.
+// One deterministic coalesce key shared by both records in a lane-change gesture.
let laneChangeGestureSeq = 0;
/** Whether Studio may write timing to this clip (false for locked/implicit rows). */
@@ -101,12 +103,17 @@ function canMoveElement(element: TimelineElement): boolean {
* `false` so the caller also skips the z-sync (no orphaned z patch).
*
* The DOM is updated synchronously up front; the returned promise never rejects.
+ *
+ * Exported for reuse by non-drag batch time-moves (track gap closing — see
+ * timelineGapCommit.ts) so they share the same optimistic-apply, rollback, and
+ * atomic single-undo persist semantics as a drag commit.
*/
-function persistMoveEdits(
+export function persistMoveEdits(
edits: TimelineMoveEdit[],
deps: DragCommitDeps,
coalesceKey?: string,
operation: TimelineMoveOperation = "timing",
+ coalesceMs?: number,
): Promise<boolean> {
if (edits.length === 0) return Promise.resolve(true);
const { updateElement, onMoveElement, onMoveElements } = deps;
@@ -148,7 +155,7 @@ function persistMoveEdits(
: { element: e.element, updates: { ...e.updates, track: e.persistTrack } },
);
const persisted = onMoveElements
- ? onMoveElements(persistEdits, coalesceKey, operation)
+ ? onMoveElements(persistEdits, coalesceKey, operation, coalesceMs)
: Promise.all(persistEdits.map((e) => Promise.resolve(onMoveElement?.(e.element, e.updates))));
return Promise.resolve(persisted).then(
() => true,
@@ -173,7 +180,7 @@ function persistMoveEdits(
/** Same-source-file predicate: authored track numbers only compare within ONE
* file's coordinate space (an expanded sub-comp child's authoredTrack is in ITS
* file, not the host timeline's). `undefined` means the active composition. */
-const sameSourceFile = (a: TimelineElement, b: TimelineElement): boolean =>
+export const sameSourceFile = (a: TimelineElement, b: TimelineElement): boolean =>
(a.sourceFile ?? null) === (b.sourceFile ?? null);
/**
@@ -203,7 +210,7 @@ const sameSourceFile = (a: TimelineElement, b: TimelineElement): boolean =>
* Edge-created lanes (min-1 / max+1 inserts) route through the insert path,
* never here.
*/
-function authoredTrackForLane(
+export function authoredTrackForLane(
lane: number,
elements: TimelineElement[],
dragged: TimelineElement,
@@ -217,7 +224,10 @@ function authoredTrackForLane(
if (!nearest || Math.abs(p.track - lane) < Math.abs(nearest.track - lane)) nearest = p;
}
if (!nearest) return lane;
- return (nearest.authoredTrack ?? nearest.track) + (lane - nearest.track);
+ // Rounded: expanded children live on FRACTIONAL synthetic display rows (see
+ // buildChildElements), so a lane distance measured against one can carry a
+ // fraction — an authored data-track-index must stay an integer.
+ return Math.round((nearest.authoredTrack ?? nearest.track) + (lane - nearest.track));
}
function insertTrackValue(trackOrder: number[], insertRow: number): number {
@@ -351,8 +361,13 @@ export function commitDraggedClipMove(drag: DraggedClipState, deps: DragCommitDe
return e;
});
const multiKeys = multi ? multi.keys : null;
- void persistMoveEdits(edits, deps, coalesceKey, "lane-reorder").then((moved) => {
- if (moved && isVertical) {
+ if (!isVertical || !deps.readZIndex || !deps.onStackingPatches) {
+ void persistMoveEdits(edits, deps, coalesceKey, "lane-reorder");
+ return;
+ }
+ void runLaneZGesture({
+ commitLane: () => persistMoveEdits(edits, deps, coalesceKey, "lane-reorder"),
+ commitZ: () =>
syncStackingForEdit(
candidate,
dragKey,
@@ -361,81 +376,123 @@ export function commitDraggedClipMove(drag: DraggedClipState, deps: DragCommitDe
multiKeys,
deps,
coalesceKey,
- );
- }
- });
+ ),
+ }).catch(() => undefined);
}
-/**
- * Insert a new track at the drop's gap boundary. The dragged clip lands on the
- * fractional insert lane; normalizeToZones then compacts every lane to a contiguous
- * integer, which shifts the clips at/below the insert down by one. That +1
- * renumber is the ONLY sanctioned multi-clip write; it is index-only (never z).
- * The whole affected set is persisted atomically (single undo), and the deliberate
- * vertical move syncs the dragged clip's stacking afterwards.
- */
+/** Build the one sanctioned multi-clip write: atomically insert and compact a
+ * source-file zone, then let the caller sync the deliberate vertical stacking. */
// fallow-ignore-next-line complexity
-function commitTrackInsert(
- drag: DraggedClipState,
- deps: DragCommitDeps,
+function buildTrackInsertEdits(
+ element: TimelineElement,
+ previewStart: number,
+ insertRow: number,
multi: {
keys: ReadonlySet<string>;
movedStart: (e: TimelineElement) => number;
} | null,
-): void {
+ deps: DragCommitDeps,
+): { candidate: TimelineElement[]; edits: TimelineMoveEdit[] } | null {
const { elements, trackOrder } = deps;
- const dragKey = keyOf(drag.element);
- const targetTrack = insertTrackValue(trackOrder, drag.insertRow!);
- // Drop-intent set: dragged clip at the fractional insert lane (so it sorts
- // between its neighbours), selection members time-shifted, others as-is.
+ const editKey = keyOf(element);
+ // Expanded-child rows are synthetic host lanes, not source-file topology.
+ if (element.expandedParentStart != null) return null;
+ const targetTrack = insertTrackValue(trackOrder, insertRow);
const candidate = elements.map((e) => {
- if (keyOf(e) === dragKey) return { ...e, start: drag.previewStart, track: targetTrack };
+ if (keyOf(e) === editKey) return { ...e, start: previewStart, track: targetTrack };
if (multi?.keys.has(keyOf(e))) return { ...e, start: multi.movedStart(e) };
return e;
});
- // normalizeToZones compacts the fractional lane to a contiguous integer, which
- // shifts the at/below clips down by one — the sanctioned +1 index renumber.
- const normalized = normalizeToZones(candidate);
+ // Foreign display rows and the opposite zone must not affect this topology.
+ const writableZone = classifyZone(element);
+ const writable = (src: TimelineElement): boolean =>
+ sameSourceFile(src, element) &&
+ classifyZone(src) === writableZone &&
+ src.expandedParentStart == null;
+ const topologyOrder = [...new Set(elements.filter(writable).map((e) => e.track))].sort(
+ (a, b) => a - b,
+ );
+ const topologyInsertRow = topologyOrder.filter((track) => track < targetTrack).length;
+ const topologyTargetTrack = insertTrackValue(topologyOrder, topologyInsertRow);
+ const normalized = normalizeToZones(
+ elements.filter(writable).map((e) => {
+ if (keyOf(e) === editKey) {
+ return { ...e, start: previewStart, track: topologyTargetTrack };
+ }
+ if (multi?.keys.has(keyOf(e))) return { ...e, start: multi.movedStart(e) };
+ return e;
+ }),
+ );
const bySrc = new Map(elements.map((e) => [keyOf(e), e]));
- // The renumber is only correct as a WHOLE-SET write: skipping an unwritable
- // clip whose lane shifts leaves its track colliding with a renumbered
- // neighbour, and the next normalize merges the two lanes. If any shifted clip
- // can't be written, refuse the insert instead of persisting a broken layout.
+ // A partial zone renumber creates collisions; refuse a shifted locked row.
for (const norm of normalized) {
const src = bySrc.get(keyOf(norm));
- if (src && !canMoveElement(src) && norm.track !== src.track) {
+ if (
+ src &&
+ writable(src) &&
+ !canMoveElement(src) &&
+ norm.track !== (src.authoredTrack ?? src.track)
+ ) {
console.warn(
`[Timeline] Track insert refused: locked clip ${keyOf(src)} would need renumbering`,
);
- return;
+ return null;
}
}
const edits: TimelineMoveEdit[] = [];
+ if (multi) {
+ for (const src of elements) {
+ const srcKey = keyOf(src);
+ if (srcKey !== editKey && multi.keys.has(srcKey) && !writable(src) && canMoveElement(src)) {
+ edits.push({
+ element: src,
+ updates: { start: multi.movedStart(src), track: src.track },
+ persistTrack: src.authoredTrack,
+ });
+ }
+ }
+ }
for (const norm of normalized) {
const src = bySrc.get(keyOf(norm));
- if (!src) continue;
- // Capabilities gate (unchanged-lane clips only reach here now): never write
- // a locked/implicit clip.
- if (!canMoveElement(src)) continue;
+ if (!src || !canMoveElement(src)) continue;
const start =
- keyOf(norm) === dragKey || multi?.keys.has(keyOf(norm))
- ? (multi?.movedStart(src) ?? drag.previewStart)
+ keyOf(norm) === editKey || multi?.keys.has(keyOf(norm))
+ ? (multi?.movedStart(src) ?? previewStart)
: src.start;
edits.push({ element: src, updates: { start, track: norm.track } });
}
+ return { candidate, edits };
+}
+
+function commitTrackInsert(
+ drag: DraggedClipState,
+ deps: DragCommitDeps,
+ multi: {
+ keys: ReadonlySet<string>;
+ movedStart: (e: TimelineElement) => number;
+ } | null,
+): void {
+ const dragKey = keyOf(drag.element);
+ const built = buildTrackInsertEdits(
+ drag.element,
+ drag.previewStart,
+ drag.insertRow!,
+ multi,
+ deps,
+ );
+ if (!built) return;
+ const { candidate, edits } = built;
+ if (edits.length === 0) return;
const coalesceKey = `clip-lane-move:${laneChangeGestureSeq++}`;
- void persistMoveEdits(edits, deps, coalesceKey, "track-insert").then((moved) => {
- // Skip the z-sync when the insert produced NO move edits (e.g. every clip in
- // the set is locked/implicit and gets filtered out). persistMoveEdits resolves
- // `true` for an empty batch so the caller's serialization proceeds, but firing
- // the z-sync here would record an orphaned z-only history entry for a move that
- // never persisted.
- if (moved && edits.length > 0) {
- // Reason the z-sync on the drop-intent `candidate` (dragged clip at its
- // fractional insert lane) — NOT the re-normalized lanes — so the sync sees
- // the user's move. The guard lane is the aimed insert row (a boundary in
- // display-lane space, comparable to the clip's contiguous current lane).
+ if (!deps.readZIndex || !deps.onStackingPatches) {
+ void persistMoveEdits(edits, deps, coalesceKey, "track-insert");
+ return;
+ }
+ void runLaneZGesture({
+ commitLane: () => persistMoveEdits(edits, deps, coalesceKey, "track-insert"),
+ commitZ: () =>
+ // Sync from the fractional drop intent, not the normalized persisted lanes.
syncStackingForEdit(
candidate,
dragKey,
@@ -444,9 +501,54 @@ function commitTrackInsert(
multi ? multi.keys : null,
deps,
coalesceKey,
- );
- }
- });
+ ),
+ }).catch(() => undefined);
+}
+
+/**
+ * Commit the timeline lane move that MIRRORS a canvas z-order menu action
+ * (resolveZMirrorLaneMove's non-null result). Same machinery as a lane drag:
+ *
+ * - kind "move": persistMoveEdits with `{start: element.start, track: displayTrack}`
+ * + `persistTrack` — identical shape to commitDraggedClipMove's lane-change
+ * branch (optimistic store update, authoredTrack mirror, rollback on failure).
+ * - kind "insert": buildTrackInsertEdits — the SAME renumber core commitTrackInsert
+ * uses — then the same atomic persist.
+ *
+ * Deliberately NO syncStackingForEdit here: the z values were just set by the
+ * user's menu action, and the lane→z sync would recompute (and fight) them. The
+ * mirror caller also omits `readZIndex`/`onStackingPatches` from `deps`, so even
+ * a future call into the sync would no-op (double protection; see
+ * useCanvasZOrderTimelineMirror).
+ *
+ * `coalesceKey` MUST be the z persist's key (`z-reorder:<action>:<ids>:g<seq>`)
+ * so editHistory folds the z write and this track write into ONE undo entry, and
+ * `coalesceMs` MUST widen this record's fold window: the mirror only runs after
+ * the z persist's server round-trip resolved, so under real network latency the
+ * gap between the two records exceeds the reducer's 300ms default and the fold
+ * would never happen live. The key is unique per gesture, so an unbounded
+ * window can never merge distinct gestures.
+ *
+ * Resolves `true` once the move persisted, `false` on rollback / refused insert.
+ */
+export function commitZMirrorLaneMove(
+ element: TimelineElement,
+ move: NonNullable<ZMirrorLaneMove>,
+ deps: DragCommitDeps,
+ coalesceKey: string,
+ coalesceMs?: number,
+): Promise<boolean> {
+ if (move.kind === "move") {
+ const edit: TimelineMoveEdit = {
+ element,
+ updates: { start: element.start, track: move.displayTrack },
+ persistTrack: move.persistTrack,
+ };
+ return persistMoveEdits([edit], deps, coalesceKey, "lane-reorder", coalesceMs);
+ }
+ const built = buildTrackInsertEdits(element, element.start, move.insertRow, null, deps);
+ if (!built || built.edits.length === 0) return Promise.resolve(false);
+ return persistMoveEdits(built.edits, deps, coalesceKey, "track-insert", coalesceMs);
}
/**
@@ -467,18 +569,16 @@ function syncStackingForEdit(
multiKeys: ReadonlySet<string> | null,
deps: DragCommitDeps,
coalesceKey?: string,
-): void {
+): Promise<void> {
const { readZIndex, onStackingPatches } = deps;
- if (!readZIndex || !onStackingPatches) return;
+ if (!readZIndex || !onStackingPatches) return Promise.resolve();
// Aiming at the clip's OWN current display lane is not a relocation — never
// touch z (guards the pure-time-move invariant even if a spurious topology call
// slips through). Every real lane-realization drop aims at a DIFFERENT lane.
- if (aimedLane === currentLane) return;
+ if (aimedLane === currentLane) return Promise.resolve();
- // `candidate` is in discovery order, so its array index IS the DOM document
- // position. Equal-z clips paint by DOM order, so the sync needs it to decide
- // "is A above B" (see StackingElement.domIndex).
+ // Discovery order is DOM order, which breaks equal-z ties.
const stackingEls = candidate.map((el, domIndex) => ({
key: keyOf(el),
start: el.start,
@@ -486,6 +586,7 @@ function syncStackingForEdit(
track: el.track,
zIndex: readZIndex(el),
isAudio: classifyZone(el) === "audio",
+ sourceFile: el.sourceFile,
domIndex,
stackingContextId: el.stackingContextId ?? null,
}));
@@ -494,5 +595,6 @@ function syncStackingForEdit(
if (multiKeys) for (const k of multiKeys) if (k !== dragKey) editedKeys.push(k);
const patches = computeStackingPatches(stackingEls, editedKeys);
- if (patches.length > 0) onStackingPatches(patches, coalesceKey);
+ if (patches.length === 0) return Promise.resolve();
+ return Promise.resolve(onStackingPatches(patches, coalesceKey)).then(() => undefined);
}
diff --git a/packages/studio/src/player/components/timelineGapCommit.test.ts b/packages/studio/src/player/components/timelineGapCommit.test.ts
new file mode 100644
index 0000000000..5fdb280398
--- /dev/null
+++ b/packages/studio/src/player/components/timelineGapCommit.test.ts
@@ -0,0 +1,163 @@
+import { describe, expect, it, vi } from "vitest";
+import type { TimelineElement } from "../store/playerStore";
+import type { DragCommitDeps } from "./timelineClipDragCommit";
+import {
+ canShiftTrackGapClips,
+ commitCloseAllTrackGaps,
+ commitCloseTrackGap,
+} from "./timelineGapCommit";
+import { resolveAllTrackGaps } from "./timelineGaps";
+
+function el(id: string, start: number, duration: number, track = 0): TimelineElement {
+ // domId + video tag → getTimelineEditCapabilities(...).canMove === true
+ return { id, tag: "video", start, duration, track, domId: id };
+}
+
+function lockedEl(id: string, start: number, duration: number): TimelineElement {
+ return { ...el(id, start, duration), timelineLocked: true };
+}
+
+function makeDeps(laneElements: TimelineElement[]) {
+ const onMoveElements = vi.fn(() => Promise.resolve());
+ const updateElement = vi.fn();
+ const deps: DragCommitDeps = {
+ elements: laneElements,
+ trackOrder: [0],
+ updateElement,
+ onMoveElements,
+ };
+ return { deps, onMoveElements, updateElement };
+}
+
+/** Assert exactly ONE atomic persist batch; return its flattened edits + coalesce key. */
+function singleBatch(onMoveElements: ReturnType<typeof vi.fn>) {
+ expect(onMoveElements).toHaveBeenCalledTimes(1);
+ const [edits, coalesceKey] = onMoveElements.mock.calls[0] as unknown as [
+ Array<{ element: TimelineElement; updates: { start: number; track: number } }>,
+ string,
+ ];
+ return { coalesceKey, edits: edits.map((e) => ({ id: e.element.id, ...e.updates })) };
+}
+
+describe("commitCloseTrackGap", () => {
+ it("persists ONE atomic batch shifting the next clip and every clip after it", () => {
+ const lane = [el("a", 0, 2), el("b", 5, 3), el("c", 10, 1)];
+ const { deps, onMoveElements } = makeDeps(lane);
+
+ expect(commitCloseTrackGap(lane, 3, deps)).toBe(true);
+
+ const { edits, coalesceKey } = singleBatch(onMoveElements);
+ // Gap is [2, 5) → width 3; b and c shift left by 3, tracks unchanged.
+ expect(edits).toEqual([
+ { id: "b", start: 2, track: 0 },
+ { id: "c", start: 7, track: 0 },
+ ]);
+ expect(typeof coalesceKey).toBe("string");
+ expect(coalesceKey).toMatch(/^track-gap-close:\d+$/);
+ });
+
+ it("optimistically applies the same starts to the store", () => {
+ const lane = [el("a", 0, 2), el("b", 5, 3)];
+ const { deps, updateElement } = makeDeps(lane);
+ commitCloseTrackGap(lane, 3, deps);
+ expect(updateElement).toHaveBeenCalledWith("b", { start: 2, track: 0 });
+ });
+
+ it("closes the leading gap (first clip lands at 0)", () => {
+ const lane = [el("a", 2, 3), el("b", 6, 1)];
+ const { deps, onMoveElements } = makeDeps(lane);
+
+ expect(commitCloseTrackGap(lane, 1, deps)).toBe(true);
+ const [edits] = onMoveElements.mock.calls[0] as unknown as [
+ Array<{ element: TimelineElement; updates: { start: number; track: number } }>,
+ ];
+ expect(edits.map((e) => ({ id: e.element.id, start: e.updates.start }))).toEqual([
+ { id: "a", start: 0 },
+ { id: "b", start: 4 },
+ ]);
+ });
+
+ it("uses a fresh coalesce key per gesture", () => {
+ const lane = [el("a", 0, 2), el("b", 5, 3)];
+ const first = makeDeps(lane);
+ const second = makeDeps(lane);
+ commitCloseTrackGap(lane, 3, first.deps);
+ commitCloseTrackGap(lane, 3, second.deps);
+ const keyA = first.onMoveElements.mock.calls[0][1 as never];
+ const keyB = second.onMoveElements.mock.calls[0][1 as never];
+ expect(keyA).not.toEqual(keyB);
+ });
+
+ it("refuses (no write) when there is no clip right of the point", () => {
+ const lane = [el("a", 0, 2)];
+ const { deps, onMoveElements, updateElement } = makeDeps(lane);
+ expect(commitCloseTrackGap(lane, 5, deps)).toBe(false);
+ expect(onMoveElements).not.toHaveBeenCalled();
+ expect(updateElement).not.toHaveBeenCalled();
+ });
+
+ it("refuses (no partial compaction) when ANY shifting clip is unmovable", () => {
+ const lane = [el("a", 0, 2), el("b", 5, 3), lockedEl("c", 10, 1)];
+ const { deps, onMoveElements, updateElement } = makeDeps(lane);
+ expect(commitCloseTrackGap(lane, 3, deps)).toBe(false);
+ expect(onMoveElements).not.toHaveBeenCalled();
+ expect(updateElement).not.toHaveBeenCalled();
+ });
+});
+
+describe("commitCloseAllTrackGaps", () => {
+ it("compacts the whole lane in ONE atomic batch (leading gap included)", () => {
+ const lane = [el("a", 1, 2), el("b", 5, 3), el("c", 10, 1)];
+ const { deps, onMoveElements } = makeDeps(lane);
+
+ expect(commitCloseAllTrackGaps(lane, deps)).toBe(true);
+
+ const { edits, coalesceKey } = singleBatch(onMoveElements);
+ expect(edits).toEqual([
+ { id: "a", start: 0, track: 0 },
+ { id: "b", start: 2, track: 0 },
+ { id: "c", start: 5, track: 0 },
+ ]);
+ expect(coalesceKey).toMatch(/^track-gap-close:\d+$/);
+ });
+
+ it("refuses when the track is already contiguous (no gaps)", () => {
+ const lane = [el("a", 0, 2), el("b", 2, 3)];
+ const { deps, onMoveElements } = makeDeps(lane);
+ expect(commitCloseAllTrackGaps(lane, deps)).toBe(false);
+ expect(onMoveElements).not.toHaveBeenCalled();
+ });
+
+ it("refuses when any shifting clip is unmovable, even if others could move", () => {
+ const lane = [lockedEl("a", 1, 2), el("b", 5, 3)];
+ const { deps, onMoveElements, updateElement } = makeDeps(lane);
+ expect(commitCloseAllTrackGaps(lane, deps)).toBe(false);
+ expect(onMoveElements).not.toHaveBeenCalled();
+ expect(updateElement).not.toHaveBeenCalled();
+ });
+
+ it("proceeds when an unmovable clip does NOT need to shift", () => {
+ // Locked clip already sits flush at 0 — only movable clips shift.
+ const lane = [lockedEl("a", 0, 2), el("b", 4, 1)];
+ const { deps, onMoveElements } = makeDeps(lane);
+ expect(commitCloseAllTrackGaps(lane, deps)).toBe(true);
+ const [edits] = onMoveElements.mock.calls[0] as unknown as [
+ Array<{ element: TimelineElement; updates: { start: number } }>,
+ ];
+ expect(edits.map((e) => ({ id: e.element.id, start: e.updates.start }))).toEqual([
+ { id: "b", start: 2 },
+ ]);
+ });
+});
+
+describe("canShiftTrackGapClips", () => {
+ it("is true only when every named clip is movable", () => {
+ const lane = [el("a", 1, 2), lockedEl("b", 5, 3)];
+ expect(canShiftTrackGapClips(lane, [{ key: "a", newStart: 0 }])).toBe(true);
+ expect(canShiftTrackGapClips(lane, resolveAllTrackGaps(lane))).toBe(false);
+ });
+
+ it("is false for unknown keys", () => {
+ expect(canShiftTrackGapClips([el("a", 0, 1)], [{ key: "ghost", newStart: 0 }])).toBe(false);
+ });
+});
diff --git a/packages/studio/src/player/components/timelineGapCommit.ts b/packages/studio/src/player/components/timelineGapCommit.ts
new file mode 100644
index 0000000000..217dc29ac6
--- /dev/null
+++ b/packages/studio/src/player/components/timelineGapCommit.ts
@@ -0,0 +1,103 @@
+import type { TimelineElement } from "../store/playerStore";
+import { getTimelineEditCapabilities } from "./timelineEditing";
+import {
+ persistMoveEdits,
+ type DragCommitDeps,
+ type TimelineMoveEdit,
+} from "./timelineClipDragCommit";
+import {
+ laneGapFloor,
+ resolveAllTrackGaps,
+ resolveCloseGapShifts,
+ resolveTrackGapAt,
+ type TrackGapShift,
+} from "./timelineGaps";
+
+/**
+ * Commit layer for the track-gap context menu ("Close gap" / "Close all gaps").
+ *
+ * Each action is ONE atomic {@link persistMoveEdits} batch — pure time moves
+ * (`updates.track === element.track`, no authored-track rewrite) tagged with a
+ * per-gesture-unique coalesce key, so an action is exactly one undo entry and
+ * flows through the existing move pipeline (optimistic store apply + rollback,
+ * SDK fast path, patchIframeDomTiming preview).
+ *
+ * Refusal rule: if ANY clip that must shift is unmovable
+ * ({@link getTimelineEditCapabilities}.canMove === false), the whole action is
+ * refused — never a partial compaction. The menu disables the item via
+ * {@link canShiftTrackGapClips}; the commit re-checks as defense in depth.
+ */
+
+const keyOf = (e: TimelineElement) => e.key ?? e.id;
+
+// Per-gesture-unique coalesce key. A monotonic counter — NOT Date.now() /
+// Math.random() (determinism rules) — mirrors laneChangeGestureSeq in
+// timelineClipDragCommit.ts.
+let gapCloseGestureSeq = 0;
+
+/** True when every clip named in `shifts` may be time-moved. */
+export function canShiftTrackGapClips(
+ laneElements: readonly TimelineElement[],
+ shifts: readonly TrackGapShift[],
+): boolean {
+ const byKey = new Map(laneElements.map((e) => [keyOf(e), e]));
+ return shifts.every((s) => {
+ const element = byKey.get(s.key);
+ return element != null && getTimelineEditCapabilities(element).canMove;
+ });
+}
+
+function buildShiftEdits(
+ laneElements: readonly TimelineElement[],
+ shifts: readonly TrackGapShift[],
+): TimelineMoveEdit[] | null {
+ if (shifts.length === 0 || !canShiftTrackGapClips(laneElements, shifts)) return null;
+ const byKey = new Map(laneElements.map((e) => [keyOf(e), e]));
+ return shifts.map((s) => {
+ const element = byKey.get(s.key)!;
+ return { element, updates: { start: s.newStart, track: element.track } };
+ });
+}
+
+function commitShifts(
+ laneElements: readonly TimelineElement[],
+ shifts: readonly TrackGapShift[],
+ deps: DragCommitDeps,
+): boolean {
+ const edits = buildShiftEdits(laneElements, shifts);
+ if (!edits) return false;
+ void persistMoveEdits(edits, deps, `track-gap-close:${gapCloseGestureSeq++}`);
+ return true;
+}
+
+/**
+ * Close the ONE gap under `time` on the lane: the next clip and every clip
+ * after it on that lane shift left by the gap's width. Returns false (and
+ * writes nothing) when there is no gap at the point or a shifting clip is
+ * unmovable.
+ */
+export function commitCloseTrackGap(
+ laneElements: readonly TimelineElement[],
+ time: number,
+ deps: DragCommitDeps,
+): boolean {
+ const gap = resolveTrackGapAt(laneElements, time, undefined, laneGapFloor(laneElements));
+ if (!gap) return false;
+ return commitShifts(laneElements, resolveCloseGapShifts(laneElements, gap), deps);
+}
+
+/**
+ * Compact the whole lane (leading gap included): clips become contiguous from
+ * 0, order and durations preserved. Returns false (and writes nothing) when
+ * the lane has no gaps or a shifting clip is unmovable.
+ */
+export function commitCloseAllTrackGaps(
+ laneElements: readonly TimelineElement[],
+ deps: DragCommitDeps,
+): boolean {
+ return commitShifts(
+ laneElements,
+ resolveAllTrackGaps(laneElements, undefined, laneGapFloor(laneElements)),
+ deps,
+ );
+}
diff --git a/packages/studio/src/player/components/timelineGaps.test.ts b/packages/studio/src/player/components/timelineGaps.test.ts
new file mode 100644
index 0000000000..7dcf220d8f
--- /dev/null
+++ b/packages/studio/src/player/components/timelineGaps.test.ts
@@ -0,0 +1,221 @@
+import { describe, expect, it } from "vitest";
+import type { TimelineElement } from "../store/playerStore";
+import {
+ laneGapFloor,
+ resolveAllGapIntervals,
+ resolveAllTrackGaps,
+ resolveCloseGapShifts,
+ resolveTrackGapAt,
+ trackHasGaps,
+} from "./timelineGaps";
+
+function el(id: string, start: number, duration: number): TimelineElement {
+ return { id, tag: "video", start, duration, track: 0, domId: id };
+}
+
+describe("resolveTrackGapAt", () => {
+ it("resolves a middle gap between two clips", () => {
+ const els = [el("a", 0, 2), el("b", 5, 3)];
+ const gap = resolveTrackGapAt(els, 3);
+ expect(gap).toEqual({ gapStart: 2, gapEnd: 5, followingKeys: ["b"] });
+ });
+
+ it("resolves the leading gap before the first clip (gapStart = 0)", () => {
+ const els = [el("a", 2, 3), el("b", 6, 1)];
+ const gap = resolveTrackGapAt(els, 1);
+ expect(gap).toEqual({ gapStart: 0, gapEnd: 2, followingKeys: ["a", "b"] });
+ });
+
+ it("includes EVERY clip at/after the gap in followingKeys", () => {
+ const els = [el("a", 0, 1), el("b", 3, 1), el("c", 5, 1), el("d", 8, 1)];
+ const gap = resolveTrackGapAt(els, 2);
+ expect(gap).toEqual({ gapStart: 1, gapEnd: 3, followingKeys: ["b", "c", "d"] });
+ });
+
+ it("returns null when there is no clip to the right of the point", () => {
+ const els = [el("a", 0, 2)];
+ expect(resolveTrackGapAt(els, 5)).toBeNull();
+ expect(resolveTrackGapAt([], 1)).toBeNull(); // empty lane
+ });
+
+ it("returns null when the point is inside a clip (half-open interval)", () => {
+ const els = [el("a", 1, 2), el("b", 5, 1)];
+ expect(resolveTrackGapAt(els, 2)).toBeNull(); // strictly inside
+ expect(resolveTrackGapAt(els, 1)).toBeNull(); // at clip start (occupied)
+ // At clip END (half-open) the point is free — the gap to "b" resolves.
+ expect(resolveTrackGapAt(els, 3)).toEqual({ gapStart: 3, gapEnd: 5, followingKeys: ["b"] });
+ });
+
+ it("resolves the leading gap for a single clip", () => {
+ const gap = resolveTrackGapAt([el("a", 4, 2)], 1);
+ expect(gap).toEqual({ gapStart: 0, gapEnd: 4, followingKeys: ["a"] });
+ });
+
+ it("treats epsilon-adjacent clips as gapless (float drift)", () => {
+ // 8.4 + 2.7 = 11.100000000000001 — the classic drift: no point near the
+ // seam resolves a gap.
+ const drifted = [el("a", 8.4, 2.7), el("b", 11.1, 2)];
+ expect(resolveTrackGapAt(drifted, 11.0999)).toBeNull();
+ expect(resolveTrackGapAt(drifted, 11.1005)).toBeNull();
+ // A sub-epsilon sliver between clips is not a closable gap either.
+ const sliver = [el("a", 0, 2.0004), el("b", 2.001, 1)];
+ expect(resolveTrackGapAt(sliver, 1.9995)).toBeNull();
+ });
+
+ it("handles overlapping clips sanely (uses the max end left of the point)", () => {
+ const els = [el("a", 0, 4), el("b", 1, 2), el("c", 6, 1)];
+ const gap = resolveTrackGapAt(els, 5);
+ expect(gap).toEqual({ gapStart: 4, gapEnd: 6, followingKeys: ["c"] });
+ });
+
+ it("prefers the key over the id when present", () => {
+ const withKey = { ...el("a", 3, 1), key: "a-key" };
+ const gap = resolveTrackGapAt([withKey], 1);
+ expect(gap?.followingKeys).toEqual(["a-key"]);
+ });
+});
+
+describe("resolveCloseGapShifts", () => {
+ it("shifts the following clips left by exactly the gap width", () => {
+ const els = [el("a", 0, 2), el("b", 5, 3), el("c", 10, 1)];
+ const gap = resolveTrackGapAt(els, 3)!;
+ expect(resolveCloseGapShifts(els, gap)).toEqual([
+ { key: "b", newStart: 2 },
+ { key: "c", newStart: 7 },
+ ]);
+ });
+
+ it("closing the leading gap lands the first clip at 0", () => {
+ const els = [el("a", 2, 3), el("b", 6, 1)];
+ const gap = resolveTrackGapAt(els, 1)!;
+ expect(resolveCloseGapShifts(els, gap)).toEqual([
+ { key: "a", newStart: 0 },
+ { key: "b", newStart: 4 },
+ ]);
+ });
+
+ it("rounds shifted starts to millisecond precision", () => {
+ const els = [el("a", 0, 1.1), el("b", 3.3000000000000003, 1)];
+ const gap = resolveTrackGapAt(els, 2)!;
+ const shifts = resolveCloseGapShifts(els, gap);
+ expect(shifts).toEqual([{ key: "b", newStart: 1.1 }]);
+ });
+});
+
+describe("resolveAllTrackGaps", () => {
+ it("compacts every gap: contiguous from 0, order and durations preserved", () => {
+ const els = [el("a", 1, 2), el("b", 5, 3), el("c", 10, 1)];
+ expect(resolveAllTrackGaps(els)).toEqual([
+ { key: "a", newStart: 0 },
+ { key: "b", newStart: 2 },
+ { key: "c", newStart: 5 },
+ ]);
+ });
+
+ it("includes the leading gap for a single clip", () => {
+ expect(resolveAllTrackGaps([el("a", 4, 2)])).toEqual([{ key: "a", newStart: 0 }]);
+ });
+
+ it("returns only the clips whose start actually changes", () => {
+ const els = [el("a", 0, 2), el("b", 2, 1), el("c", 5, 1)];
+ expect(resolveAllTrackGaps(els)).toEqual([{ key: "c", newStart: 3 }]);
+ });
+
+ it("returns [] for an already-contiguous track and for an empty lane", () => {
+ expect(resolveAllTrackGaps([el("a", 0, 2), el("b", 2, 3)])).toEqual([]);
+ expect(resolveAllTrackGaps([])).toEqual([]);
+ });
+
+ it("ignores epsilon-level drift instead of emitting no-op shifts", () => {
+ const els = [el("a", 0, 8.4), el("b", 8.4, 2.7), el("c", 11.100000000000001, 2)];
+ expect(resolveAllTrackGaps(els)).toEqual([]);
+ });
+
+ it("serializes overlapping clips in start order (sum-of-durations rule)", () => {
+ const els = [el("a", 0, 4), el("b", 2, 2)];
+ expect(resolveAllTrackGaps(els)).toEqual([{ key: "b", newStart: 4 }]);
+ });
+
+ it("is deterministic for identical starts (key tie-break)", () => {
+ const els = [el("b", 3, 1), el("a", 3, 2)];
+ expect(resolveAllTrackGaps(els)).toEqual([
+ { key: "a", newStart: 0 },
+ { key: "b", newStart: 2 },
+ ]);
+ });
+});
+
+describe("resolveAllGapIntervals", () => {
+ it("reports every current gap, leading gap included, left to right", () => {
+ const els = [el("a", 1, 2), el("b", 5, 3), el("c", 10, 1)];
+ expect(resolveAllGapIntervals(els)).toEqual([
+ { start: 0, end: 1 },
+ { start: 3, end: 5 },
+ { start: 8, end: 10 },
+ ]);
+ });
+
+ it("returns [] for contiguous or empty lanes", () => {
+ expect(resolveAllGapIntervals([el("a", 0, 2), el("b", 2, 3)])).toEqual([]);
+ expect(resolveAllGapIntervals([])).toEqual([]);
+ });
+
+ it("never fabricates an interval from overlapping clips (cursor = max end)", () => {
+ const els = [el("a", 0, 4), el("b", 1, 2), el("c", 6, 1)];
+ expect(resolveAllGapIntervals(els)).toEqual([{ start: 4, end: 6 }]);
+ });
+
+ it("ignores epsilon-level drift seams", () => {
+ const els = [el("a", 0, 8.4), el("b", 8.4, 2.7), el("c", 11.100000000000001, 2)];
+ expect(resolveAllGapIntervals(els)).toEqual([]);
+ });
+});
+
+describe("trackHasGaps", () => {
+ it("detects gaps, including the leading gap", () => {
+ expect(trackHasGaps([el("a", 1, 2)])).toBe(true);
+ expect(trackHasGaps([el("a", 0, 2), el("b", 4, 1)])).toBe(true);
+ });
+
+ it("is false for contiguous or empty tracks", () => {
+ expect(trackHasGaps([el("a", 0, 2), el("b", 2, 1)])).toBe(false);
+ expect(trackHasGaps([])).toBe(false);
+ });
+});
+
+describe("lane floor (expanded sub-comp children)", () => {
+ const child = (id: string, start: number, duration: number): TimelineElement => ({
+ ...el(id, start, duration),
+ expandedParentStart: 16,
+ sourceFile: "scene.html",
+ });
+
+ it("laneGapFloor is 0 for ordinary lanes and the host window start for child lanes", () => {
+ expect(laneGapFloor([el("a", 0, 2)])).toBe(0);
+ expect(laneGapFloor([child("c1", 16.5, 2), child("c2", 20, 2)])).toBe(16);
+ });
+
+ it("compaction lands the first child at the HOST window start, never absolute 0", () => {
+ const lane = [child("c1", 18, 2), child("c2", 22, 2)];
+ expect(resolveAllTrackGaps(lane, undefined, laneGapFloor(lane))).toEqual([
+ { key: "c1", newStart: 16 },
+ { key: "c2", newStart: 18 },
+ ]);
+ });
+
+ it("the leading gap starts at the floor for both close-one and the highlight intervals", () => {
+ const lane = [child("c1", 18, 2)];
+ const floor = laneGapFloor(lane);
+ expect(resolveTrackGapAt(lane, 17, undefined, floor)).toEqual({
+ gapStart: 16,
+ gapEnd: 18,
+ followingKeys: ["c1"],
+ });
+ expect(resolveAllGapIntervals(lane, undefined, floor)).toEqual([{ start: 16, end: 18 }]);
+ });
+
+ it("a child lane contiguous from its host start has no gaps", () => {
+ const lane = [child("c1", 16, 2), child("c2", 18, 2)];
+ expect(trackHasGaps(lane, undefined, laneGapFloor(lane))).toBe(false);
+ });
+});
diff --git a/packages/studio/src/player/components/timelineGaps.ts b/packages/studio/src/player/components/timelineGaps.ts
new file mode 100644
index 0000000000..ce76fa7a25
--- /dev/null
+++ b/packages/studio/src/player/components/timelineGaps.ts
@@ -0,0 +1,182 @@
+import type { TimelineElement } from "../store/playerStore";
+
+/**
+ * Pure gap math for a single timeline display lane (CapCut/Premiere-style
+ * "Close gap" / "Close all gaps"). Operates on the DISPLAY element set the
+ * timeline renders for one lane — the caller passes the clips of the
+ * right-clicked lane only; cross-lane behavior is out of scope by design.
+ *
+ * Conventions:
+ * - A clip occupies the half-open interval [start, start + duration).
+ * - Comparisons are epsilon-tolerant ({@link TRACK_GAP_EPSILON_S}) so float
+ * drift (e.g. 8.4 + 2.7 = 11.100000000000001) never fabricates a sliver gap.
+ * - Computed starts are rounded to millisecond precision, matching the drag
+ * commit's `round3`.
+ */
+const TRACK_GAP_EPSILON_S = 1e-3;
+
+const keyOf = (e: TimelineElement) => e.key ?? e.id;
+
+/**
+ * The lane's time ORIGIN — the earliest start a clip on this lane may take.
+ * 0 for ordinary lanes; for a lane of expanded sub-comp children (post-
+ * collision-fix a lane is always single-origin) it is the children's host
+ * window start (`expandedParentStart`): display times are host-absolute, so
+ * compacting toward absolute 0 would drag a child BEFORE its host's window
+ * and persist a wrong (even negative) local time.
+ */
+export function laneGapFloor(elements: readonly TimelineElement[]): number {
+ return Math.max(0, ...elements.map((e) => e.expandedParentStart ?? 0));
+}
+const round3 = (v: number) => Math.round(v * 1000) / 1000;
+const endOf = (e: TimelineElement) => e.start + e.duration;
+
+/** Lane clips sorted by start (key as a deterministic tie-break). */
+function sortedLaneClips(elements: readonly TimelineElement[]): TimelineElement[] {
+ return [...elements].sort((a, b) => a.start - b.start || keyOf(a).localeCompare(keyOf(b)));
+}
+
+export interface TrackGapAt {
+ /** Gap left edge: the max end of the clips left of the point (0 for the leading gap). */
+ gapStart: number;
+ /** Gap right edge: the start of the next clip on the lane. */
+ gapEnd: number;
+ /** Keys of the next clip and every clip after it on the lane, in start order. */
+ followingKeys: string[];
+}
+
+/**
+ * Resolve the gap under a right-clicked point on one lane.
+ *
+ * Returns null when the point sits inside a clip, when there is no clip to the
+ * right of the point (nothing to close), or when the neighbouring clips are
+ * epsilon-adjacent (no real gap).
+ */
+export function resolveTrackGapAt(
+ elements: readonly TimelineElement[],
+ time: number,
+ epsilon: number = TRACK_GAP_EPSILON_S,
+ floor: number = 0,
+): TrackGapAt | null {
+ const clips = sortedLaneClips(elements);
+ // Point inside a clip's half-open [start, end) → not empty space.
+ const occupied = clips.some((c) => time >= c.start - epsilon && time < endOf(c) - epsilon);
+ if (occupied) return null;
+
+ const following = clips.filter((c) => c.start > time - epsilon);
+ if (following.length === 0) return null; // nothing to the right — nothing to close
+
+ const gapEnd = following[0].start;
+ // Max end among clips left of the point (they all end at/before it since the
+ // point is unoccupied); the lane floor for the leading gap before the first
+ // clip (0 for ordinary lanes, the host window start for expanded children).
+ const gapStart = Math.max(
+ floor,
+ ...clips.filter((c) => c.start <= time - epsilon).map((c) => endOf(c)),
+ );
+ if (gapEnd - gapStart <= epsilon) return null; // epsilon-adjacent — no gap
+
+ return { gapStart, gapEnd, followingKeys: following.map(keyOf) };
+}
+
+export interface TrackGapShift {
+ key: string;
+ newStart: number;
+}
+
+/** An empty interval on the lane, [start, end) in seconds. */
+export interface TrackGapInterval {
+ start: number;
+ end: number;
+}
+
+/**
+ * Every CURRENT empty interval on the lane, leading gap included — the regions
+ * "Close all gaps" would collapse, in left-to-right order. Purely descriptive
+ * (for the hover-highlight overlay): unlike {@link resolveAllTrackGaps} it
+ * reports the gaps as they are now, not the post-compaction clip starts.
+ * Overlapping clips never fabricate a negative interval (the cursor tracks the
+ * max end seen so far).
+ */
+export function resolveAllGapIntervals(
+ elements: readonly TimelineElement[],
+ epsilon: number = TRACK_GAP_EPSILON_S,
+ floor: number = 0,
+): TrackGapInterval[] {
+ const gaps: TrackGapInterval[] = [];
+ let cursor = floor;
+ for (const clip of sortedLaneClips(elements)) {
+ if (clip.start - cursor > epsilon) gaps.push({ start: cursor, end: clip.start });
+ cursor = Math.max(cursor, endOf(clip));
+ }
+ return gaps;
+}
+
+/**
+ * Compact the whole lane: every clip lands at the sum of the durations of the
+ * clips before it (contiguous from 0, order and durations preserved).
+ * Overlapping clips (spill lanes) are serialized in start order — sane, if
+ * lossy for deliberate overlaps; the display lane set should not contain them.
+ *
+ * Returns ONLY the clips whose start actually changes (beyond epsilon).
+ */
+export function resolveAllTrackGaps(
+ elements: readonly TimelineElement[],
+ epsilon: number = TRACK_GAP_EPSILON_S,
+ floor: number = 0,
+): TrackGapShift[] {
+ const shifts: TrackGapShift[] = [];
+ let cursor = floor;
+ for (const clip of sortedLaneClips(elements)) {
+ const newStart = round3(cursor);
+ if (Math.abs(newStart - clip.start) > epsilon) {
+ shifts.push({ key: keyOf(clip), newStart });
+ }
+ cursor += clip.duration;
+ }
+ return shifts;
+}
+
+/**
+ * Every empty interval on the lane across the FULL rendered extent `[0, end)`:
+ * the closable gaps plus the open region after the last clip. Powers the
+ * click-selected lane highlight ("light the whole track except the clips") —
+ * unlike {@link resolveAllGapIntervals} it is not limited to what a gap-close
+ * could collapse.
+ */
+export function resolveLaneEmptyIntervals(
+ elements: readonly TimelineElement[],
+ end: number,
+ epsilon: number = TRACK_GAP_EPSILON_S,
+ floor: number = 0,
+): TrackGapInterval[] {
+ const gaps = resolveAllGapIntervals(elements, epsilon, floor);
+ const maxEnd = Math.max(floor, ...elements.map(endOf));
+ if (end - maxEnd > epsilon) gaps.push({ start: maxEnd, end });
+ return gaps;
+}
+
+/** Whether the lane has any gap "Close all gaps" would collapse. */
+export function trackHasGaps(
+ elements: readonly TimelineElement[],
+ epsilon: number = TRACK_GAP_EPSILON_S,
+ floor: number = 0,
+): boolean {
+ return resolveAllTrackGaps(elements, epsilon, floor).length > 0;
+}
+
+/**
+ * Per-clip shifts for closing ONE gap: the next clip and every clip after it
+ * on the lane move left by the gap's width. Starts are clamped at 0 (float
+ * safety; real shifts never cross the gap's own left edge).
+ */
+export function resolveCloseGapShifts(
+ elements: readonly TimelineElement[],
+ gap: TrackGapAt,
+): TrackGapShift[] {
+ const width = gap.gapEnd - gap.gapStart;
+ const followSet = new Set(gap.followingKeys);
+ return sortedLaneClips(elements)
+ .filter((c) => followSet.has(keyOf(c)))
+ .map((c) => ({ key: keyOf(c), newStart: Math.max(gap.gapStart, round3(c.start - width)) }));
+}
diff --git a/packages/studio/src/player/components/timelineLayout.test.ts b/packages/studio/src/player/components/timelineLayout.test.ts
index 24e746e612..3642dea953 100644
--- a/packages/studio/src/player/components/timelineLayout.test.ts
+++ b/packages/studio/src/player/components/timelineLayout.test.ts
@@ -5,6 +5,7 @@ import {
TRACKS_TOP_PAD,
TRACKS_BOTTOM_PAD,
GUTTER,
+ TRACKS_LEFT_PAD,
getTimelineRowTop,
getTimelineRowFromY,
getTimelineCanvasHeight,
@@ -85,7 +86,7 @@ describe("track-area breathing pad y-math", () => {
it("drops onto lane 0 when the pointer is in the middle of the first lane", () => {
const clientY = getTimelineRowTop(0) + TRACK_H / 2;
- const clientX = GUTTER + 100; // t = 1s
+ const clientX = GUTTER + TRACKS_LEFT_PAD + 100; // t = 1s
const { start, track } = resolveTimelineAssetDrop(base, clientX, clientY);
expect(track).toBe(0);
expect(start).toBe(1);
diff --git a/packages/studio/src/player/components/timelineLayout.ts b/packages/studio/src/player/components/timelineLayout.ts
index b5b08e6a3c..3b3562e480 100644
--- a/packages/studio/src/player/components/timelineLayout.ts
+++ b/packages/studio/src/player/components/timelineLayout.ts
@@ -31,6 +31,17 @@ export const INSERT_BOUNDARY_BAND = CLIP_Y / TRACK_H;
*/
export const TRACKS_TOP_PAD = 50;
export const TRACKS_BOTTOM_PAD = Math.round(TRACK_H * 1.5);
+/**
+ * Breathing room LEFT of t=0 (CapCut-style), inside the scroll content — the
+ * horizontal sibling of TRACKS_TOP_PAD: empty lane surface between the sticky
+ * gutter and where the ruler's 00:00 / the clips actually start, scrolling
+ * WITH the content. Time↔pixel mapping: content x = GUTTER + TRACKS_LEFT_PAD
+ * + t·pps, and every pointer→time inverse subtracts it symmetrically. The
+ * lanes and the ruler realize it as a plain flow spacer between the sticky
+ * gutter cell and the time-mapped content div, so all content-relative math
+ * (clip left = t·pps, beat lines, lane-menu time) is untouched.
+ */
+export const TRACKS_LEFT_PAD = 48;
/**
* The y (content-space) of the top edge of track ROW index `row` (0 = first
@@ -209,8 +220,8 @@ export function getTimelineFitPps(viewportWidth: number, effectiveDuration: numb
const safeDuration =
Number.isFinite(effectiveDuration) && effectiveDuration > 0 ? effectiveDuration : 0;
const span = Math.max(safeDuration * FIT_ZOOM_HEADROOM, MIN_TIMELINE_EXTENT_S);
- if (!Number.isFinite(viewportWidth) || viewportWidth <= GUTTER) return 100;
- return (viewportWidth - GUTTER - 2) / span;
+ if (!Number.isFinite(viewportWidth) || viewportWidth <= GUTTER + TRACKS_LEFT_PAD) return 100;
+ return (viewportWidth - GUTTER - TRACKS_LEFT_PAD - 2) / span;
}
/**
@@ -230,7 +241,7 @@ export function getTimelineDisplayContentWidth(input: {
const safePps = Number.isFinite(input.pps) ? Math.max(input.pps, 0) : 0;
return Math.max(
input.trackContentWidth,
- input.viewportWidth - GUTTER - 2,
+ input.viewportWidth - GUTTER - TRACKS_LEFT_PAD - 2,
input.dragGhostEndPx ?? 0,
input.resizeGhostEndPx ?? 0,
MIN_TIMELINE_EXTENT_S * safePps,
@@ -300,9 +311,14 @@ export const PLAYHEAD_HEAD_W = 9;
*/
export function getTimelinePlayheadLeft(time: number, pixelsPerSecond: number): number {
if (!Number.isFinite(time) || !Number.isFinite(pixelsPerSecond)) {
- return GUTTER - PLAYHEAD_HEAD_W / 2;
+ return GUTTER + TRACKS_LEFT_PAD - PLAYHEAD_HEAD_W / 2;
}
- return GUTTER + Math.max(0, time) * Math.max(0, pixelsPerSecond) - PLAYHEAD_HEAD_W / 2;
+ return (
+ GUTTER +
+ TRACKS_LEFT_PAD +
+ Math.max(0, time) * Math.max(0, pixelsPerSecond) -
+ PLAYHEAD_HEAD_W / 2
+ );
}
export function getTimelineCanvasHeight(trackCount: number): number {
@@ -373,7 +389,7 @@ export function resolveTimelineAssetDrop(
clientX: number,
clientY: number,
): { start: number; track: number } {
- const x = clientX - input.rectLeft + input.scrollLeft - GUTTER;
+ const x = clientX - input.rectLeft + input.scrollLeft - GUTTER - TRACKS_LEFT_PAD;
const contentY = clientY - input.rectTop + input.scrollTop;
const start = Math.max(
0,
diff --git a/packages/studio/src/player/components/timelineMarquee.test.ts b/packages/studio/src/player/components/timelineMarquee.test.ts
index b185841b23..732076edb9 100644
--- a/packages/studio/src/player/components/timelineMarquee.test.ts
+++ b/packages/studio/src/player/components/timelineMarquee.test.ts
@@ -7,7 +7,17 @@ import {
getTimelineClipRect,
computeMarqueeSelection,
} from "./timelineMarquee";
-import { GUTTER, TRACK_H, RULER_H, CLIP_Y, getTimelineRowTop } from "./timelineLayout";
+import {
+ GUTTER,
+ TRACK_H,
+ RULER_H,
+ CLIP_Y,
+ TRACKS_LEFT_PAD,
+ getTimelineRowTop,
+} from "./timelineLayout";
+
+// Canvas-space time origin: right edge of the sticky gutter + the left pad.
+const ORIGIN = GUTTER + TRACKS_LEFT_PAD;
describe("isTimelineRulerPress", () => {
const rectTop = 500; // scroll container's viewport top
@@ -86,7 +96,7 @@ describe("getTimelineClipRect", () => {
it("maps start/duration to x via pps and the track row to y via the shared row→y helper", () => {
const rect = getTimelineClipRect({ start: 2, duration: 3, track: 2 }, trackOrder, 100);
expect(rect).toEqual({
- left: GUTTER + 200,
+ left: ORIGIN + 200,
top: getTimelineRowTop(1) + CLIP_Y,
width: 300,
height: TRACK_H - CLIP_Y * 2,
@@ -96,7 +106,7 @@ describe("getTimelineClipRect", () => {
it("places the first visible track below the ruler + top breathing pad", () => {
const rect = getTimelineClipRect({ start: 0, duration: 1, track: 0 }, trackOrder, 50);
expect(rect?.top).toBe(getTimelineRowTop(0) + CLIP_Y);
- expect(rect?.left).toBe(GUTTER);
+ expect(rect?.left).toBe(ORIGIN);
});
it("uses the row index in trackOrder, not the raw track number", () => {
@@ -129,26 +139,26 @@ describe("computeMarqueeSelection", () => {
const row1Top = getTimelineRowTop(1) + CLIP_Y;
it("selects only the clips the marquee rect intersects", () => {
- const marquee = { left: GUTTER, top: row0Top, width: 50, height: 10 };
+ const marquee = { left: ORIGIN, top: row0Top, width: 50, height: 10 };
const { ids, primaryId } = computeMarqueeSelection({ clips, trackOrder, pps, marquee });
expect(ids).toEqual(new Set(["a"]));
expect(primaryId).toBe("a");
});
it("selects across tracks when the rect spans multiple rows", () => {
- const marquee = { left: GUTTER, top: row0Top, width: 60, height: row1Top - row0Top + 5 };
+ const marquee = { left: ORIGIN, top: row0Top, width: 60, height: row1Top - row0Top + 5 };
const { ids } = computeMarqueeSelection({ clips, trackOrder, pps, marquee });
expect(ids).toEqual(new Set(["a", "c"]));
});
it("excludes clips outside the rect horizontally", () => {
- const marquee = { left: GUTTER + 140, top: row0Top, width: 50, height: 10 };
+ const marquee = { left: ORIGIN + 140, top: row0Top, width: 50, height: 10 };
const { ids } = computeMarqueeSelection({ clips, trackOrder, pps, marquee });
expect(ids).toEqual(new Set());
});
it("returns null primaryId and keeps the base when nothing is hit (additive)", () => {
- const marquee = { left: GUTTER + 140, top: row0Top, width: 50, height: 10 };
+ const marquee = { left: ORIGIN + 140, top: row0Top, width: 50, height: 10 };
const { ids, primaryId } = computeMarqueeSelection({
clips,
trackOrder,
@@ -161,7 +171,7 @@ describe("computeMarqueeSelection", () => {
});
it("unions additive base selection with new hits; primary comes from the marquee", () => {
- const marquee = { left: GUTTER, top: row1Top, width: 100, height: 10 };
+ const marquee = { left: ORIGIN, top: row1Top, width: 100, height: 10 };
const { ids, primaryId } = computeMarqueeSelection({
clips,
trackOrder,
@@ -174,8 +184,8 @@ describe("computeMarqueeSelection", () => {
});
it("shrinking the rect live drops clips it no longer covers", () => {
- const wide = { left: GUTTER, top: row0Top, width: 320, height: 10 };
- const narrow = { left: GUTTER, top: row0Top, width: 80, height: 10 };
+ const wide = { left: ORIGIN, top: row0Top, width: 320, height: 10 };
+ const narrow = { left: ORIGIN, top: row0Top, width: 80, height: 10 };
expect(computeMarqueeSelection({ clips, trackOrder, pps, marquee: wide }).ids).toEqual(
new Set(["a", "b"]),
);
diff --git a/packages/studio/src/player/components/timelineMarquee.ts b/packages/studio/src/player/components/timelineMarquee.ts
index 718dd86594..21c18913d1 100644
--- a/packages/studio/src/player/components/timelineMarquee.ts
+++ b/packages/studio/src/player/components/timelineMarquee.ts
@@ -1,4 +1,11 @@
-import { GUTTER, TRACK_H, RULER_H, CLIP_Y, getTimelineRowTop } from "./timelineLayout";
+import {
+ GUTTER,
+ TRACK_H,
+ RULER_H,
+ CLIP_Y,
+ TRACKS_LEFT_PAD,
+ getTimelineRowTop,
+} from "./timelineLayout";
import { rectsOverlap, type Rect } from "../../utils/marqueeGeometry";
/** Pointer must travel at least this far (either axis) before a pointerdown on
@@ -73,7 +80,7 @@ export function getTimelineClipRect(
const row = trackOrder.indexOf(clip.track);
if (row < 0 || !Number.isFinite(pps) || pps <= 0) return null;
return {
- left: GUTTER + clip.start * pps,
+ left: GUTTER + TRACKS_LEFT_PAD + clip.start * pps,
top: getTimelineRowTop(row) + CLIP_Y,
width: Math.max(clip.duration * pps, MIN_CLIP_W),
height: TRACK_H - CLIP_Y * 2,
diff --git a/packages/studio/src/player/components/timelineStackingSync.test.ts b/packages/studio/src/player/components/timelineStackingSync.test.ts
index 599bc35026..a7d1e81e74 100644
--- a/packages/studio/src/player/components/timelineStackingSync.test.ts
+++ b/packages/studio/src/player/components/timelineStackingSync.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, it } from "vitest";
-import { computeStackingPatches, laneIsAbove, type StackingElement } from "./timelineStackingSync";
+import {
+ computeStackingPatches,
+ laneIsAbove,
+ samePaintScope,
+ type StackingElement,
+} from "./timelineStackingSync";
function el(
key: string,
@@ -20,6 +25,42 @@ function patchMap(elements: StackingElement[], edited: string[]): Record<string,
}
describe("stacking-context partitioning", () => {
+ it("uses source file and normalized stacking context as the canonical paint scope", () => {
+ expect(samePaintScope({}, { stackingContextId: null })).toBe(true);
+ expect(samePaintScope({}, { sourceFile: "index.html" })).toBe(false);
+ expect(
+ samePaintScope(
+ { sourceFile: "scene.html", stackingContextId: "card" },
+ { sourceFile: "scene.html", stackingContextId: "modal" },
+ ),
+ ).toBe(false);
+ });
+
+ it("never compares or patches across source files in the root context", () => {
+ const root: StackingElement = {
+ key: "root",
+ track: 0,
+ start: 0,
+ duration: 5,
+ zIndex: 1,
+ isAudio: false,
+ sourceFile: "index.html",
+ stackingContextId: null,
+ };
+ const scene: StackingElement = {
+ key: "scene",
+ track: 1,
+ start: 0,
+ duration: 5,
+ zIndex: 10,
+ isAudio: false,
+ sourceFile: "scenes/scene.html",
+ stackingContextId: null,
+ };
+
+ expect(patchMap([root, scene], ["root"])).toEqual({});
+ });
+
it("never compares or patches across stacking contexts", () => {
// X lives in sub-comp context "scene-1" with a high leaf z; Y is a root clip
// with a lower leaf z, overlapping in time. Their leaf z values are NOT
diff --git a/packages/studio/src/player/components/timelineStackingSync.ts b/packages/studio/src/player/components/timelineStackingSync.ts
index e86bfe49af..1243e1f3b6 100644
--- a/packages/studio/src/player/components/timelineStackingSync.ts
+++ b/packages/studio/src/player/components/timelineStackingSync.ts
@@ -43,6 +43,8 @@ export interface StackingElement {
zIndex: number;
/** Audio clips have no visual stacking and are excluded from the computation. */
isAudio: boolean;
+ /** Source document. Leaf z-indexes are comparable only inside this file. */
+ sourceFile?: string;
/**
* CSS stacking context the clip's node lives in (TimelineElement.stackingContextId).
* Leaf z-indexes are only comparable WITHIN one context — across contexts the
@@ -70,12 +72,20 @@ export interface StackingPatch {
const EPS = 1e-6;
/**
- * Canonical stacking-context key: null/undefined both mean the root context.
- * The ONLY place the normalization lives — context partitioning, membership
- * checks, and pairwise equality must all go through it.
+ * Canonical paint-scope key: leaf z-indexes are comparable only within the same
+ * source document and CSS stacking context. The ONLY place this normalization
+ * lives — partitioning, membership checks, and pairwise equality all use it.
*/
-const contextKey = (el: { stackingContextId?: string | null }): string | null =>
- el.stackingContextId ?? null;
+const paintScopeKey = (el: { sourceFile?: string; stackingContextId?: string | null }): string =>
+ JSON.stringify([el.sourceFile ?? null, el.stackingContextId ?? null]);
+
+/** Canonical paint-scope equality for stacking sync and its inverse mirror. */
+export function samePaintScope(
+ a: { sourceFile?: string; stackingContextId?: string | null },
+ b: { sourceFile?: string; stackingContextId?: string | null },
+): boolean {
+ return paintScopeKey(a) === paintScopeKey(b);
+}
/**
* Two clips overlap in time when their half-open [start, end) intervals intersect.
@@ -86,7 +96,10 @@ const contextKey = (el: { stackingContextId?: string | null }): string | null =>
* epsilon guards against float fuzz (e.g. 5.0000001 vs 5) spuriously overlapping two
* abutting clips and shuffling lanes. The two are intended to differ, not align.
*/
-function overlapsInTime(a: StackingElement, b: StackingElement): boolean {
+function overlapsInTime(
+ a: Pick<StackingElement, "start" | "duration">,
+ b: Pick<StackingElement, "start" | "duration">,
+): boolean {
return a.start < b.start + b.duration - EPS && b.start < a.start + a.duration - EPS;
}
@@ -114,9 +127,13 @@ interface MutZ extends StackingElement {
* Does `a` currently paint ON TOP of `b`? Higher z wins; equal z breaks by DOM
* order (later in DOM paints on top). When either domIndex is absent, equal z is
* treated as "not strictly above" (ambiguous) — callers should supply domIndex to
- * disambiguate (see StackingElement.domIndex). Operates on resolved (`MutZ`) clips.
+ * disambiguate (see StackingElement.domIndex). Exported (like laneIsAbove) as the
+ * ONE paint-order predicate so every consumer agrees on what "paints above" means.
*/
-function paintsAbove(a: MutZ, b: MutZ): boolean {
+function paintsAbove(
+ a: Pick<StackingElement, "zIndex" | "domIndex">,
+ b: Pick<StackingElement, "zIndex" | "domIndex">,
+): boolean {
if (a.zIndex !== b.zIndex) return a.zIndex > b.zIndex;
if (a.domIndex != null && b.domIndex != null) return a.domIndex > b.domIndex;
return false;
@@ -301,12 +318,11 @@ export function computeStackingPatches(
// excluded outright (item 13).
const allResolved = elements.filter((e) => Number.isFinite(e.zIndex));
- // Leaf z is only meaningful within ONE stacking context: across contexts the
- // ancestor contexts' z decides paint order, so comparing (or patching) leaf
- // values across contexts is nonsense. Restrict the computation to the edited
- // clips' own context(s); cross-context lane relations are out of scope.
- const editedContexts = new Set(allResolved.filter((e) => editedSet.has(e.key)).map(contextKey));
- const resolved = allResolved.filter((e) => editedContexts.has(contextKey(e)));
+ // Leaf z is only meaningful within ONE source document and stacking context:
+ // across either boundary the ancestor composition/context decides paint order.
+ // Restrict the computation to the edited clips' own paint scope(s).
+ const editedScopes = new Set(allResolved.filter((e) => editedSet.has(e.key)).map(paintScopeKey));
+ const resolved = allResolved.filter((e) => editedScopes.has(paintScopeKey(e)));
// Mutable z snapshot so edits + cascaded bumps see each other's applied z.
const byKey = new Map<string, MutZ>(resolved.map((e) => [e.key, { ...e }]));
@@ -326,10 +342,9 @@ export function computeStackingPatches(
// The full live set, so the transitive cascade can reach clips that overlap a
// LIFTED neighbour without overlapping the edited clip itself (#2198).
const all = [...byKey.values()];
- const sameContext = (a: MutZ, b: MutZ) => contextKey(a) === contextKey(b);
const overlappersOf = (clip: MutZ): MutZ[] =>
all.filter(
- (o) => o.key !== clip.key && !o.isAudio && sameContext(clip, o) && overlapsInTime(clip, o),
+ (o) => o.key !== clip.key && !o.isAudio && samePaintScope(clip, o) && overlapsInTime(clip, o),
);
for (const clip of edited) {
diff --git a/packages/studio/src/player/components/timelineZMirror.test.ts b/packages/studio/src/player/components/timelineZMirror.test.ts
new file mode 100644
index 0000000000..68fe1d6d60
--- /dev/null
+++ b/packages/studio/src/player/components/timelineZMirror.test.ts
@@ -0,0 +1,667 @@
+import { describe, expect, it } from "vitest";
+import type { TimelineElement } from "../store/playerStore";
+import {
+ resolveRepositionLaneMove,
+ resolveZMirrorLaneMove,
+ type ZMirrorInput,
+} from "./timelineZMirror";
+
+function el(
+ id: string,
+ track: number,
+ start: number,
+ duration: number,
+ extra: Partial<TimelineElement> = {},
+): TimelineElement {
+ return { id, key: id, tag: "video", start, duration, track, domId: id, ...extra };
+}
+
+function audio(id: string, track: number, start: number, duration: number): TimelineElement {
+ return el(id, track, start, duration, { tag: "audio" });
+}
+
+function resolve(
+ action: ZMirrorInput["action"],
+ element: TimelineElement,
+ elements: TimelineElement[],
+ crossedKey?: string | null,
+) {
+ return resolveZMirrorLaneMove({ action, element, elements, crossedKey });
+}
+
+// Target on TOP lane 0; b/c fully occupy the two lanes below over t's span.
+const stackBelow = () => {
+ const t = el("t", 0, 0, 10);
+ const b = el("b", 1, 0, 10);
+ const c = el("c", 2, 0, 10);
+ return { t, elements: [t, b, c] };
+};
+
+// Sparse file: authored tracks 3/5/7 displayed as lanes 0/1/2 (a free over t's span).
+const sparseAuthored = () => {
+ const a = el("a", 0, 20, 5, { authoredTrack: 3 });
+ const b = el("b", 1, 0, 10, { authoredTrack: 5 });
+ const t = el("t", 2, 0, 10, { authoredTrack: 7 });
+ return { t, elements: [a, b, t] };
+};
+
+describe("resolveZMirrorLaneMove — bring-forward / send-backward", () => {
+ // Stack: a on lane 0, b on lane 1, target on lane 2 — all overlapping in time.
+ const stack = () => {
+ const a = el("a", 0, 0, 10);
+ const b = el("b", 1, 0, 10);
+ const t = el("t", 2, 0, 10);
+ return { a, b, t, elements: [a, b, t] };
+ };
+
+ it("bring-forward with crossedKey lands on the closest free lane above the neighbor", () => {
+ // Free lane 0 exists above the crossed neighbor's lane... make lane 0 free by
+ // shifting a out of the span.
+ const a = el("a", 0, 20, 5); // lane 0 free over t's span
+ const b = el("b", 1, 0, 10);
+ const t = el("t", 2, 0, 10);
+ expect(resolve("bring-forward", t, [a, b, t], "b")).toEqual({
+ kind: "move",
+ displayTrack: 0,
+ persistTrack: 0,
+ });
+ });
+
+ it("bring-forward with crossedKey inserts above the neighbor when no lane is free", () => {
+ const { t, elements } = stack();
+ // Lanes 0 and 1 both occupied over t's span → new lane at the boundary
+ // ABOVE the crossed neighbor (row of lane 1 in the ascending order).
+ expect(resolve("bring-forward", t, elements, "b")).toEqual({ kind: "insert", insertRow: 1 });
+ });
+
+ it("bring-forward without crossedKey uses the closest overlapping neighbor above", () => {
+ const { t, elements } = stack();
+ // Closest overlapping neighbor above lane 2 is b (lane 1); lanes 0/1 are
+ // occupied → insert above b, same as the crossedKey case.
+ expect(resolve("bring-forward", t, elements)).toEqual({ kind: "insert", insertRow: 1 });
+ });
+
+ it("bring-forward with an unknown crossedKey falls back to the temporal neighbor", () => {
+ const { t, elements } = stack();
+ expect(resolve("bring-forward", t, elements, "nope")).toEqual({
+ kind: "insert",
+ insertRow: 1,
+ });
+ });
+
+ it("bring-forward returns null when nothing overlaps above and no crossedKey", () => {
+ const a = el("a", 0, 20, 5); // above but NOT overlapping in time
+ const t = el("t", 1, 0, 10);
+ expect(resolve("bring-forward", t, [a, t])).toBeNull();
+ });
+
+ it("send-backward lands on the closest free lane below the neighbor", () => {
+ const t = el("t", 0, 0, 10);
+ const b = el("b", 1, 0, 10);
+ const c = el("c", 2, 20, 5); // lane 2 free over t's span
+ expect(resolve("send-backward", t, [t, b, c], "b")).toEqual({
+ kind: "move",
+ displayTrack: 2,
+ persistTrack: 2,
+ });
+ });
+
+ it("send-backward inserts below the neighbor when no lane below is free", () => {
+ const { t, elements } = stackBelow();
+ // Boundary below b's lane (row 1 + 1 = 2).
+ expect(resolve("send-backward", t, elements, "b")).toEqual({ kind: "insert", insertRow: 2 });
+ });
+
+ it("send-backward returns null when nothing overlaps below and no crossedKey", () => {
+ const t = el("t", 0, 0, 10);
+ const b = el("b", 1, 20, 5);
+ expect(resolve("send-backward", t, [t, b])).toBeNull();
+ });
+
+ it("BOUNDED: never steps past the next overlapping element to a farther free lane", () => {
+ // Above neighbor b (lane 2): lane 1 holds x — the NEXT temporally-overlapping
+ // same-file element in the direction — and lane 0 is free. A single forward
+ // step crosses ONE element, so the free lane 0 beyond x is out of reach:
+ // insert immediately above b instead (row of lane 2 in the ascending order).
+ const a = el("a", 0, 30, 5); // lane 0 free over t's span — but beyond the bound
+ const x = el("x", 1, 5, 10); // overlaps t → the exclusive bound
+ const b = el("b", 2, 0, 10);
+ const t = el("t", 3, 0, 10);
+ expect(resolve("bring-forward", t, [a, x, b, t], "b")).toEqual({
+ kind: "insert",
+ insertRow: 2,
+ });
+ });
+
+ it("OPEN SPACE: with no second overlapping element, skips an occupied lane to the next free one", () => {
+ // Lane 1's occupant is a FOREIGN-file clip: it occupies the lane (freeness is
+ // file-agnostic) but is not in the same stacking context, so it does not
+ // bound the step — the search continues to free lane 0, as before.
+ const a = el("a", 0, 30, 5); // lane 0 free over t's span
+ const x = el("x", 1, 5, 10, { sourceFile: "sub.html" });
+ const b = el("b", 2, 0, 10);
+ const t = el("t", 3, 0, 10);
+ expect(resolve("bring-forward", t, [a, x, b, t], "b")).toEqual({
+ kind: "move",
+ displayTrack: 0,
+ persistTrack: 0,
+ });
+ });
+
+ it("returns null when the closest free lane is the clip's own lane (z/track divergence)", () => {
+ // Crossed neighbor sits BELOW the clip in lane space (diverged z): searching
+ // up from lane 2 finds lane 1 free — the clip's own lane → already in place.
+ const t = el("t", 1, 0, 10);
+ const b = el("b", 2, 0, 10);
+ expect(resolve("bring-forward", t, [t, b], "b")).toBeNull();
+ });
+});
+
+describe("resolveZMirrorLaneMove — one-element step bound (forward/backward)", () => {
+ // Three stacked back-to-back clips (lanes 0/1/2, all overlapping) plus a free
+ // lane BEYOND the far element — the lane the old resolver would overshoot to.
+ const threeStackedWithFarFree = () => {
+ const a = el("a", 0, 0, 10);
+ const b = el("b", 1, 0, 10);
+ const c = el("c", 2, 0, 10);
+ const d = el("d", 3, 20, 5); // lane 3 free over the span — beyond c
+ return { a, b, c, d, elements: [a, b, c, d] };
+ };
+
+ it("send-backward from the top inserts between elements 1 and 2 — not past element 2", () => {
+ const { a, elements } = threeStackedWithFarFree();
+ // Reference = b (lane 1); next overlap below = c (lane 2) bounds the search;
+ // no free lane strictly between → insert at the b/c boundary (row 2), NOT
+ // the farther free lane 3.
+ expect(resolve("send-backward", a, elements, "b")).toEqual({ kind: "insert", insertRow: 2 });
+ });
+
+ it("bring-forward from the bottom inserts between elements 1 and 2 (symmetric)", () => {
+ const d = el("d", 0, 20, 5); // lane 0 free over the span — beyond a
+ const a = el("a", 1, 0, 10);
+ const b = el("b", 2, 0, 10);
+ const t = el("t", 3, 0, 10);
+ // Reference = b (lane 2); next overlap above = a (lane 1) bounds the search;
+ // no free lane strictly between → insert at the a/b boundary (row 2), NOT
+ // the farther free lane 0.
+ expect(resolve("bring-forward", t, [d, a, b, t], "b")).toEqual({
+ kind: "insert",
+ insertRow: 2,
+ });
+ });
+
+ it("takes a free lane strictly between the reference and the next overlap", () => {
+ const a = el("a", 0, 0, 10); // second element — the exclusive bound
+ const gap = el("gap", 1, 20, 5); // lane 1 free over the span, inside the interval
+ const b = el("b", 2, 0, 10); // crossed reference
+ const t = el("t", 3, 0, 10);
+ expect(resolve("bring-forward", t, [a, gap, b, t], "b")).toEqual({
+ kind: "move",
+ displayTrack: 1,
+ persistTrack: 1,
+ });
+ });
+
+ it("of several free lanes in the interval, takes the one closest to the reference", () => {
+ const a = el("a", 0, 0, 10); // bound
+ const g1 = el("g1", 1, 20, 5); // free, farther from reference
+ const g2 = el("g2", 2, 20, 5); // free, closest to reference
+ const b = el("b", 3, 0, 10); // crossed reference
+ const t = el("t", 4, 0, 10);
+ expect(resolve("bring-forward", t, [a, g1, g2, b, t], "b")).toEqual({
+ kind: "move",
+ displayTrack: 2,
+ persistTrack: 2,
+ });
+ });
+
+ it("no second overlapping element beyond the reference → the zone edge bounds (as today)", () => {
+ const { t, elements } = stackBelow();
+ // Only c overlaps below the reference b... remove c's overlap: reference is
+ // then the ONLY overlap below; the search runs to the zone edge and takes
+ // the free lane beyond the neighbor.
+ const spread = elements.map((e) => (e.id === "c" ? { ...e, start: 20 } : e));
+ expect(resolve("send-backward", t, spread, "b")).toEqual({
+ kind: "move",
+ displayTrack: 2,
+ persistTrack: 2,
+ });
+ });
+
+ it("bring-to-front is NOT bounded: still moves past the whole overlap set", () => {
+ const { t, elements } = (() => {
+ const free = el("free", 0, 20, 5); // free lane beyond the topmost overlap
+ const a = el("a", 1, 0, 10);
+ const b = el("b", 2, 0, 10);
+ const t = el("t", 3, 0, 10);
+ return { t, elements: [free, a, b, t] };
+ })();
+ expect(resolve("bring-to-front", t, elements)).toEqual({
+ kind: "move",
+ displayTrack: 0,
+ persistTrack: 0,
+ });
+ });
+});
+
+describe("resolveZMirrorLaneMove — bring-to-front / send-to-back", () => {
+ it("bring-to-front moves above the topmost temporally-overlapping clip", () => {
+ const a = el("a", 0, 20, 5); // lane 0 free over t's span
+ const b = el("b", 1, 0, 10); // topmost overlap
+ const c = el("c", 2, 0, 10);
+ const t = el("t", 3, 0, 10);
+ expect(resolve("bring-to-front", t, [a, b, c, t])).toEqual({
+ kind: "move",
+ displayTrack: 0,
+ persistTrack: 0,
+ });
+ });
+
+ it("bring-to-front inserts above the topmost overlap when no lane is free", () => {
+ const b = el("b", 0, 0, 10);
+ const c = el("c", 1, 0, 10);
+ const t = el("t", 2, 0, 10);
+ expect(resolve("bring-to-front", t, [b, c, t])).toEqual({ kind: "insert", insertRow: 0 });
+ });
+
+ it("bring-to-front is null when already topmost among overlaps (temporal scope)", () => {
+ // A clip exists on a higher lane but does NOT overlap in time — with the
+ // default temporal-overlap scope the target is already at the front.
+ const a = el("a", 0, 20, 5);
+ const t = el("t", 1, 0, 10);
+ const c = el("c", 2, 0, 10);
+ expect(resolve("bring-to-front", t, [a, t, c])).toBeNull();
+ });
+
+ it("send-to-back moves below the bottommost temporally-overlapping clip", () => {
+ const t = el("t", 0, 0, 10);
+ const b = el("b", 1, 0, 10); // bottommost overlap
+ const c = el("c", 2, 20, 5); // lane 2 free over t's span
+ expect(resolve("send-to-back", t, [t, b, c])).toEqual({
+ kind: "move",
+ displayTrack: 2,
+ persistTrack: 2,
+ });
+ });
+
+ it("send-to-back inserts below the bottommost overlap when no lane is free", () => {
+ const { t, elements } = stackBelow();
+ expect(resolve("send-to-back", t, elements)).toEqual({ kind: "insert", insertRow: 3 });
+ });
+
+ it("send-to-back is null when already bottommost among overlaps", () => {
+ const t = el("t", 1, 0, 10);
+ const a = el("a", 0, 0, 10);
+ expect(resolve("send-to-back", t, [a, t])).toBeNull();
+ });
+
+ it("returns null when nothing overlaps at all", () => {
+ const t = el("t", 0, 0, 10);
+ const a = el("a", 1, 20, 5);
+ for (const action of ["bring-to-front", "send-to-back"] as const) {
+ expect(resolve(action, t, [t, a])).toBeNull();
+ }
+ });
+});
+
+describe("resolveZMirrorLaneMove — span freeness", () => {
+ it("a lane free at the clip's start but occupied later in the span is NOT free", () => {
+ const t = el("t", 2, 0, 10);
+ const b = el("b", 1, 0, 10); // crossed neighbor
+ // Lane 0: nothing at t=0, but occupied over [6, 9) — inside t's span.
+ const late = el("late", 0, 6, 3);
+ expect(resolve("bring-forward", t, [late, b, t], "b")).toEqual({
+ kind: "insert",
+ insertRow: 1,
+ });
+ });
+
+ it("half-open spans: a clip starting exactly at the moved clip's end does not occupy", () => {
+ const t = el("t", 2, 0, 10);
+ const b = el("b", 1, 0, 10);
+ const adjacent = el("adj", 0, 10, 5); // [10, 15) touches [0, 10) but no overlap
+ expect(resolve("bring-forward", t, [adjacent, b, t], "b")).toEqual({
+ kind: "move",
+ displayTrack: 0,
+ persistTrack: 0,
+ });
+ });
+
+ it("freeness is file-agnostic: an other-file clip occupies the lane", () => {
+ const t = el("t", 2, 0, 10);
+ const b = el("b", 1, 0, 10);
+ const foreign = el("f", 0, 0, 10, { sourceFile: "sub.html" });
+ expect(resolve("bring-forward", t, [foreign, b, t], "b")).toEqual({
+ kind: "insert",
+ insertRow: 1,
+ });
+ });
+});
+
+describe("resolveZMirrorLaneMove — zone boundary (audio untouched)", () => {
+ // Visual lanes 0-1, audio lanes 2-3.
+ const zoned = () => {
+ const t = el("t", 0, 0, 10);
+ const b = el("b", 1, 0, 10);
+ const m = audio("music", 2, 0, 30);
+ const vo = audio("vo", 3, 0, 30);
+ return { t, b, m, vo, elements: [t, b, m, vo] };
+ };
+
+ it("send-backward never lands on an audio lane — inserts at the zone boundary", () => {
+ const { t, elements } = zoned();
+ // Lane 2 (audio) is out of bounds even though "below"; boundary row 2 sits
+ // between the bottom visual lane and the first audio lane — a visual insert.
+ expect(resolve("send-backward", t, elements, "b")).toEqual({ kind: "insert", insertRow: 2 });
+ });
+
+ it("send-to-back stops at the visual zone edge", () => {
+ const { t, elements } = zoned();
+ expect(resolve("send-to-back", t, elements)).toEqual({ kind: "insert", insertRow: 2 });
+ });
+
+ it("audio clips never mirror (returns null)", () => {
+ const { m, elements } = zoned();
+ for (const action of [
+ "bring-to-front",
+ "bring-forward",
+ "send-backward",
+ "send-to-back",
+ ] as const) {
+ expect(resolve(action, m, elements)).toBeNull();
+ }
+ });
+
+ it("audio clips do not count as overlap references for visual clips", () => {
+ // Only audio below the target → send-backward has no visual neighbor → null.
+ const t = el("t", 0, 0, 10);
+ const m = audio("music", 1, 0, 30);
+ expect(resolve("send-backward", t, [t, m])).toBeNull();
+ expect(resolve("send-to-back", t, [t, m])).toBeNull();
+ });
+});
+
+describe("resolveZMirrorLaneMove — authored (persist) space", () => {
+ it("persistTrack takes the target lane occupant's authoredTrack, not the display lane", () => {
+ // Occupant of the free-over-span target lane 0 (authored 3) anchors the persist value.
+ const { t, elements } = sparseAuthored();
+ expect(resolve("bring-forward", t, elements, "b")).toEqual({
+ kind: "move",
+ displayTrack: 0,
+ persistTrack: 3,
+ });
+ });
+
+ it("falls back to nearest-same-file lane offset when the target lane has no same-file occupant", () => {
+ // The moved clip is an expanded sub-comp child; the target lane's only
+ // occupant belongs to the host file, so the persist value offsets from the
+ // nearest same-file lane instead (authored 4 at lane 1 → lane 0 = 3).
+ const host = el("h", 0, 20, 5); // host-file clip on the target lane (not overlapping)
+ const sib = el("s", 1, 0, 10, { sourceFile: "sub.html", authoredTrack: 4 });
+ const t = el("t", 2, 0, 10, { sourceFile: "sub.html", authoredTrack: 5 });
+ expect(resolve("bring-forward", t, [host, sib, t], "s")).toEqual({
+ kind: "move",
+ displayTrack: 0,
+ persistTrack: 3,
+ });
+ });
+});
+
+describe("resolveZMirrorLaneMove — stacking-context (source file) scoping", () => {
+ it("other-file clips are not overlap references (extremes computed per file)", () => {
+ // A host clip overlaps above the sub-comp child, but the child's own file
+ // has nothing above it → bring-to-front is null (already at ITS front).
+ const host = el("h", 0, 0, 10);
+ const t = el("t", 1, 0, 10, { sourceFile: "sub.html" });
+ expect(resolve("bring-to-front", t, [host, t])).toBeNull();
+ });
+
+ it("same-file overlaps in an expanded sub-comp resolve within the child's lanes", () => {
+ const host = el("h", 0, 0, 10);
+ const sib = el("s", 1, 0, 10, { sourceFile: "sub.html", authoredTrack: 0 });
+ const t = el("t", 2, 0, 10, { sourceFile: "sub.html", authoredTrack: 1 });
+ // Topmost same-file overlap is sib (lane 1); lane 0 is occupied by the host
+ // over the span (freeness is file-agnostic) → insert above sib's lane.
+ expect(resolve("bring-to-front", t, [host, sib, t])).toEqual({
+ kind: "insert",
+ insertRow: 1,
+ });
+ });
+});
+
+describe("resolveZMirrorLaneMove — degenerate inputs and determinism", () => {
+ it("zero-duration element returns null", () => {
+ const t = el("t", 1, 0, 0);
+ const a = el("a", 0, 0, 10);
+ expect(resolve("bring-to-front", t, [a, t])).toBeNull();
+ });
+
+ it("single-clip timeline returns null for every action", () => {
+ const t = el("t", 0, 0, 10);
+ for (const action of [
+ "bring-to-front",
+ "bring-forward",
+ "send-backward",
+ "send-to-back",
+ ] as const) {
+ expect(resolve(action, t, [t])).toBeNull();
+ }
+ });
+
+ it("identical inputs produce identical outputs (deterministic, input untouched)", () => {
+ const first = sparseAuthored();
+ const snapshot = structuredClone(first.elements);
+ const r1 = resolve("bring-forward", first.t, first.elements, "b");
+ const r2 = resolve("bring-forward", first.t, first.elements, "b");
+ const fresh = sparseAuthored();
+ const r3 = resolve("bring-forward", fresh.t, fresh.elements, "b");
+ expect(r1).toEqual(r2);
+ expect(r1).toEqual(r3);
+ expect(first.elements).toEqual(snapshot); // pure — never mutates its input
+ });
+});
+
+describe("resolveRepositionLaneMove (Layers-panel equal jump)", () => {
+ // Bottom→top render order helper: keys as the panel's reversed order.
+ const reposition = (
+ element: TimelineElement,
+ elements: TimelineElement[],
+ desiredOrderKeys: (string | null)[],
+ ) => resolveRepositionLaneMove({ element, elements, desiredOrderKeys });
+
+ // Three stacked clips on lanes 0/1/2, all overlapping. Render order matches
+ // lanes today: bottom→top = c(2), b(1), t(0)... target starts on lane 2.
+ const stack3 = () => {
+ const a = el("a", 0, 0, 10);
+ const b = el("b", 1, 0, 10);
+ const t = el("t", 2, 0, 10);
+ return { a, b, t, elements: [a, b, t] };
+ };
+
+ it("multi-step jump to the top inserts a new lane above the new below-neighbor", () => {
+ const { t, elements } = stack3();
+ // t dragged to the TOP of the panel: bottom→top = [b, a, t].
+ // New below-neighbor is a (lane 0); lanes above are occupied/none free →
+ // insert at a's boundary (order.indexOf(0) = 0).
+ expect(reposition(t, elements, ["b", "a", "t"])).toEqual({ kind: "insert", insertRow: 0 });
+ });
+
+ it("multi-step jump lands on a free lane between the new neighbors", () => {
+ // Lanes 0,1,2,3: a(0), b(1) short-lived, c(2), t(3). Lane 1 is free over
+ // t's span. t dragged between a and c in paint order: above-neighbor a
+ // (lane 0), below-neighbor c (lane 2) → free lane 1, strictly between.
+ const a = el("a", 0, 0, 10);
+ const b = el("b", 1, 20, 5);
+ const c = el("c", 2, 0, 10);
+ const t = el("t", 3, 0, 10);
+ // bottom→top: c (bottom), t (middle), a (top); b not in the sibling set.
+ expect(reposition(t, [a, b, c, t], ["c", "t", "a"])).toEqual({
+ kind: "move",
+ displayTrack: 1,
+ persistTrack: 1,
+ });
+ });
+
+ it("drop toward the bottom lands on a free lane below the new above-neighbor", () => {
+ // Lanes: t(0), b(1), c(2) short-lived → lane 2 free over t's span.
+ const t = el("t", 0, 0, 10);
+ const b = el("b", 1, 0, 10);
+ const c = el("c", 2, 20, 5);
+ // t dragged below b: bottom→top = [t, b]. Above-neighbor b (lane 1) →
+ // closest free lane below it is lane 2.
+ expect(reposition(t, [t, b, c], ["t", "b"])).toEqual({
+ kind: "move",
+ displayTrack: 2,
+ persistTrack: 2,
+ });
+ });
+
+ it("drop below the bottom clip inserts a new bottom lane when none is free", () => {
+ const x = el("x", 0, 0, 10);
+ const y = el("y", 1, 0, 10);
+ const z = el("z", 2, 0, 10);
+ // x (top lane 0) dragged to the bottom of the panel: bottom→top = [x, z, y].
+ // Above-neighbor = z (lane 2); no free lane below it → insert below z
+ // (order.indexOf(2) + 1 = 3).
+ expect(reposition(x, [x, y, z], ["x", "z", "y"])).toEqual({ kind: "insert", insertRow: 3 });
+ });
+
+ it("skips non-clip siblings (null keys) when resolving neighbors", () => {
+ // t on TOP lane 0, a below on lane 1. t dragged below a in paint order,
+ // with two decorations (null keys) interleaved: the resolver must skip the
+ // nulls and find a (lane 1) as the above-neighbor → no free lane below it
+ // → insert below a (order.indexOf(1) + 1 = 2).
+ const t = el("t", 0, 0, 10);
+ const a = el("a", 1, 0, 10);
+ expect(reposition(t, [t, a], [null, "t", null, "a"])).toEqual({
+ kind: "insert",
+ insertRow: 2,
+ });
+ });
+
+ it("returns null when the drop leaves the clip where it already sits", () => {
+ const a = el("a", 0, 20, 5); // lane 0 free over t's span but t stays put
+ const b = el("b", 1, 0, 10);
+ const t = el("t", 2, 0, 10);
+ // bottom→top = [t, b] — t stays below b; nearest above-neighbor b (lane 1),
+ // scanning down from lane 1 finds t's own lane 2 first.
+ expect(reposition(t, [a, b, t], ["t", "b"])).toBeNull();
+ });
+
+ it("returns null for audio, zero-duration, decoration-only sets, and unknown self", () => {
+ const t = el("t", 1, 0, 10);
+ const a = el("a", 0, 0, 10);
+ expect(reposition(audio("s", 3, 0, 10), [t, a], ["s", "t"])).toBeNull();
+ expect(reposition(el("z0", 1, 0, 0), [t, a], ["z0", "t"])).toBeNull();
+ expect(reposition(t, [t, a], [null, "t", null])).toBeNull(); // no clip neighbor
+ expect(reposition(t, [t, a], ["a"])).toBeNull(); // self missing from order
+ });
+
+ it("audio lanes are never targeted (insert stays within the visual zone)", () => {
+ const a = el("a", 0, 0, 10);
+ const t = el("t", 1, 0, 10);
+ const music = audio("m", 2, 0, 30);
+ // t dropped below a... wait, t already below a. Drag a below t instead:
+ // bottom→top = [a, t]. Above-neighbor t (lane 1); no free visual lane below
+ // → insert below t (order.indexOf(1) + 1 = 2), never onto the audio lane.
+ expect(reposition(a, [a, t, music], ["a", "t"])).toEqual({ kind: "insert", insertRow: 2 });
+ });
+
+ it("is pure: identical inputs, identical outputs, input untouched", () => {
+ const build = () => {
+ const a = el("a", 0, 0, 10);
+ const b = el("b", 1, 0, 10);
+ const t = el("t", 2, 0, 10);
+ return { t, elements: [a, b, t] };
+ };
+ const first = build();
+ const snapshot = structuredClone(first.elements);
+ const r1 = reposition(first.t, first.elements, ["b", "a", "t"]);
+ const fresh = build();
+ const r2 = reposition(fresh.t, fresh.elements, ["b", "a", "t"]);
+ expect(r1).toEqual(r2);
+ expect(first.elements).toEqual(snapshot);
+ });
+});
+
+describe("paint scope (source file + stacking context)", () => {
+ it("forward never references a same-file clip in a DIFFERENT stacking context", () => {
+ // b overlaps t and sits above, but lives in a nested stacking context —
+ // leaf z is not comparable, so the mirror must not treat it as a neighbor.
+ const b = el("b", 0, 0, 10, { stackingContextId: "ctx-nested" });
+ const t = el("t", 1, 0, 10);
+ expect(resolve("bring-forward", t, [b, t])).toBeNull();
+ });
+
+ it("cross-file clips with matching null root contexts never compare (expanded view)", () => {
+ const foreign = el("f", 0, 0, 10, { sourceFile: "scenes/intro.html" });
+ const t = el("t", 1, 0, 10);
+ expect(resolve("bring-forward", t, [foreign, t])).toBeNull();
+ expect(resolve("bring-to-front", t, [foreign, t])).toBeNull();
+ });
+
+ it("reposition skips neighbors outside the paint scope when resolving lanes", () => {
+ // t (lane 0) dragged below a in paint order; o sits between them in the
+ // DESIRED order but lives in a nested stacking context, so it must be
+ // skipped: the above-neighbor is a (lane 1). Lane 2 is occupied by o over
+ // the span (freeness is scope-agnostic) → insert below a (row 2).
+ const t = el("t", 0, 0, 10);
+ const a = el("a", 1, 0, 10);
+ const other = el("o", 2, 0, 10, { stackingContextId: "ctx-a" });
+ expect(
+ resolveRepositionLaneMove({
+ element: t,
+ elements: [t, a, other],
+ desiredOrderKeys: ["t", "o", "a"],
+ }),
+ ).toEqual({ kind: "insert", insertRow: 2 });
+ });
+});
+
+describe("expanded sub-comp children — lane scoping", () => {
+ const child = (id: string, track: number, start: number, duration: number) =>
+ el(id, track, start, duration, {
+ sourceFile: "scene.html",
+ expandedParentStart: 5,
+ });
+
+ it("a child mirrors onto a SIBLING's lane and persists the sibling's AUTHORED track", () => {
+ // Sibling c1 owns fractional display lane 0.25 (authored track 2 in its own
+ // file) but sits elsewhere in time → its lane is free over t's span.
+ const c1 = el("c1", 0.25, 20, 3, {
+ sourceFile: "scene.html",
+ expandedParentStart: 5,
+ authoredTrack: 2,
+ });
+ const c2 = child("c2", 0.5, 5, 5);
+ const t = child("t", 0.75, 5, 5);
+ expect(resolve("bring-forward", t, [c1, c2, t], "c2")).toEqual({
+ kind: "move",
+ displayTrack: 0.25,
+ persistTrack: 2,
+ });
+ });
+
+ it("a child NEVER lands on a host-space lane with no same-file occupant", () => {
+ // Free integer host lane 0 above the crossed sibling — out of scope for a
+ // child; with no sibling lane free either, the mirror refuses (null), it
+ // does not insert.
+ const host = el("h", 0, 20, 3); // host-space lane, free over the span
+ const c2 = child("c2", 0.5, 5, 5);
+ const t = child("t", 0.75, 5, 5);
+ expect(resolve("bring-forward", t, [host, c2, t], "c2")).toBeNull();
+ });
+
+ it("reposition of a child refuses instead of inserting a host lane", () => {
+ const c2 = child("c2", 0.5, 5, 5);
+ const t = child("t", 0.75, 5, 5);
+ // t dragged above c2 in the layers order; no free sibling lane → null.
+ expect(
+ resolveRepositionLaneMove({
+ element: t,
+ elements: [c2, t],
+ desiredOrderKeys: ["c2", "t"],
+ }),
+ ).toBeNull();
+ });
+});
diff --git a/packages/studio/src/player/components/timelineZMirror.ts b/packages/studio/src/player/components/timelineZMirror.ts
new file mode 100644
index 0000000000..f9a5fe28af
--- /dev/null
+++ b/packages/studio/src/player/components/timelineZMirror.ts
@@ -0,0 +1,393 @@
+import type { TimelineElement } from "../store/playerStore";
+import { classifyZone } from "./timelineZones";
+import { isLaneFree, timeRangesOverlap } from "./timelineCollision";
+import { authoredTrackForLane, sameSourceFile } from "./timelineClipDragCommit";
+import { samePaintScope } from "./timelineStackingSync";
+
+/**
+ * Mirror a canvas z-order action (Bring to Front / Bring Forward / Send Backward /
+ * Send to Back) into a timeline LANE move — the pure resolver, no UI wiring.
+ *
+ * ── The model ────────────────────────────────────────────────────────────────
+ * Track order is the DEFAULT paint order; authored z is the ADVANCED override.
+ * Render truth stays z — the renderer never reads track index — and the studio
+ * maintains z ↔ track consistency at EDIT time: a deliberate vertical lane move
+ * syncs z (timelineStackingSync), and a z-order menu action calls THIS resolver
+ * to compute the accompanying lane move. When the user authors z that diverges
+ * from track order, the mirror never fights the authored override — it only
+ * keeps the default in step.
+ *
+ * ── Locked rules (agreed design — do not re-litigate here) ───────────────────
+ * - The mirror computes a lane move to ACCOMPANY a z action on a timeline clip;
+ * it never replaces the z patch.
+ * - ONE-ELEMENT STEP (bring-forward / send-backward): the z action stepped past
+ * exactly ONE element — the reference neighbor — so the lane move must too.
+ * Target = the free lane (whole-span, file-agnostic occupancy, same zone)
+ * closest to the reference, searched STRICTLY BETWEEN the reference's lane
+ * and the next temporally-overlapping same-file visual element's lane in the
+ * direction (exclusive bound). No free lane in that open interval (the common
+ * back-to-back case) → CREATE one at the boundary immediately beyond the
+ * reference neighbor (commitTrackInsert semantics) — never scan past the
+ * second element to a farther free lane, which would overshoot the paint
+ * order. With no second overlapping element
+ * beyond the reference, the bound is the zone edge: closest free lane beyond
+ * the neighbor, else insert immediately beyond it.
+ * - bring-to-front / send-to-back move past the WHOLE overlap set: closest free
+ * lane beyond the extreme overlap in the direction, else insert adjacent to
+ * the extreme.
+ * - Direction: bring-forward/front = toward LOWER display lanes (up = above);
+ * send-backward/back = toward HIGHER lanes, but only within the visual zone —
+ * the audio zone is untouched and never crossed (a bottom-of-zone insert lands
+ * AT the visual/audio boundary, i.e. still a visual lane).
+ * - Reference scope: same source file AND same stacking context (see
+ * samePaintScope — a file can contain several stacking contexts, and leaf z
+ * is only comparable within one). Lane FREENESS stays file-agnostic (any
+ * clip in the zone occupies its lane for everyone).
+ * - Non-clip decorations (no timeline presence) are out of scope — callers keep
+ * z-only behavior for them. Audio elements never mirror (z on audio is
+ * meaningless); the resolver returns null.
+ *
+ * ── OPEN product question ────────────────────────────────────────────────────
+ * send-to-back / bring-to-front scope: below/above EVERYTHING visual, or only
+ * the clips that temporally overlap the moved clip? The default implemented
+ * here is TEMPORAL-OVERLAP scope (the extreme is computed over same-file clips
+ * that overlap the moved clip in time), pending M/Bin sign-off. A clip with no
+ * temporal overlaps in the direction is "already at the extreme" → null.
+ *
+ * Deterministic: a pure function of its inputs — no Date, no randomness, no DOM.
+ */
+
+export type ZMirrorAction = "bring-to-front" | "bring-forward" | "send-backward" | "send-to-back";
+
+export interface ZMirrorInput {
+ action: ZMirrorAction;
+ /** The clip acted on — store/display space (post-normalizeToZones lanes),
+ * carrying `authoredTrack` when the display lane diverges from the file. */
+ element: TimelineElement;
+ /** The expanded display element set (same set the drag commit reasons on). */
+ elements: TimelineElement[];
+ /** Timeline key of the neighbor the z action stepped over (forward/backward),
+ * when known — see resolveCrossedNeighbor in canvasContextMenuZOrder. */
+ crossedKey?: string | null;
+}
+
+export type ZMirrorLaneMove =
+ | {
+ /** Land on an existing display lane. */
+ kind: "move";
+ /** Display lane to move to (store space). */
+ displayTrack: number;
+ /** Authored-space value to write (authoredTrackForLane translation). */
+ persistTrack: number;
+ }
+ | {
+ /** Create a new lane: boundary row compatible with commitTrackInsert's
+ * insertRow (index into the ascending display trackOrder; 0 = above the
+ * top lane, length = below the bottom). */
+ kind: "insert";
+ insertRow: number;
+ }
+ | null;
+
+const keyOf = (el: TimelineElement): string => el.key ?? el.id;
+
+/**
+ * Lane candidates for an EXPANDED sub-comp child: only its own siblings' lanes
+ * (same file). An expanded child's display row is synthetic host-space — landing
+ * it on an arbitrary host lane has no same-file occupant to translate the
+ * authored track from, and a track INSERT would renumber host space from a
+ * child origin. Ordinary top-level clips return null (no restriction).
+ */
+function expandedChildAllowedLanes(
+ element: TimelineElement,
+ elements: TimelineElement[],
+): ReadonlySet<number> | null {
+ if (element.expandedParentStart == null) return null;
+ const selfKey = keyOf(element);
+ return new Set(
+ elements
+ .filter((el) => keyOf(el) !== selfKey && sameSourceFile(el, element))
+ .map((el) => el.track),
+ );
+}
+
+/** Ascending unique display lanes of `elements` — identical to how Timeline.tsx
+ * builds `trackOrder`, so `insertRow` indexes the same boundary space. Exported
+ * so the mirror wiring can hand commitZMirrorLaneMove the matching trackOrder. */
+export function displayTrackOrder(elements: TimelineElement[]): number[] {
+ return [...new Set(elements.map((el) => el.track))].sort((a, b) => a - b);
+}
+
+/**
+ * Resolve the timeline lane move that mirrors a z-order action on `element`.
+ * Returns null when no timeline mirror applies: audio / zero-length clips, no
+ * reference neighbor in the action's direction (the menu action was likely
+ * disabled or a no-op), or the clip is already laned where the action puts it.
+ */
+export function resolveZMirrorLaneMove(input: ZMirrorInput): ZMirrorLaneMove {
+ const { action, element, elements } = input;
+ if (classifyZone(element) === "audio") return null;
+ if (!(element.duration > 0)) return null;
+
+ const selfKey = keyOf(element);
+ const start = element.start;
+ const end = element.start + element.duration;
+ const up = action === "bring-forward" || action === "bring-to-front";
+
+ // Same paint scope (source file + stacking context), visual, temporally overlapping.
+ const overlapSet = elements.filter(
+ (el) =>
+ keyOf(el) !== selfKey &&
+ classifyZone(el) === "visual" &&
+ samePaintScope(el, element) &&
+ timeRangesOverlap(start, end, el.start, el.start + el.duration),
+ );
+
+ const referenceLane = resolveReferenceLane(input, overlapSet, up);
+ if (referenceLane == null) return null;
+
+ const order = displayTrackOrder(elements);
+ const visualLanes = displayTrackOrder(elements.filter((el) => classifyZone(el) === "visual"));
+ const refIdx = visualLanes.indexOf(referenceLane);
+ if (refIdx === -1) return null; // reference is not a visual lane — no mirror
+
+ const boundLane = stepBoundLane(action, overlapSet, referenceLane, up);
+ const allowedLanes = expandedChildAllowedLanes(element, elements);
+ const lane = closestFreeLane({
+ elements,
+ visualLanes,
+ refIdx,
+ up,
+ boundLane,
+ start,
+ end,
+ selfKey,
+ allowedLanes,
+ });
+ if (lane != null) {
+ // The closest free lane is the clip's OWN lane (possible only when z and
+ // track had diverged): the clip already sits where the action puts it.
+ if (lane === element.track) return null;
+ return {
+ kind: "move",
+ displayTrack: lane,
+ persistTrack: authoredTrackForLane(lane, elements, element),
+ };
+ }
+
+ // Expanded children never INSERT: a new lane is a host-lane-space renumber,
+ // meaningless in the child's own file (buildTrackInsertEdits refuses too).
+ if (allowedLanes) return null;
+ // No free lane before the bound (or the zone edge) → create one adjacent to
+ // the reference: the boundary between its lane and the next in direction.
+ return { kind: "insert", insertRow: order.indexOf(referenceLane) + (up ? 0 : 1) };
+}
+
+export interface ZRepositionInput {
+ /** The clip the Layers-panel drag moved — store/display space. */
+ element: TimelineElement;
+ /** The expanded display element set (same set the drag commit reasons on). */
+ elements: TimelineElement[];
+ /**
+ * Timeline keys of the reordered sibling set in DESIRED render order,
+ * bottom→top, the moved element's own key included at its new slot. Siblings
+ * with no timeline presence carry null — they are skipped when resolving the
+ * nearest clip neighbors.
+ */
+ desiredOrderKeys: ReadonlyArray<string | null>;
+}
+
+/**
+ * Mirror an ARBITRARY z repositioning (a Layers-panel drag, which can jump
+ * several siblings in one drop) into a timeline lane move — the "equal jump"
+ * generalization of {@link resolveZMirrorLaneMove}'s one-step rule: the clip
+ * lands between its NEW paint neighbors' lanes.
+ *
+ * The reference lanes are the nearest siblings in the desired render order
+ * that are visual, same-file timeline clips: `above` = the first such sibling
+ * that now paints above the moved clip, `below` = the first that paints below.
+ * Target lane = the free lane (whole-span, same zone) strictly between the
+ * above-neighbor's lane and the below-neighbor's lane, closest to the above
+ * neighbor; when only one neighbor exists the zone edge bounds the search on
+ * the open side. No free lane in the interval → INSERT a new lane immediately
+ * beyond the above neighbor (below it), or immediately above the below
+ * neighbor when dropped on top — commitTrackInsert semantics, exactly like the
+ * menu mirror's insert fallback.
+ *
+ * Null when no mirror applies: audio / zero-length clips, no clip neighbor in
+ * the set (a z-only decoration shuffle), or the clip already sits where the
+ * drop puts it.
+ */
+// fallow-ignore-next-line complexity
+export function resolveRepositionLaneMove(input: ZRepositionInput): ZMirrorLaneMove {
+ const { element, elements, desiredOrderKeys } = input;
+ if (classifyZone(element) === "audio") return null;
+ if (!(element.duration > 0)) return null;
+
+ const selfKey = keyOf(element);
+ const selfIdx = desiredOrderKeys.indexOf(selfKey);
+ if (selfIdx === -1) return null;
+
+ const clipLaneForKey = (key: string | null): number | null => {
+ if (key == null) return null;
+ const el = elements.find((candidate) => keyOf(candidate) === key);
+ return el &&
+ classifyZone(el) === "visual" &&
+ el.duration > 0 &&
+ samePaintScope(el, element) &&
+ keyOf(el) !== selfKey
+ ? el.track
+ : null;
+ };
+
+ // Nearest clip neighbor painting ABOVE (later in bottom→top order) / BELOW.
+ let aboveLane: number | null = null;
+ for (let i = selfIdx + 1; i < desiredOrderKeys.length && aboveLane == null; i++) {
+ aboveLane = clipLaneForKey(desiredOrderKeys[i]);
+ }
+ let belowLane: number | null = null;
+ for (let i = selfIdx - 1; i >= 0 && belowLane == null; i--) {
+ belowLane = clipLaneForKey(desiredOrderKeys[i]);
+ }
+ if (aboveLane == null && belowLane == null) return null;
+
+ const order = displayTrackOrder(elements);
+ const visualLanes = displayTrackOrder(elements.filter((el) => classifyZone(el) === "visual"));
+ const allowedLanes = expandedChildAllowedLanes(element, elements);
+ const args = {
+ elements,
+ visualLanes,
+ start: element.start,
+ end: element.start + element.duration,
+ selfKey,
+ allowedLanes,
+ };
+
+ let lane: number | null;
+ let insertRow: number;
+ if (aboveLane != null) {
+ // Paints above = LOWER display lane: search DOWNWARD from the above
+ // neighbor (closest lane under it first), bounded by the below neighbor
+ // (exclusive) when one exists, else by the zone edge.
+ const refIdx = visualLanes.indexOf(aboveLane);
+ if (refIdx === -1) return null;
+ lane = closestFreeLane({ ...args, refIdx, up: false, boundLane: belowLane });
+ insertRow = order.indexOf(aboveLane) + 1;
+ } else {
+ // Dropped above everything that remains: search UPWARD from the below
+ // neighbor toward the zone top.
+ const refIdx = visualLanes.indexOf(belowLane!);
+ if (refIdx === -1) return null;
+ lane = closestFreeLane({ ...args, refIdx, up: true, boundLane: null });
+ insertRow = order.indexOf(belowLane!);
+ }
+
+ if (lane != null) {
+ if (lane === element.track) return null;
+ return {
+ kind: "move",
+ displayTrack: lane,
+ persistTrack: authoredTrackForLane(lane, elements, element),
+ };
+ }
+ // Expanded children never INSERT (host-lane-space renumber from a child
+ // origin) — see expandedChildAllowedLanes.
+ if (allowedLanes) return null;
+ return { kind: "insert", insertRow };
+}
+
+/**
+ * ONE-ELEMENT-STEP bound (bring-forward / send-backward only): the lane of the
+ * NEXT temporally-overlapping same-file visual element strictly beyond the
+ * reference in the direction — the free-lane search may not reach it
+ * (exclusive). Front/back have no bound (they step past the whole overlap
+ * set), and neither does a step with no second overlapping element beyond the
+ * reference (the zone edge bounds instead).
+ */
+function stepBoundLane(
+ action: ZMirrorAction,
+ overlapSet: TimelineElement[],
+ referenceLane: number,
+ up: boolean,
+): number | null {
+ if (action !== "bring-forward" && action !== "send-backward") return null;
+ const beyond = overlapSet
+ .map((el) => el.track)
+ .filter((lane) => (up ? lane < referenceLane : lane > referenceLane));
+ if (beyond.length === 0) return null;
+ return (up ? Math.max : Math.min)(...beyond);
+}
+
+/**
+ * Closest free lane strictly beyond the reference, lane-by-lane in direction,
+ * whole-span freeness, same zone (visual lanes only — never into audio),
+ * stopping at the exclusive bound when one applies. Null → no free lane in
+ * the open interval.
+ */
+function closestFreeLane(args: {
+ elements: TimelineElement[];
+ visualLanes: number[];
+ refIdx: number;
+ up: boolean;
+ boundLane: number | null;
+ start: number;
+ end: number;
+ selfKey: string;
+ /** When set, only these lanes are candidates (expanded-child scoping). */
+ allowedLanes?: ReadonlySet<number> | null;
+}): number | null {
+ const { elements, visualLanes, refIdx, up, boundLane, start, end, selfKey, allowedLanes } = args;
+ const step = up ? -1 : 1;
+ for (let i = refIdx + step; i >= 0 && i < visualLanes.length; i += step) {
+ const lane = visualLanes[i];
+ if (pastSearchBound(lane, boundLane, up)) break;
+ if (allowedLanes && !allowedLanes.has(lane)) continue;
+ if (isLaneFree(elements, lane, start, end, selfKey)) return lane;
+ }
+ return null;
+}
+
+/** The exclusive one-element-step bound: stop at (never on/past) `boundLane`. */
+function pastSearchBound(lane: number, boundLane: number | null, up: boolean): boolean {
+ if (boundLane == null) return false;
+ return up ? lane <= boundLane : lane >= boundLane;
+}
+
+/**
+ * The lane the search starts from (the "reference neighbor"):
+ * - forward/backward: the crossed neighbor when provided and valid (a visual
+ * clip in the set); otherwise the closest temporally-overlapping same-file
+ * clip in the direction. None → null (the menu was probably disabled).
+ * - front/back: the extreme of the temporal-overlap set — topmost (lowest lane)
+ * for front, bottommost (highest lane) for back — restricted to overlaps
+ * strictly beyond the clip's own lane. None → already at the extreme → null.
+ */
+function resolveReferenceLane(
+ input: ZMirrorInput,
+ overlapSet: TimelineElement[],
+ up: boolean,
+): number | null {
+ const stepAction = input.action === "bring-forward" || input.action === "send-backward";
+ if (stepAction) {
+ const crossedLane = crossedNeighborLane(input);
+ // Unknown / absent / non-visual crossed key → the temporal neighbor below.
+ if (crossedLane != null) return crossedLane;
+ }
+
+ // Overlapping same-file lanes strictly beyond the moved clip's lane, in direction.
+ const lanes = overlapSet
+ .map((el) => el.track)
+ .filter((lane) => (up ? lane < input.element.track : lane > input.element.track));
+ if (lanes.length === 0) return null;
+
+ // Step actions want the CLOSEST lane in direction (max when up, min when
+ // down); front/back want the EXTREME of the set (min when up, max when down).
+ return (stepAction === up ? Math.max : Math.min)(...lanes);
+}
+
+/** The crossed neighbor's display lane, when the key names a visual clip in the set. */
+function crossedNeighborLane({ elements, crossedKey }: ZMirrorInput): number | null {
+ if (crossedKey == null) return null;
+ const crossed = elements.find((el) => keyOf(el) === crossedKey);
+ return crossed && classifyZone(crossed) === "visual" ? crossed.track : null;
+}
diff --git a/packages/studio/src/player/components/timelineZoom.test.ts b/packages/studio/src/player/components/timelineZoom.test.ts
index 8b2fc00572..34a5834cbe 100644
--- a/packages/studio/src/player/components/timelineZoom.test.ts
+++ b/packages/studio/src/player/components/timelineZoom.test.ts
@@ -45,11 +45,11 @@ describe("getTimelinePixelsPerSecond", () => {
describe("getNextTimelineZoomPercent", () => {
it("zooms out from fit relative to 100 percent", () => {
- expect(getNextTimelineZoomPercent("out", "fit", 375)).toBe(80);
+ expect(getNextTimelineZoomPercent("out", "fit", 375)).toBe(50);
});
it("zooms in from fit relative to 100 percent", () => {
- expect(getNextTimelineZoomPercent("in", "fit", 375)).toBe(125);
+ expect(getNextTimelineZoomPercent("in", "fit", 375)).toBe(200);
});
it("clamps the lower bound", () => {
diff --git a/packages/studio/src/player/components/timelineZoom.ts b/packages/studio/src/player/components/timelineZoom.ts
index 15baa15667..c243d7d18f 100644
--- a/packages/studio/src/player/components/timelineZoom.ts
+++ b/packages/studio/src/player/components/timelineZoom.ts
@@ -2,9 +2,13 @@ import type { ZoomMode } from "../store/playerStore";
export const MIN_TIMELINE_ZOOM_PERCENT = 10;
export const MAX_TIMELINE_ZOOM_PERCENT = 2000;
-const ZOOM_OUT_FACTOR = 0.8;
-const ZOOM_IN_FACTOR = 1.25;
-const PINCH_ZOOM_SENSITIVITY = 0.0035;
+// CapCut-strength steps: one button press / pinch gesture moves the zoom
+// meaningfully (user feedback, twice-doubled: 1.25×/0.8× + 0.0035 felt like
+// "zooming several times to get anywhere", then 1.5× + 0.007 still too soft).
+// Kept reciprocal (2 × 0.5 = 1) so in+out round-trips.
+const ZOOM_OUT_FACTOR = 0.5;
+const ZOOM_IN_FACTOR = 2;
+const PINCH_ZOOM_SENSITIVITY = 0.014;
export function clampTimelineZoomPercent(percent: number): number {
if (!Number.isFinite(percent)) return 100;
diff --git a/packages/studio/src/player/components/useTimelineClipDrag.ts b/packages/studio/src/player/components/useTimelineClipDrag.ts
index 4d0d6d72b9..f63c0d5c2a 100644
--- a/packages/studio/src/player/components/useTimelineClipDrag.ts
+++ b/packages/studio/src/player/components/useTimelineClipDrag.ts
@@ -76,7 +76,7 @@ interface UseTimelineClipDragInput {
* commitDraggedClipMove. Both optional → absent = no-op (backward compatible).
*/
readZIndex?: (element: TimelineElement) => number;
- onStackingPatches?: (patches: StackingPatch[]) => void;
+ onStackingPatches?: (patches: StackingPatch[]) => Promise<unknown> | void;
}
export function useTimelineClipDrag({
diff --git a/packages/studio/src/player/components/useTimelineGapHighlights.test.ts b/packages/studio/src/player/components/useTimelineGapHighlights.test.ts
new file mode 100644
index 0000000000..7dab8b2543
--- /dev/null
+++ b/packages/studio/src/player/components/useTimelineGapHighlights.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it } from "vitest";
+import type { TimelineElement } from "../store/playerStore";
+import { buildTimelineGapStrips } from "./useTimelineGapHighlights";
+
+function el(id: string, track: number, start: number, duration: number): TimelineElement {
+ return { id, key: id, tag: "video", start, duration, track, domId: id };
+}
+
+const laneA = [el("a1", 0, 1, 2), el("a2", 0, 5, 2)]; // gaps: [0,1), [3,5)
+const laneB = [el("b1", 1, 0, 2), el("b2", 1, 2, 3)]; // contiguous
+const tracks: [number, TimelineElement[]][] = [
+ [0, laneA],
+ [1, laneB],
+];
+const expandedElements = [...laneA, ...laneB];
+
+const base = {
+ gapHighlight: null,
+ tracks,
+ selectedElementId: null,
+ selectedElementIds: new Set<string>(),
+ expandedElements,
+ dragActive: false,
+ displayDuration: 60,
+};
+
+describe("buildTimelineGapStrips", () => {
+ it("emits a loud hover strip set from the gap-menu highlight", () => {
+ const strips = buildTimelineGapStrips({
+ ...base,
+ gapHighlight: { track: 0, intervals: [{ start: 3, end: 5 }] },
+ });
+ expect(strips).toEqual([{ track: 0, intervals: [{ start: 3, end: 5 }], kind: "hover" }]);
+ });
+
+ it("click-selection lights the WHOLE lane minus clips, trailing space included", () => {
+ const strips = buildTimelineGapStrips({ ...base, selectedElementId: "a1" });
+ expect(strips).toEqual([
+ {
+ track: 0,
+ intervals: [
+ { start: 0, end: 1 },
+ { start: 3, end: 5 },
+ { start: 7, end: 60 },
+ ],
+ kind: "selected",
+ },
+ ]);
+ });
+
+ it("a contiguous lane still lights its trailing open space", () => {
+ expect(buildTimelineGapStrips({ ...base, selectedElementId: "b1" })).toEqual([
+ { track: 1, intervals: [{ start: 5, end: 60 }], kind: "selected" },
+ ]);
+ });
+
+ it("a lane filling the whole rendered extent emits nothing", () => {
+ const laneFull = [el("f1", 5, 0, 60)];
+ const strips = buildTimelineGapStrips({
+ ...base,
+ tracks: [...tracks, [5, laneFull]],
+ expandedElements: [...expandedElements, ...laneFull],
+ selectedElementId: "f1",
+ });
+ expect(strips).toEqual([]);
+ });
+
+ it("a one-member selectedElementIds mirror of the click still counts as single", () => {
+ // The store mirrors a plain click into selectedElementIds = {clicked}.
+ const strips = buildTimelineGapStrips({
+ ...base,
+ selectedElementId: "a1",
+ selectedElementIds: new Set(["a1"]),
+ });
+ expect(strips).toHaveLength(1);
+ expect(strips[0].kind).toBe("selected");
+ });
+
+ it("marquee multi-selection never emits the selected hint", () => {
+ const strips = buildTimelineGapStrips({
+ ...base,
+ selectedElementId: "a1",
+ selectedElementIds: new Set(["a1", "b1"]),
+ });
+ expect(strips).toEqual([]);
+ });
+
+ it("hover wins on its own lane — no doubled strips for the same track", () => {
+ const strips = buildTimelineGapStrips({
+ ...base,
+ gapHighlight: { track: 0, intervals: [{ start: 3, end: 5 }] },
+ selectedElementId: "a1",
+ });
+ expect(strips).toHaveLength(1);
+ expect(strips[0].kind).toBe("hover");
+ });
+
+ it("hover and selection on DIFFERENT lanes coexist", () => {
+ const laneC = [el("c1", 2, 4, 2)];
+ const strips = buildTimelineGapStrips({
+ ...base,
+ tracks: [...tracks, [2, laneC]],
+ expandedElements: [...expandedElements, ...laneC],
+ gapHighlight: { track: 2, intervals: [{ start: 0, end: 4 }] },
+ selectedElementId: "a1",
+ });
+ expect(strips.map((s) => s.kind)).toEqual(["hover", "selected"]);
+ });
+
+ it("a live drag suppresses every strip", () => {
+ const strips = buildTimelineGapStrips({
+ ...base,
+ dragActive: true,
+ gapHighlight: { track: 0, intervals: [{ start: 3, end: 5 }] },
+ selectedElementId: "a1",
+ });
+ expect(strips).toEqual([]);
+ });
+});
diff --git a/packages/studio/src/player/components/useTimelineGapHighlights.ts b/packages/studio/src/player/components/useTimelineGapHighlights.ts
new file mode 100644
index 0000000000..ba2daa1fe4
--- /dev/null
+++ b/packages/studio/src/player/components/useTimelineGapHighlights.ts
@@ -0,0 +1,110 @@
+import { useMemo } from "react";
+import type { TimelineElement } from "../store/playerStore";
+import { laneGapFloor, resolveLaneEmptyIntervals, type TrackGapInterval } from "./timelineGaps";
+import type { TrackGapHighlight } from "./useTrackGapMenu";
+
+/**
+ * One lane's gap strips for the TimelineCanvas overlay.
+ *
+ * kind "hover" — the gap(s) a hovered "Close gap" / "Close all gaps" menu
+ * row would collapse: the loud affordance.
+ * kind "selected" — every empty interval on a click-selected clip's lane: the
+ * quiet always-on hint (single click-selection only — a
+ * marquee multi-select spans lanes and would paint noise).
+ */
+export interface TimelineLaneGapStrips {
+ track: number;
+ intervals: TrackGapInterval[];
+ kind: "hover" | "selected";
+}
+
+/**
+ * Derive the gap strips TimelineCanvas paints. The menu-hover highlight wins
+ * on its lane (painting both would just double the same strips); the
+ * selected-clip hint renders on the selection's lane otherwise. Suppressed
+ * entirely during a live drag — the drop placeholder / insert line own that
+ * moment, and the lane set is in flux.
+ */
+interface GapHighlightInput {
+ gapHighlight: TrackGapHighlight | null;
+ tracks: [number, TimelineElement[]][];
+ selectedElementId: string | null;
+ selectedElementIds: ReadonlySet<string>;
+ expandedElements: TimelineElement[];
+ dragActive: boolean;
+ /** Rendered timeline extent (seconds) — the selected-lane highlight spans the
+ * WHOLE lane minus its clips, trailing open space included. */
+ displayDuration: number;
+}
+
+/**
+ * Single selection only: the store mirrors a plain click into a one-member
+ * selectedElementIds set (setSelectedElementId collapses the multi-select),
+ * so "single" means empty OR exactly the selected clip itself. A marquee
+ * multi-select spans lanes and stays hint-free.
+ */
+function isSingleSelection(selectedElementId: string, ids: ReadonlySet<string>): boolean {
+ return ids.size === 0 || (ids.size === 1 && ids.has(selectedElementId));
+}
+
+/** The subtle strips for a single click-selected clip's lane, or null. */
+function selectedLaneStrips(input: GapHighlightInput): TimelineLaneGapStrips | null {
+ const { selectedElementId, selectedElementIds, expandedElements, tracks, gapHighlight } = input;
+ if (!selectedElementId || !isSingleSelection(selectedElementId, selectedElementIds)) return null;
+ const selected = expandedElements.find((el) => (el.key ?? el.id) === selectedElementId);
+ if (!selected || selected.track === gapHighlight?.track) return null;
+ const laneElements = tracks.find(([t]) => t === selected.track)?.[1] ?? [];
+ const intervals = resolveLaneEmptyIntervals(
+ laneElements,
+ input.displayDuration,
+ undefined,
+ laneGapFloor(laneElements),
+ );
+ return intervals.length > 0 ? { track: selected.track, intervals, kind: "selected" } : null;
+}
+
+/** Pure strip derivation — exported for direct unit testing. */
+export function buildTimelineGapStrips(input: GapHighlightInput): TimelineLaneGapStrips[] {
+ if (input.dragActive) return [];
+ const strips: TimelineLaneGapStrips[] = [];
+ if (input.gapHighlight && input.gapHighlight.intervals.length > 0) {
+ strips.push({ ...input.gapHighlight, kind: "hover" });
+ }
+ // Single click-selection → subtle gap hint on that clip's lane.
+ const selected = selectedLaneStrips(input);
+ if (selected) strips.push(selected);
+ return strips;
+}
+
+export function useTimelineGapHighlights(input: GapHighlightInput): TimelineLaneGapStrips[] {
+ const {
+ gapHighlight,
+ tracks,
+ selectedElementId,
+ selectedElementIds,
+ expandedElements,
+ dragActive,
+ displayDuration,
+ } = input;
+ return useMemo(
+ () =>
+ buildTimelineGapStrips({
+ gapHighlight,
+ tracks,
+ selectedElementId,
+ selectedElementIds,
+ expandedElements,
+ dragActive,
+ displayDuration,
+ }),
+ [
+ gapHighlight,
+ tracks,
+ selectedElementId,
+ selectedElementIds,
+ expandedElements,
+ dragActive,
+ displayDuration,
+ ],
+ );
+}
diff --git a/packages/studio/src/player/components/useTimelinePlayhead.ts b/packages/studio/src/player/components/useTimelinePlayhead.ts
index c24203377a..6706c0f7b3 100644
--- a/packages/studio/src/player/components/useTimelinePlayhead.ts
+++ b/packages/studio/src/player/components/useTimelinePlayhead.ts
@@ -4,6 +4,7 @@ import { useMountEffect } from "../../hooks/useMountEffect";
import { getPinchTimelineZoomPercent } from "./timelineZoom";
import {
GUTTER,
+ TRACKS_LEFT_PAD,
getTimelinePlayheadLeft,
getTimelineScrollLeftForZoomTransition,
getTimelineScrollLeftForZoomAnchor,
@@ -73,7 +74,7 @@ export function useTimelinePlayhead({
const nextScrollLeft = getTimelineScrollLeftForZoomAnchor({
pointerX: scroll.clientWidth / 2,
currentScrollLeft: scroll.scrollLeft,
- gutter: GUTTER,
+ gutter: GUTTER + TRACKS_LEFT_PAD,
currentPixelsPerSecond: prevPps,
nextPixelsPerSecond: pps,
duration: durationRef.current,
@@ -129,7 +130,7 @@ export function useTimelinePlayhead({
const el = scrollRef.current;
if (!el || effectiveDuration <= 0) return;
const rect = el.getBoundingClientRect();
- const x = clientX - rect.left + el.scrollLeft - GUTTER;
+ const x = clientX - rect.left + el.scrollLeft - GUTTER - TRACKS_LEFT_PAD;
if (x < 0) return;
const time = Math.max(0, Math.min(effectiveDuration, x / pps));
liveTime.notify(time);
@@ -185,7 +186,7 @@ export function useTimelinePlayhead({
const nextScrollLeft = getTimelineScrollLeftForZoomAnchor({
pointerX: e.clientX - rect.left,
currentScrollLeft: scroll.scrollLeft,
- gutter: GUTTER,
+ gutter: GUTTER + TRACKS_LEFT_PAD,
currentPixelsPerSecond: ppsRef.current,
nextPixelsPerSecond: nextPps,
duration: durationRef.current,
diff --git a/packages/studio/src/player/components/useTimelineRangeSelection.ts b/packages/studio/src/player/components/useTimelineRangeSelection.ts
index ca1dc2697f..1df2a74fee 100644
--- a/packages/studio/src/player/components/useTimelineRangeSelection.ts
+++ b/packages/studio/src/player/components/useTimelineRangeSelection.ts
@@ -7,7 +7,7 @@ import {
} from "./timelineEditing";
import type { TimelineElement } from "../store/playerStore";
import { liveTime, usePlayerStore } from "../store/playerStore";
-import { GUTTER } from "./timelineLayout";
+import { GUTTER, TRACKS_LEFT_PAD } from "./timelineLayout";
import {
computeMarqueeSelection,
getMarqueeRect,
@@ -228,7 +228,8 @@ export function useTimelineRangeSelection({
setShowPopover(false);
const rect = scrollRef.current?.getBoundingClientRect();
if (rect) {
- const x = e.clientX - rect.left + (scrollRef.current?.scrollLeft ?? 0) - GUTTER;
+ const x =
+ e.clientX - rect.left + (scrollRef.current?.scrollLeft ?? 0) - GUTTER - TRACKS_LEFT_PAD;
const time = Math.max(0, x / pps);
rangeAnchorTime.current = time;
setRangeSelection({ start: time, end: time, anchorX: e.clientX, anchorY: e.clientY });
@@ -285,7 +286,7 @@ export function useTimelineRangeSelection({
const el = scrollRef.current;
if (el) {
const rect = el.getBoundingClientRect();
- const x = clientX - rect.left + el.scrollLeft - GUTTER;
+ const x = clientX - rect.left + el.scrollLeft - GUTTER - TRACKS_LEFT_PAD;
if (x >= 0) {
const dur = el.scrollWidth / pps;
liveTime.notify(Math.max(0, Math.min(dur, x / pps)));
@@ -309,7 +310,8 @@ export function useTimelineRangeSelection({
if (isRangeSelecting.current) {
const rect = scrollRef.current?.getBoundingClientRect();
if (rect) {
- const x = e.clientX - rect.left + (scrollRef.current?.scrollLeft ?? 0) - GUTTER;
+ const x =
+ e.clientX - rect.left + (scrollRef.current?.scrollLeft ?? 0) - GUTTER - TRACKS_LEFT_PAD;
setRangeSelection((prev) =>
prev
? { ...prev, end: Math.max(0, x / pps), anchorX: e.clientX, anchorY: e.clientY }
diff --git a/packages/studio/src/player/components/useTimelineScrollViewport.ts b/packages/studio/src/player/components/useTimelineScrollViewport.ts
new file mode 100644
index 0000000000..55d5e9a2df
--- /dev/null
+++ b/packages/studio/src/player/components/useTimelineScrollViewport.ts
@@ -0,0 +1,73 @@
+import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
+import { useMountEffect } from "../../hooks/useMountEffect";
+import { shouldShowTimelineShortcutHint } from "./timelineLayout";
+
+/**
+ * The timeline scroll container's viewport plumbing — extracted verbatim from
+ * Timeline.tsx (600-line studio cap): the ResizeObserver-backed viewport width,
+ * the rAF-throttled shortcut-hint visibility sync, and the callback ref that
+ * wires both to the scroll element. `resyncShortcutHintOn` re-checks the hint
+ * whenever any of its values change (timeline readiness / element count /
+ * canvas height), matching the original effect.
+ */
+export function useTimelineScrollViewport(
+ scrollRef: RefObject<HTMLDivElement | null>,
+ resyncShortcutHintOn: ReadonlyArray<unknown>,
+): {
+ viewportWidth: number;
+ showShortcutHint: boolean;
+ setScrollRef: (el: HTMLDivElement | null) => void;
+} {
+ const [viewportWidth, setViewportWidth] = useState(0);
+ const [showShortcutHint, setShowShortcutHint] = useState(true);
+ const roRef = useRef<ResizeObserver | null>(null);
+ const shortcutHintRafRef = useRef(0);
+
+ const syncShortcutHintVisibility = useCallback(() => {
+ const scroll = scrollRef.current;
+ setShowShortcutHint(
+ scroll ? shouldShowTimelineShortcutHint(scroll.scrollHeight, scroll.clientHeight) : true,
+ );
+ }, [scrollRef]);
+
+ const scheduleShortcutHintVisibilitySync = useCallback(() => {
+ if (shortcutHintRafRef.current) cancelAnimationFrame(shortcutHintRafRef.current);
+ shortcutHintRafRef.current = requestAnimationFrame(() => {
+ shortcutHintRafRef.current = 0;
+ syncShortcutHintVisibility();
+ });
+ }, [syncShortcutHintVisibility]);
+
+ const setScrollRef = useCallback(
+ (el: HTMLDivElement | null) => {
+ if (roRef.current) {
+ roRef.current.disconnect();
+ roRef.current = null;
+ }
+ scrollRef.current = el;
+ if (!el) return;
+
+ const syncScrollViewport = () => {
+ setViewportWidth(el.clientWidth);
+ scheduleShortcutHintVisibilitySync();
+ };
+
+ syncScrollViewport();
+ roRef.current = new ResizeObserver(syncScrollViewport);
+ roRef.current.observe(el);
+ },
+ [scrollRef, scheduleShortcutHintVisibilitySync],
+ );
+
+ useMountEffect(() => () => {
+ roRef.current?.disconnect();
+ if (shortcutHintRafRef.current) cancelAnimationFrame(shortcutHintRafRef.current);
+ });
+
+ useEffect(() => {
+ syncShortcutHintVisibility();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [syncShortcutHintVisibility, ...resyncShortcutHintOn]);
+
+ return { viewportWidth, showShortcutHint, setScrollRef };
+}
diff --git a/packages/studio/src/player/components/useTimelineStackingSync.test.tsx b/packages/studio/src/player/components/useTimelineStackingSync.test.tsx
index 7d0c89fef0..11eb0f32a3 100644
--- a/packages/studio/src/player/components/useTimelineStackingSync.test.tsx
+++ b/packages/studio/src/player/components/useTimelineStackingSync.test.tsx
@@ -40,7 +40,6 @@ describe("useTimelineStackingSync", () => {
start: 0,
duration: 2,
track: 0,
- sourceFile: "nested.html",
};
let apply: ((patches: Array<{ key: string; zIndex: number }>, key?: string) => unknown) | null =
null;
diff --git a/packages/studio/src/player/components/useTimelineStackingSync.ts b/packages/studio/src/player/components/useTimelineStackingSync.ts
index d21974d01c..f68aa68a83 100644
--- a/packages/studio/src/player/components/useTimelineStackingSync.ts
+++ b/packages/studio/src/player/components/useTimelineStackingSync.ts
@@ -37,7 +37,7 @@ export function useTimelineStackingSync({ expandedElementsRef }: UseTimelineStac
id: el.domId ?? el.id,
selector: el.selector,
selectorIndex: el.selectorIndex,
- sourceFile: el.sourceFile,
+ sourceFile: el.sourceFile ?? zSyncActiveCompPath ?? "index.html",
},
zSyncActiveCompPath,
);
@@ -61,7 +61,7 @@ export function useTimelineStackingSync({ expandedElementsRef }: UseTimelineStac
const applyStackingPatches = useCallback(
(patches: StackingPatch[], coalesceKey?: string) => {
- if (!handleDomZIndexReorderCommit) return;
+ if (!handleDomZIndexReorderCommit) return Promise.resolve();
const entries = patches.flatMap((p) => {
const el = expandedElementsRef.current.find((e) => (e.key ?? e.id) === p.key);
const node = el && resolveIframeElement(el);
@@ -82,7 +82,9 @@ export function useTimelineStackingSync({ expandedElementsRef }: UseTimelineStac
});
// 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);
+ return entries.length
+ ? handleDomZIndexReorderCommit(entries, coalesceKey).then(() => undefined)
+ : Promise.resolve();
},
[handleDomZIndexReorderCommit, resolveIframeElement, zSyncActiveCompPath, expandedElementsRef],
);
diff --git a/packages/studio/src/player/components/useTimelineTrackDerivations.ts b/packages/studio/src/player/components/useTimelineTrackDerivations.ts
new file mode 100644
index 0000000000..b6bace824d
--- /dev/null
+++ b/packages/studio/src/player/components/useTimelineTrackDerivations.ts
@@ -0,0 +1,38 @@
+import { useMemo } from "react";
+import type { TimelineElement } from "../store/playerStore";
+import { getTrackStyle, type TrackVisualStyle } from "./timelineIcons";
+
+/**
+ * Per-render track derivations Timeline.tsx feeds the canvas/lanes: the lane →
+ * clip grouping (`tracks`, ascending), per-lane visual styles, the ascending
+ * `trackOrder`, and the z-override badge set. Extracted from Timeline.tsx as a
+ * cohesive unit (600-line studio cap); each memo keys on the expanded display
+ * element set exactly as before.
+ */
+export function useTimelineTrackDerivations(expandedElements: TimelineElement[]): {
+ tracks: [number, TimelineElement[]][];
+ trackStyles: Map<number, TrackVisualStyle>;
+ trackOrder: number[];
+} {
+ const tracks = useMemo(() => {
+ const map = new Map<number, TimelineElement[]>();
+ for (const el of expandedElements) {
+ const list = map.get(el.track) ?? [];
+ list.push(el);
+ map.set(el.track, list);
+ }
+ return Array.from(map.entries()).sort(([a], [b]) => a - b);
+ }, [expandedElements]);
+
+ const trackStyles = useMemo(() => {
+ const map = new Map<number, TrackVisualStyle>();
+ for (const [trackNum, els] of tracks) {
+ map.set(trackNum, getTrackStyle(els[0]?.tag ?? ""));
+ }
+ return map;
+ }, [tracks]);
+
+ const trackOrder = useMemo(() => tracks.map(([trackNum]) => trackNum), [tracks]);
+
+ return { tracks, trackStyles, trackOrder };
+}
diff --git a/packages/studio/src/player/components/useTrackGapMenu.ts b/packages/studio/src/player/components/useTrackGapMenu.ts
new file mode 100644
index 0000000000..7339171ee3
--- /dev/null
+++ b/packages/studio/src/player/components/useTrackGapMenu.ts
@@ -0,0 +1,155 @@
+import { useCallback, useMemo, useState, type MutableRefObject } from "react";
+import { usePlayerStore, type TimelineElement } from "../store/playerStore";
+import type { DragCommitDeps } from "./timelineClipDragCommit";
+import {
+ laneGapFloor,
+ resolveAllGapIntervals,
+ resolveAllTrackGaps,
+ resolveCloseGapShifts,
+ resolveTrackGapAt,
+ type TrackGapInterval,
+} from "./timelineGaps";
+import {
+ canShiftTrackGapClips,
+ commitCloseAllTrackGaps,
+ commitCloseTrackGap,
+} from "./timelineGapCommit";
+
+/** Right-click anchor on EMPTY lane space: pointer position + clicked lane/time. */
+interface TrackGapMenuAnchor {
+ x: number;
+ y: number;
+ track: number;
+ time: number;
+}
+
+/** Gap strips to paint on one lane while a menu row is hovered. */
+export interface TrackGapHighlight {
+ track: number;
+ intervals: TrackGapInterval[];
+}
+
+/**
+ * Track-gap context menu (right-click on empty lane space) — state, the
+ * derived menu model, and the two commit actions. Extracted from Timeline.tsx
+ * as a cohesive unit (600-line studio cap); behavior identical.
+ *
+ * Only the ANCHOR (and the hovered row) is state; the menu model (gap under
+ * the pointer, compaction, movability) derives from live `tracks` so an open
+ * menu reflects concurrent edits. `gapHighlight` — the strips TimelineCanvas
+ * paints while "Close gap" / "Close all gaps" is hovered — derives the same
+ * way. Commits are ONE atomic batch each via the existing move-persist
+ * pipeline (see timelineGapCommit.ts).
+ */
+export function useTrackGapMenu({
+ tracks,
+ expandedElementsRef,
+ trackOrderRef,
+ onMoveElement,
+ onMoveElements,
+}: {
+ tracks: [number, TimelineElement[]][];
+ expandedElementsRef: MutableRefObject<TimelineElement[]>;
+ trackOrderRef: MutableRefObject<number[]>;
+ onMoveElement: DragCommitDeps["onMoveElement"];
+ onMoveElements: DragCommitDeps["onMoveElements"];
+}) {
+ const updateElement = usePlayerStore((s) => s.updateElement);
+ const [gapContextMenu, setGapContextMenu] = useState<TrackGapMenuAnchor | null>(null);
+ const [hoveredGapAction, setHoveredGapAction] = useState<"close-gap" | "close-all" | null>(null);
+
+ const gapMenuLaneElements = useMemo(
+ () => (gapContextMenu ? (tracks.find(([t]) => t === gapContextMenu.track)?.[1] ?? []) : null),
+ [gapContextMenu, tracks],
+ );
+ const gapMenuModel = useMemo(() => {
+ if (!gapContextMenu || !gapMenuLaneElements) return null;
+ const floor = laneGapFloor(gapMenuLaneElements);
+ const gap = resolveTrackGapAt(gapMenuLaneElements, gapContextMenu.time, undefined, floor);
+ const allShifts = resolveAllTrackGaps(gapMenuLaneElements, undefined, floor);
+ return {
+ x: gapContextMenu.x,
+ y: gapContextMenu.y,
+ gapWidth: gap ? gap.gapEnd - gap.gapStart : null,
+ canCloseGap:
+ gap != null &&
+ canShiftTrackGapClips(gapMenuLaneElements, resolveCloseGapShifts(gapMenuLaneElements, gap)),
+ hasAnyGaps: allShifts.length > 0,
+ canCloseAllGaps:
+ allShifts.length > 0 && canShiftTrackGapClips(gapMenuLaneElements, allShifts),
+ };
+ }, [gapContextMenu, gapMenuLaneElements]);
+
+ // The strips to paint while a menu row is hovered: the one gap under the
+ // pointer for "Close gap", every current gap (leading included) for
+ // "Close all gaps". Null when nothing is hovered / nothing would close.
+ const gapHighlight = useMemo<TrackGapHighlight | null>(() => {
+ if (!gapContextMenu || !gapMenuLaneElements || !hoveredGapAction) return null;
+ const floor = laneGapFloor(gapMenuLaneElements);
+ if (hoveredGapAction === "close-gap") {
+ const gap = resolveTrackGapAt(gapMenuLaneElements, gapContextMenu.time, undefined, floor);
+ if (!gap) return null;
+ return {
+ track: gapContextMenu.track,
+ intervals: [{ start: gap.gapStart, end: gap.gapEnd }],
+ };
+ }
+ const intervals = resolveAllGapIntervals(gapMenuLaneElements, undefined, floor);
+ return intervals.length > 0 ? { track: gapContextMenu.track, intervals } : null;
+ }, [gapContextMenu, gapMenuLaneElements, hoveredGapAction]);
+
+ const closeTrackGap = useCallback(() => {
+ if (!gapContextMenu || !gapMenuLaneElements) return;
+ commitCloseTrackGap(gapMenuLaneElements, gapContextMenu.time, {
+ elements: expandedElementsRef.current,
+ trackOrder: trackOrderRef.current,
+ updateElement,
+ onMoveElement,
+ onMoveElements,
+ });
+ }, [
+ gapContextMenu,
+ gapMenuLaneElements,
+ expandedElementsRef,
+ trackOrderRef,
+ updateElement,
+ onMoveElement,
+ onMoveElements,
+ ]);
+ const closeAllTrackGaps = useCallback(() => {
+ if (!gapMenuLaneElements) return;
+ commitCloseAllTrackGaps(gapMenuLaneElements, {
+ elements: expandedElementsRef.current,
+ trackOrder: trackOrderRef.current,
+ updateElement,
+ onMoveElement,
+ onMoveElements,
+ });
+ }, [
+ gapMenuLaneElements,
+ expandedElementsRef,
+ trackOrderRef,
+ updateElement,
+ onMoveElement,
+ onMoveElements,
+ ]);
+
+ const openGapMenu = useCallback((anchor: TrackGapMenuAnchor) => {
+ setHoveredGapAction(null);
+ setGapContextMenu(anchor);
+ }, []);
+ const dismissGapMenu = useCallback(() => {
+ setHoveredGapAction(null);
+ setGapContextMenu(null);
+ }, []);
+
+ return {
+ gapMenuModel,
+ gapHighlight,
+ setHoveredGapAction,
+ openGapMenu,
+ dismissGapMenu,
+ closeTrackGap,
+ closeAllTrackGaps,
+ };
+}
diff --git a/packages/studio/src/player/hooks/useExpandedTimelineElements.test.ts b/packages/studio/src/player/hooks/useExpandedTimelineElements.test.ts
index 888b426220..6e7b1c4676 100644
--- a/packages/studio/src/player/hooks/useExpandedTimelineElements.test.ts
+++ b/packages/studio/src/player/hooks/useExpandedTimelineElements.test.ts
@@ -152,10 +152,34 @@ describe("buildExpandedElements", () => {
["pill-3", "group-1"],
]);
const domClipChildren = [
- { id: "group-1", parentId: "scene-host", hostId: "scene-host", label: "Group 1" },
- { id: "pill-1", parentId: "group-1", hostId: "scene-host", label: "pill-1" },
- { id: "pill-2", parentId: "group-1", hostId: "scene-host", label: "pill-2" },
- { id: "pill-3", parentId: "group-1", hostId: "scene-host", label: "pill-3" },
+ {
+ id: "group-1",
+ parentId: "scene-host",
+ hostId: "scene-host",
+ label: "Group 1",
+ stackingContextId: "css:0",
+ },
+ {
+ id: "pill-1",
+ parentId: "group-1",
+ hostId: "scene-host",
+ label: "pill-1",
+ stackingContextId: "css:0.0",
+ },
+ {
+ id: "pill-2",
+ parentId: "group-1",
+ hostId: "scene-host",
+ label: "pill-2",
+ stackingContextId: "css:0.1",
+ },
+ {
+ id: "pill-3",
+ parentId: "group-1",
+ hostId: "scene-host",
+ label: "pill-3",
+ stackingContextId: "css:0.1",
+ },
];
// Expanding pill-3's siblings: topLevel scene-host, immediate parent group-1.
@@ -173,6 +197,7 @@ describe("buildExpandedElements", () => {
expect(pills[0]!.start).toBe(5);
expect(pills[0]!.duration).toBe(6);
expect(pills[0]!.sourceFile).toBe("scene.html");
+ expect(pills.map((pill) => pill.stackingContextId)).toEqual(["css:0.0", "css:0.1", "css:0.1"]);
// The host row is replaced by its children.
expect(out.some((e) => e.domId === "scene-host")).toBe(false);
});
@@ -273,3 +298,41 @@ describe("resolveTimelineExpansionRawId", () => {
).toBe("caption");
});
});
+
+describe("buildExpandedElements — collision-free synthetic rows (cross-file lane safety)", () => {
+ it("expanded children NEVER share a display track with an unrelated top-level clip", () => {
+ // The Deepwork regression: host on track 0 with two children used to put
+ // child #2 on integer track 1 — the same lane as index.html#foreign. Lane
+ // grouping merges purely by track number, so a gap-close on that "one"
+ // lane batch-persisted a foreign file's clip.
+ const elements = [
+ el({ id: "host", start: 0, duration: 20, track: 0, compositionSrc: "scene.html" }),
+ el({ id: "foreign", start: 20, duration: 5, track: 1 }),
+ ];
+ const manifest = [
+ clip({ id: "host", start: 0, duration: 20, compositionSrc: "scene.html" }),
+ clip({ id: "c1", start: 0, duration: 5 }),
+ clip({ id: "c2", start: 10, duration: 5 }),
+ ];
+ const parentMap = new Map([
+ ["c1", "host"],
+ ["c2", "host"],
+ ]);
+
+ const out = buildExpandedElements(elements, manifest, parentMap, "host", "host");
+ const foreign = out.find((e) => e.id === "foreign")!;
+ const children = out.filter((e) => e.domId === "c1" || e.domId === "c2");
+ expect(children).toHaveLength(2);
+ for (const child of children) {
+ // No lane sharing with the foreign clip…
+ expect(child.track).not.toBe(foreign.track);
+ // …and structurally impossible to collide with ANY normalized (integer)
+ // lane: synthetic rows are strict fractions under the host's lane.
+ expect(Number.isInteger(child.track)).toBe(false);
+ expect(child.track).toBeGreaterThan(0);
+ expect(child.track).toBeLessThan(1);
+ }
+ // Distinct ordered rows per child.
+ expect(children[0].track).not.toBe(children[1].track);
+ });
+});
diff --git a/packages/studio/src/player/hooks/useExpandedTimelineElements.ts b/packages/studio/src/player/hooks/useExpandedTimelineElements.ts
index eb326e4e1e..402a79a3d0 100644
--- a/packages/studio/src/player/hooks/useExpandedTimelineElements.ts
+++ b/packages/studio/src/player/hooks/useExpandedTimelineElements.ts
@@ -168,7 +168,17 @@ function buildChildElements(
// file's coordinate space) and the runtime-computed `stackingContextId`
// must survive verbatim — lane persists and z-sync read them, they are
// never reconstructed from display lanes.
- track: display.track + result.length,
+ //
+ // COLLISION-FREE synthetic rows: the old `display.track + index` scheme
+ // could equal a REAL clip's integer lane (host on track 0 with two
+ // children puts child #2 on track 1 — where an unrelated top-level clip
+ // may live). Lane grouping merges purely by track number, so that
+ // collision fused clips from DIFFERENT source files into one display
+ // lane, and lane-scoped actions (gap close) then batch-persisted foreign
+ // clips. Fractions strictly between the host's lane and the next integer
+ // can never equal a normalized (integer) lane, while still rendering the
+ // children as their own ordered rows directly under the host.
+ track: display.track + (result.length + 1) / (siblings.length + 2),
authoredTrack: base.authoredTrack,
stackingContextId: base.stackingContextId,
expandedParentStart: editBasis.start,
@@ -205,6 +215,7 @@ function domSiblingClips(
parentCompositionId: host.id ?? null,
compositionSrc: host.compositionSrc ?? null,
assetUrl: null,
+ stackingContextId: c.stackingContextId,
}),
);
}
diff --git a/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts b/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts
index f7c222be70..c4526e2609 100644
--- a/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts
+++ b/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts
@@ -11,6 +11,7 @@
import { useCallback } from "react";
import { liveTime, usePlayerStore } from "../store/playerStore";
import type { TimelineElement, DomClipChild } from "../store/playerStore";
+import { resolveCssStackingContextId } from "@hyperframes/core/runtime/stacking-context";
import type { PlaybackAdapter, ClipManifestClip, IframeWindow } from "../lib/playbackTypes";
import {
parseTimelineFromDOM,
@@ -199,6 +200,7 @@ export function useTimelineSyncCallbacks({
parentId,
hostId,
label: isGroup ? child.getAttribute("data-hf-group") || child.id : child.id,
+ stackingContextId: resolveCssStackingContextId(child),
});
parentMap.set(child.id, parentId);
if (isGroup) collect(child, child.id);
diff --git a/packages/studio/src/player/lib/layerOrdering.test.ts b/packages/studio/src/player/lib/layerOrdering.test.ts
index cb5f035a33..37219fe648 100644
--- a/packages/studio/src/player/lib/layerOrdering.test.ts
+++ b/packages/studio/src/player/lib/layerOrdering.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { describe, expect, it } from "vitest";
-import { computeReorderZValues, getElementZIndex, resolveContextOrder } from "./layerOrdering";
+import { getElementZIndex, resolveContextOrder } from "./layerOrdering";
function makeElement(zIndex?: string): HTMLElement {
const element = document.createElement("div");
@@ -31,20 +31,6 @@ describe("getElementZIndex", () => {
});
});
-describe("computeReorderZValues", () => {
- it("preserves distinct existing z-index values and remaps them onto the new order", () => {
- expect(computeReorderZValues([1, 8, 3], 0, 2)).toEqual([8, 3, 1]);
- });
-
- it("renumbers an all-tied group to descending contiguous z-index values", () => {
- expect(computeReorderZValues([0, 0, 0], 2, 0)).toEqual([3, 2, 1]);
- });
-
- it("renumbers the whole group when any existing z-index values are tied", () => {
- expect(computeReorderZValues([5, 5, 1], 2, 0)).toEqual([3, 2, 1]);
- });
-});
-
describe("resolveContextOrder", () => {
it("sorts a flat sibling group by z-index descending then original order", () => {
const ordered = resolveContextOrder([
diff --git a/packages/studio/src/player/lib/layerOrdering.ts b/packages/studio/src/player/lib/layerOrdering.ts
index d5ad26f065..1f62820db4 100644
--- a/packages/studio/src/player/lib/layerOrdering.ts
+++ b/packages/studio/src/player/lib/layerOrdering.ts
@@ -1,3 +1,5 @@
+import { readLayerRevealPriorZ } from "./timelineElementHelpers";
+
export interface StackingContextDescriptor {
parentCompositionId: string | null;
compositionAncestors: readonly string[];
@@ -11,6 +13,9 @@ export interface ContextOrderItem extends StackingContextDescriptor {
// fallow-ignore-next-line complexity
export function getElementZIndex(element: HTMLElement): number {
try {
+ // An active Layers-panel reveal lift reports the element's TRUE z.
+ const prior = readLayerRevealPriorZ(element);
+ if (prior != null) return prior;
const inline = element.style?.zIndex;
if (inline && inline !== "auto") {
const parsed = parseInt(inline, 10);
@@ -27,34 +32,6 @@ export function getElementZIndex(element: HTMLElement): number {
}
}
-// fallow-ignore-next-line complexity
-export function hasExplicitZIndex(element: HTMLElement): boolean {
- try {
- const inline = element.style?.zIndex;
- if (inline) return inline !== "auto";
- const win = element.ownerDocument?.defaultView;
- if (!win) return false;
- const value = win.getComputedStyle(element).zIndex;
- return value !== "auto" && value !== "";
- } catch {
- return false;
- }
-}
-
-export function computeReorderZValues(
- existingValues: readonly number[],
- fromIndex: number,
- toIndex: number,
-): number[] {
- const reordered = [...existingValues];
- const [moved] = reordered.splice(fromIndex, 1);
- reordered.splice(toIndex, 0, moved);
-
- const sorted = [...existingValues].sort((a, b) => b - a);
- const hasDupes = sorted.some((v, i) => i > 0 && v === sorted[i - 1]);
- return hasDupes ? reordered.map((_, i) => reordered.length - i) : sorted;
-}
-
export function resolveStackingContextKey(item: StackingContextDescriptor): string {
return item.stackingContextId ?? item.parentCompositionId ?? item.compositionAncestors[0] ?? "";
}
diff --git a/packages/studio/src/player/lib/timelineDOM.test.ts b/packages/studio/src/player/lib/timelineDOM.test.ts
index ac3ad76037..784ce6a178 100644
--- a/packages/studio/src/player/lib/timelineDOM.test.ts
+++ b/packages/studio/src/player/lib/timelineDOM.test.ts
@@ -110,7 +110,79 @@ describe("parseTimelineFromDOM — hfId from data-hf-id", () => {
});
});
+describe("createTimelineElementFromManifestClip — source-scoped selector identity", () => {
+ it("ignores an index.html duplicate when indexing a scene.html selector", () => {
+ const doc = makeDoc(`
+ <div data-composition-id="root" data-composition-file="index.html">
+ <div class="sub"></div>
+ <div data-composition-id="scene" data-composition-file="scene.html">
+ <div class="sub"></div>
+ <div class="sub" data-target></div>
+ </div>
+ </div>
+ `);
+ const target = doc.querySelector("[data-target]");
+ if (!target) throw new Error("missing target");
+
+ const element = createTimelineElementFromManifestClip({
+ clip: {
+ id: null,
+ label: "Sub",
+ kind: "element",
+ tagName: "div",
+ start: 0,
+ duration: 5,
+ track: 0,
+ compositionId: null,
+ parentCompositionId: null,
+ compositionSrc: null,
+ assetUrl: null,
+ },
+ fallbackIndex: 0,
+ doc,
+ hostEl: target,
+ });
+
+ expect(element.sourceFile).toBe("scene.html");
+ expect(element.selectorIndex).toBe(1);
+ expect(element.key).toBe("scene.html:.sub:1");
+ });
+});
+
describe("createImplicitTimelineLayersFromDOM — hfId from data-hf-id", () => {
+ it("uses the runtime root paint scope for implicit siblings of manifest clips", () => {
+ const doc = makeDoc(`
+ <div data-composition-id="root">
+ <div id="timed" data-start="0" data-duration="5"></div>
+ <div id="implicit"></div>
+ </div>
+ `);
+ const timedHost = doc.getElementById("timed");
+ const timed = createTimelineElementFromManifestClip({
+ clip: {
+ id: "timed",
+ label: "Timed",
+ start: 0,
+ duration: 5,
+ track: 0,
+ stackingContextId: "css:root",
+ kind: "element",
+ tagName: "div",
+ compositionId: null,
+ parentCompositionId: null,
+ compositionSrc: null,
+ assetUrl: null,
+ },
+ fallbackIndex: 0,
+ doc,
+ hostEl: timedHost,
+ });
+ const implicit = createImplicitTimelineLayersFromDOM(doc, 5, [timed])[0];
+
+ expect(implicit?.stackingContextId).toBe("css:root");
+ expect(implicit?.stackingContextId).toBe(timed.stackingContextId);
+ });
+
it("harvests hfId from an implicit layer child that has data-hf-id", () => {
const doc = makeDoc(`
<div data-composition-id="root">
diff --git a/packages/studio/src/player/lib/timelineDOM.ts b/packages/studio/src/player/lib/timelineDOM.ts
index 68c98a6591..04d65f8119 100644
--- a/packages/studio/src/player/lib/timelineDOM.ts
+++ b/packages/studio/src/player/lib/timelineDOM.ts
@@ -10,6 +10,7 @@
import type { TimelineElement } from "../store/playerStore";
import type { ClipManifestClip } from "./playbackTypes";
+import { resolveCssStackingContextId } from "@hyperframes/core/runtime/stacking-context";
import {
resolveMediaElement,
applyMediaMetadataFromElement,
@@ -228,6 +229,7 @@ export function createImplicitTimelineLayersFromDOM(
selector,
selectorIndex,
sourceFile,
+ stackingContextId: resolveCssStackingContextId(child),
start: 0,
tag: child.tagName.toLowerCase(),
timingSource: "implicit",
@@ -303,6 +305,7 @@ export function parseTimelineFromDOM(doc: Document, rootDuration: number): Timel
selector,
selectorIndex,
sourceFile,
+ stackingContextId: resolveCssStackingContextId(el),
timingSource: "authored",
zIndex: readTimelineElementZIndex(el),
};
diff --git a/packages/studio/src/player/lib/timelineElementHelpers.ts b/packages/studio/src/player/lib/timelineElementHelpers.ts
index 1a77589e76..08e125539c 100644
--- a/packages/studio/src/player/lib/timelineElementHelpers.ts
+++ b/packages/studio/src/player/lib/timelineElementHelpers.ts
@@ -10,6 +10,31 @@
import type { TimelineElement } from "../store/playerStore";
import type { ClipManifestClip } from "./playbackTypes";
import { isFinitePositive } from "./playbackAdapter";
+import { getSourceScopedSelectorIndex } from "../../utils/sourceScopedSelectorIndex";
+
+// ---------------------------------------------------------------------------
+// Layer-reveal lift transparency
+// ---------------------------------------------------------------------------
+
+/**
+ * Attributes carrying the pre-lift state of a Layers-panel selection reveal
+ * (useLayerRevealOverride): while a layer is selected it PAINTS on top via a
+ * temporary inline z-index, but the lift is a purely visual, ephemeral studio
+ * affordance — every z reader must keep reporting the element's TRUE z
+ * (stored here) so menus, badges, the lane mirror, and the panel sort never
+ * reason on the lifted value. A z-reorder commit removes the attributes (the
+ * commit is the new truth).
+ */
+export const LAYER_REVEAL_PRIOR_Z_ATTR = "data-hf-reveal-prior-z";
+export const LAYER_REVEAL_PRIOR_POSITION_ATTR = "data-hf-reveal-prior-pos";
+
+/** The lifted element's true (pre-lift) z, or null when no lift is active. */
+export function readLayerRevealPriorZ(el: Element): number | null {
+ const raw = el.getAttribute(LAYER_REVEAL_PRIOR_Z_ATTR);
+ if (raw == null) return null;
+ const n = Number.parseInt(raw, 10);
+ return Number.isFinite(n) ? n : null;
+}
// ---------------------------------------------------------------------------
// Duration attribute helpers
@@ -22,8 +47,11 @@ import { isFinitePositive } from "./playbackAdapter";
* back to computed style; "auto" / empty / unparseable ⇒ 0. Works with a
* detached parse Document (no defaultView) as well as a live iframe. Mirrors
* canvasContextMenuZOrder.parseZIndex semantics so the two directions agree.
+ * Reveal-lift transparent: an active lift reports the stored TRUE z.
*/
export function readTimelineElementZIndex(el: Element): number {
+ const prior = readLayerRevealPriorZ(el);
+ if (prior != null) return prior;
const html = el as HTMLElement;
const parseZ = (value: string | null | undefined): number | null => {
if (value == null || value === "" || value === "auto") return null;
@@ -237,17 +265,13 @@ export function getTimelineElementSelectorIndex(
el: Element,
selector: string | undefined,
): number | undefined {
- if (!selector || selector.startsWith("#") || selector.startsWith("[data-composition-id=")) {
- return undefined;
- }
-
- try {
- const matches = Array.from(doc.querySelectorAll(selector));
- const matchIndex = matches.indexOf(el);
- return matchIndex >= 0 ? matchIndex : undefined;
- } catch {
- return undefined;
- }
+ return getSourceScopedSelectorIndex(
+ doc,
+ el,
+ selector,
+ getTimelineElementSourceFile(el),
+ getTimelineElementSourceFile,
+ );
}
export function buildTimelineElementKey(params: {
diff --git a/packages/studio/src/player/store/playerStore.ts b/packages/studio/src/player/store/playerStore.ts
index 279c95a484..665a63beee 100644
--- a/packages/studio/src/player/store/playerStore.ts
+++ b/packages/studio/src/player/store/playerStore.ts
@@ -44,7 +44,7 @@ export interface TimelineElement {
zIndex?: number;
/** True when the effective z-index was authored inline or through CSS, not auto. */
hasExplicitZIndex?: boolean;
- /** Stacking context this element belongs to; root clips use the root composition id. */
+ /** Canonical CSS stacking context this element's z-index participates in. */
stackingContextId?: string | null;
/** Nearest parent composition context, matching RuntimeTimelineClip. */
parentCompositionId?: string | null;
@@ -124,6 +124,13 @@ interface PlayerState {
zoomMode: ZoomMode;
/** Timeline zoom percent relative to the fit width when in manual mode */
manualZoomPercent: number;
+ /**
+ * Bumped on every live z-index edit (handleDomZIndexReorderCommit apply AND
+ * rollback). Flashless z commits (skipReload) never reload the iframe or
+ * bump refreshKey, so DOM-derived views (the Layers panel's z-sorted tree)
+ * subscribe to this to re-read the live DOM while playback is paused.
+ */
+ zEditVersion: number;
/** Work-area in-point (seconds). When set, loop starts here and A jumps here. */
inPoint: number | null;
/** Work-area out-point (seconds). When set, loop ends here and E jumps here. */
@@ -212,6 +219,7 @@ interface PlayerState {
) => void;
setZoomMode: (mode: ZoomMode) => void;
setManualZoomPercent: (percent: number) => void;
+ bumpZEditVersion: () => void;
setInPoint: (time: number | null) => void;
setOutPoint: (time: number | null) => void;
reset: () => void;
@@ -274,6 +282,7 @@ export interface DomClipChild {
/** The manifest sub-comp host clip id this descendant ultimately lives under. */
hostId: string;
label: string;
+ stackingContextId: string;
}
interface BeatHistoryEntry {
@@ -308,6 +317,7 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({
loopEnabled: false,
zoomMode: "fit",
manualZoomPercent: 100,
+ zEditVersion: 0,
timelinePps: 100,
timelineFitPps: 100,
inPoint: null,
@@ -494,6 +504,7 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({
}),
setManualZoomPercent: (percent) =>
set({ manualZoomPercent: Math.max(10, Math.min(2000, Math.round(percent))) }),
+ bumpZEditVersion: () => set((state) => ({ zEditVersion: state.zEditVersion + 1 })),
setCurrentTime: (time) => set({ currentTime: Number.isFinite(time) ? time : 0 }),
setDuration: (duration) => set({ duration: Number.isFinite(duration) ? duration : 0 }),
setTimelineReady: (ready) => set({ timelineReady: ready }),
diff --git a/packages/studio/src/utils/domEditSaveQueue.ts b/packages/studio/src/utils/domEditSaveQueue.ts
index a3024892ee..79549ffd92 100644
--- a/packages/studio/src/utils/domEditSaveQueue.ts
+++ b/packages/studio/src/utils/domEditSaveQueue.ts
@@ -13,7 +13,7 @@ interface DomEditSaveQueueOptions {
}
export interface DomEditSaveQueue {
- enqueue: (save: () => Promise<void>) => Promise<void>;
+ enqueue: <T>(save: () => Promise<T>) => Promise<T>;
waitForIdle: () => Promise<void>;
reset: () => void;
destroy: () => void;
@@ -52,10 +52,11 @@ export function createDomEditSaveQueue(options: DomEditSaveQueueOptions = {}): D
});
};
- const run = async (save: () => Promise<void>) => {
+ const run = async <T>(save: () => Promise<T>): Promise<T> => {
try {
- await save();
+ const result = await save();
if (!breakerOpen) consecutiveFailures = 0;
+ return result;
} catch (error) {
consecutiveFailures += 1;
if (consecutiveFailures >= failureThreshold) open(error);
diff --git a/packages/studio/src/utils/editHistory.test.ts b/packages/studio/src/utils/editHistory.test.ts
index 86a3a32e1c..cfd1d1f48d 100644
--- a/packages/studio/src/utils/editHistory.test.ts
+++ b/packages/studio/src/utils/editHistory.test.ts
@@ -277,6 +277,88 @@ describe("edit history", () => {
expect(state.undo[0].files["index.html"].after).toBe("timing+gsap");
});
+ it("keeps timing-only files when a multi-file GSAP follow-up touches one path", () => {
+ const timing = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Move timeline clips",
+ kind: "timeline",
+ coalesceKey: "timeline-group-move:a,b",
+ files: {
+ "index.html": { before: "index-before", after: "index-timing" },
+ "scene.html": { before: "scene-before", after: "scene-timing" },
+ },
+ now: 0,
+ id: "timing",
+ });
+ const gsap = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Move timeline clips",
+ kind: "timeline",
+ coalesceKey: "timeline-group-move:a,b",
+ coalesceMs: 10_000,
+ files: {
+ "index.html": { before: "index-timing", after: "index-timing+gsap" },
+ },
+ now: 2000,
+ id: "gsap",
+ });
+
+ const state = pushEditHistoryEntry(
+ pushEditHistoryEntry(createEmptyEditHistory(), timing),
+ gsap,
+ );
+
+ expect(state.undo).toHaveLength(1);
+ expect(Object.keys(state.undo[0].files)).toEqual(["index.html", "scene.html"]);
+ expect(state.undo[0].files).toMatchObject({
+ "index.html": { before: "index-before", after: "index-timing+gsap" },
+ "scene.html": { before: "scene-before", after: "scene-timing" },
+ });
+ });
+
+ it("keeps a discontinuous GSAP follow-up separate and preserves foreign bytes on undo", () => {
+ const timing = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Move timeline clip",
+ kind: "timeline",
+ coalesceKey: "timeline-move:clip",
+ files: { "index.html": { before: "A", after: "B" } },
+ now: 0,
+ id: "timing",
+ });
+ const gsapAfterForeignWrite = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Move timeline clip",
+ kind: "timeline",
+ coalesceKey: "timeline-move:clip",
+ coalesceMs: 10_000,
+ files: { "index.html": { before: "F", after: "G" } },
+ now: 2000,
+ id: "gsap",
+ });
+
+ const state = pushEditHistoryEntry(
+ pushEditHistoryEntry(createEmptyEditHistory(), timing),
+ gsapAfterForeignWrite,
+ );
+
+ expect(state.undo.map((entry) => entry.id)).toEqual(["timing", "gsap"]);
+ const undoGsap = undoEditHistory(state, { "index.html": hashEditHistoryContent("G") }, 3000);
+ expect(undoGsap.ok).toBe(true);
+ expect(undoGsap.filesToWrite).toEqual({ "index.html": "F" });
+
+ const undoTiming = undoEditHistory(
+ undoGsap.state,
+ { "index.html": hashEditHistoryContent("F") },
+ 4000,
+ );
+ expect(undoTiming).toMatchObject({
+ ok: false,
+ reason: "content-mismatch",
+ filesToWrite: {},
+ });
+ });
+
it("does not merge a slow follow-up without the coalesceMs override", () => {
const timing = buildEditHistoryEntry({
projectId: "project-1",
diff --git a/packages/studio/src/utils/editHistory.ts b/packages/studio/src/utils/editHistory.ts
index a5f938ce51..85a42f8b7b 100644
--- a/packages/studio/src/utils/editHistory.ts
+++ b/packages/studio/src/utils/editHistory.ts
@@ -126,9 +126,21 @@ export function pushEditHistoryEntry(
previous &&
previous.coalesceKey &&
previous.coalesceKey === entry.coalesceKey &&
- entry.createdAt - previous.createdAt <= coalesceMs
+ entry.createdAt - previous.createdAt <= coalesceMs &&
+ // A shared key/window is not enough: bytes from an external writer may
+ // have landed between the two Studio-owned edits. Only fold a path when
+ // the follow-up starts from the exact output the previous entry recorded.
+ // Otherwise keep both entries so undo restores the foreign bytes first and
+ // the older entry's content check safely blocks at that ownership boundary.
+ Object.entries(entry.files).every(([path, snapshot]) => {
+ const previousSnapshot = previous.files[path];
+ return !previousSnapshot || previousSnapshot.after === snapshot.before;
+ })
) {
- const files: Record<string, EditHistoryFileSnapshot> = {};
+ // A follow-up may touch only a subset of the files in the original edit
+ // (for example, only one file in a multi-file timing move has GSAP). Keep
+ // previous-only paths in the single coalesced undo entry.
+ const files: Record<string, EditHistoryFileSnapshot> = { ...previous.files };
for (const [path, snapshot] of Object.entries(entry.files)) {
const previousSnapshot = previous.files[path];
files[path] = previousSnapshot
diff --git a/packages/studio/src/utils/gsapSoftReload.test.ts b/packages/studio/src/utils/gsapSoftReload.test.ts
index 6dae557369..c2178e5f85 100644
--- a/packages/studio/src/utils/gsapSoftReload.test.ts
+++ b/packages/studio/src/utils/gsapSoftReload.test.ts
@@ -3,9 +3,8 @@
import { describe, it, expect, vi } from "vitest";
import {
applySoftReload,
+ applySoftReloadFinalization,
ensureMotionPathPluginLoaded,
- diffSoftReloadableRestore,
- applyUndoRestoreToPreview,
} from "./gsapSoftReload";
const SCRIPT_TEXT = `
@@ -66,6 +65,7 @@ function buildMockIframe(overrides: Record<string, unknown> = {}) {
iframe: { contentWindow, contentDocument } as unknown as HTMLIFrameElement,
contentWindow,
mockTimeline,
+ container,
};
}
@@ -288,6 +288,58 @@ describe("applySoftReload", () => {
});
});
+// ── Finalization-only path: seek → rebind → manual edits, with NO script
+// execution — the flashless sync for timing edits that changed no script.
+describe("applySoftReloadFinalization", () => {
+ it("seeks, rebinds, and reapplies manual edits without touching any script", () => {
+ const { iframe, contentWindow, container, mockTimeline } = buildMockIframe();
+ const scriptsBefore = container.querySelectorAll("script").length;
+
+ expect(applySoftReloadFinalization(iframe, 2.0)).toBe(true);
+
+ expect(contentWindow.__player.seek).toHaveBeenCalledWith(2.0);
+ expect(contentWindow.__hfForceTimelineRebind).toHaveBeenCalledTimes(1);
+ expect(contentWindow.__hfStudioManualEditsApply).toHaveBeenCalledTimes(1);
+ // No script executed or removed; the live timeline was never killed.
+ expect(container.querySelectorAll("script").length).toBe(scriptsBefore);
+ expect(mockTimeline.kill).not.toHaveBeenCalled();
+ expect(contentWindow.__timelines.root).toBe(mockTimeline);
+ });
+
+ it("runs inside __hfSuppressSceneMutations when the runtime provides it", () => {
+ const suppress = vi.fn(<T>(fn: () => T): T => fn());
+ const { iframe, contentWindow } = buildMockIframe({
+ __hfSuppressSceneMutations: suppress,
+ });
+
+ expect(applySoftReloadFinalization(iframe, 1.5)).toBe(true);
+
+ expect(suppress).toHaveBeenCalledTimes(1);
+ expect(contentWindow.__hfForceTimelineRebind).toHaveBeenCalledTimes(1);
+ });
+
+ it("does NOT require gsap — a script-less runtime with the rebind hook works", () => {
+ const { iframe, contentWindow } = buildMockIframe({ gsap: undefined });
+ expect(applySoftReloadFinalization(iframe, 0)).toBe(true);
+ expect(contentWindow.__hfForceTimelineRebind).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns false when the iframe or the rebind hook is unavailable", () => {
+ expect(applySoftReloadFinalization(null, 0)).toBe(false);
+ const { iframe } = buildMockIframe({ __hfForceTimelineRebind: undefined });
+ expect(applySoftReloadFinalization(iframe, 0)).toBe(false);
+ });
+
+ it("returns false when the rebind throws (caller full-reloads)", () => {
+ const { iframe } = buildMockIframe({
+ __hfForceTimelineRebind: vi.fn(() => {
+ throw new Error("runtime mid-teardown");
+ }),
+ });
+ expect(applySoftReloadFinalization(iframe, 0)).toBe(false);
+ });
+});
+
function buildBootstrapIframe(overrides: Record<string, unknown> = {}) {
const head = document.createElement("div");
const appendedScripts: HTMLScriptElement[] = [];
@@ -452,116 +504,3 @@ describe("applySoftReload authored-opacity restore", () => {
expect(restoreOpacity(el)).toBe("");
});
});
-
-// ── Bug 2: undo/redo restore soft-apply ──────────────────────────────────────
-
-const wrap = (body: string) => `<html><body>${body}</body></html>`;
-
-describe("diffSoftReloadableRestore", () => {
- it("reports the changed id for an attribute/inline-style-only diff", () => {
- const prev = wrap(`<div id="a" style="translate: 10px 10px">t</div>`);
- const next = wrap(`<div id="a" style="translate: 0px 0px">t</div>`);
- expect(diffSoftReloadableRestore(prev, next)).toEqual({ changedElementIds: ["a"] });
- });
-
- it("treats a structural change (added element) as NOT soft-reloadable", () => {
- const prev = wrap(`<div id="a">t</div>`);
- const next = wrap(`<div id="a">t</div><div id="a-split">t</div>`);
- expect(diffSoftReloadableRestore(prev, next)).toBeNull();
- });
-
- it("treats an element text/child change as NOT soft-reloadable", () => {
- const prev = wrap(`<div id="a">one</div>`);
- const next = wrap(`<div id="a">two</div>`);
- expect(diffSoftReloadableRestore(prev, next)).toBeNull();
- });
-
- it("allows a GSAP-script-only change (no id'd-attribute diff)", () => {
- const prev = wrap(
- `<div id="a">t</div><script>window.__timelines["root"]=gsap.timeline().to("#a",{x:1});</script>`,
- );
- const next = wrap(
- `<div id="a">t</div><script>window.__timelines["root"]=gsap.timeline().to("#a",{x:9});</script>`,
- );
- expect(diffSoftReloadableRestore(prev, next)).toEqual({ changedElementIds: [] });
- });
-});
-
-function buildLiveIframe(bodyHtml: string) {
- const doc = document.implementation.createHTMLDocument("");
- doc.body.innerHTML = bodyHtml;
- const contentWindow = {
- gsap: { timeline: () => {} },
- __hfForceTimelineRebind: () => {},
- __timelines: {} as Record<string, unknown>,
- __player: { getTime: () => 3, seek: vi.fn() },
- __hfStudioManualEditsApply: vi.fn(),
- };
- return {
- iframe: { contentWindow, contentDocument: doc } as unknown as HTMLIFrameElement,
- contentWindow,
- doc,
- };
-}
-
-describe("applyUndoRestoreToPreview", () => {
- const ROOT = "index.html";
-
- it("soft-applies an attribute/style-only restore: syncs the live element, no full reload", () => {
- const { iframe, contentWindow, doc } = buildLiveIframe(
- `<div id="a" style="translate: 10px 10px" data-hf-path-offset="true">t</div>`,
- );
- const reloadPreview = vi.fn();
- const files = {
- [ROOT]: {
- previous: wrap(
- `<div id="a" style="translate: 10px 10px" data-hf-path-offset="true">t</div>`,
- ),
- restored: wrap(`<div id="a" style="translate: 0px 0px" data-hf-path-offset="true">t</div>`),
- },
- };
- const outcome = applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview);
- expect(outcome).toBe("soft");
- expect(reloadPreview).not.toHaveBeenCalled();
- // Live element reverted to the restored inline style.
- expect(doc.getElementById("a")!.getAttribute("style")).toBe("translate: 0px 0px");
- // No GSAP script in the restore → the manual-edit reapply runs, playhead held.
- expect(contentWindow.__player.seek).toHaveBeenCalledWith(3);
- expect(contentWindow.__hfStudioManualEditsApply).toHaveBeenCalled();
- });
-
- it("full-reloads a multi-file restore", () => {
- const { iframe } = buildLiveIframe(`<div id="a">t</div>`);
- const reloadPreview = vi.fn();
- const files = {
- [ROOT]: {
- previous: wrap(`<div id="a" style="x">t</div>`),
- restored: wrap(`<div id="a">t</div>`),
- },
- "scenes/intro.html": { previous: "a", restored: "b" },
- };
- expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview)).toBe("full");
- expect(reloadPreview).toHaveBeenCalledTimes(1);
- });
-
- it("full-reloads a structural restore (split/delete undo)", () => {
- const { iframe } = buildLiveIframe(`<div id="a">t</div><div id="a-split">t</div>`);
- const reloadPreview = vi.fn();
- const files = {
- [ROOT]: {
- previous: wrap(`<div id="a">t</div><div id="a-split">t</div>`),
- restored: wrap(`<div id="a">t</div>`),
- },
- };
- expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview)).toBe("full");
- expect(reloadPreview).toHaveBeenCalledTimes(1);
- });
-
- it("full-reloads when the restore touches a sub-comp, not the active comp", () => {
- const { iframe } = buildLiveIframe(`<div id="a">t</div>`);
- const reloadPreview = vi.fn();
- const files = { "scenes/intro.html": { previous: "a", restored: "b" } };
- expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview)).toBe("full");
- expect(reloadPreview).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/packages/studio/src/utils/gsapSoftReload.ts b/packages/studio/src/utils/gsapSoftReload.ts
index cf265b891a..71b624276d 100644
--- a/packages/studio/src/utils/gsapSoftReload.ts
+++ b/packages/studio/src/utils/gsapSoftReload.ts
@@ -90,7 +90,7 @@ function isGsapScript(text: string): boolean {
);
}
-function findGsapScriptElements(doc: Document): HTMLScriptElement[] {
+export function findGsapScriptElements(doc: Document): HTMLScriptElement[] {
const results: HTMLScriptElement[] = [];
const scripts = doc.querySelectorAll<HTMLScriptElement>("script:not([src])");
for (const script of scripts) {
@@ -102,8 +102,9 @@ function findGsapScriptElements(doc: Document): HTMLScriptElement[] {
/**
* Extract the GSAP timeline script text from a serialized HTML document, for
* feeding into applySoftReload. Returns null when zero or multiple GSAP scripts
- * are present (ambiguous — caller should fall back to a full reload), matching
- * applySoftReload's own single-script requirement.
+ * are present (ambiguous — a serialized snapshot can't say WHICH script a
+ * single rewritten text corresponds to; caller should fall back to a full
+ * reload), matching applySoftReload's own single-script requirement.
*/
export function extractGsapScriptText(html: string): string | null {
const doc = new DOMParser().parseFromString(html, "text/html");
@@ -183,157 +184,53 @@ export interface SoftReloadOptions {
authoredHtml?: string;
}
-/** One file's restore from the edit-history store: before (live) / after (target) bytes. */
-export interface UndoRestoreFile {
- previous: string;
- restored: string;
-}
-function idElementMap(doc: Document): Map<string, Element> {
- const map = new Map<string, Element>();
- for (const el of doc.querySelectorAll("[id]")) {
- const id = el.getAttribute("id");
- if (id) map.set(id, el);
- }
- return map;
-}
-
-// Strip id'd elements to bare `id` and blank GSAP scripts, in place: docs that
-// differ only in id'd attributes/inline-style/script text normalize equal; any
-// residual difference is beyond soft-reload's reach → caller full-reloads.
-function normalizeSoftResidual(doc: Document): void {
- for (const el of doc.querySelectorAll("[id]")) {
- const id = el.getAttribute("id");
- for (const name of [...el.getAttributeNames()]) {
- if (name !== "id") el.removeAttribute(name);
- }
- if (id) el.setAttribute("id", id);
- }
- for (const script of findGsapScriptElements(doc)) script.textContent = "";
-}
-
-// Soft-reloadable iff the docs differ SOLELY in id'd-element attributes/inline
-// style and/or the GSAP script; returns the changed ids to sync onto the live
-// DOM. Structural/text diffs → null → the caller full-reloads. Pure.
-export function diffSoftReloadableRestore(
- previous: string,
- restored: string,
-): { changedElementIds: string[] } | null {
- let prevDoc: Document;
- let nextDoc: Document;
- try {
- prevDoc = new DOMParser().parseFromString(previous, "text/html");
- nextDoc = new DOMParser().parseFromString(restored, "text/html");
- } catch {
- return null;
- }
- const prevById = idElementMap(prevDoc);
- const nextById = idElementMap(nextDoc);
- // A different id set means an element was added or removed (e.g. a split, a
- // delete) — structural, so soft-reload can't express it.
- if (prevById.size !== nextById.size) return null;
- const changedElementIds: string[] = [];
- for (const [id, nextEl] of nextById) {
- const prevEl = prevById.get(id);
- if (!prevEl || prevEl.tagName !== nextEl.tagName) return null;
- // A change inside the element (text / children) is out of soft scope; only
- // its own attributes may differ. (GSAP scripts are handled via re-run.)
- if (prevEl.innerHTML !== nextEl.innerHTML) return null;
- if (prevEl.outerHTML !== nextEl.outerHTML) changedElementIds.push(id);
- }
- // Confirm nothing OUTSIDE id'd-element attributes and GSAP scripts changed.
- normalizeSoftResidual(prevDoc);
- normalizeSoftResidual(nextDoc);
- if (prevDoc.documentElement.outerHTML !== nextDoc.documentElement.outerHTML) return null;
- return { changedElementIds };
-}
-
-/** Copy every attribute from `source` onto the live `target`, dropping extras. */
-function syncElementAttributes(target: Element, source: Element): void {
- for (const name of [...target.getAttributeNames()]) {
- if (!source.hasAttribute(name)) target.removeAttribute(name);
- }
- for (const name of source.getAttributeNames()) {
- target.setAttribute(name, source.getAttribute(name) ?? "");
- }
+/**
+ * The soft reload's finalization step, shared with the rebind-only preview sync
+ * below: seek → force timeline rebind → reapply studio manual edits.
+ *
+ * Seek BEFORE rebind: __hfForceTimelineRebind's own internal force-render
+ * (see init.ts) renders the freshly-created timeline at whatever the
+ * runtime's internal scrub position already is, not at whatever we pass
+ * here afterward — a redundant seek() call after rebind can be a GSAP
+ * no-op if the timeline already reports being at that time internally.
+ */
+function finalizeSoftReload(win: IframeWindow, currentTime: number): void {
+ win.__player?.seek?.(currentTime);
+ win.__hfForceTimelineRebind?.();
+ win.__hfStudioManualEditsApply?.();
}
/**
- * Soft-apply an undo/redo restore to the live preview WITHOUT a full iframe
- * remount (which blanks the frame black and re-flashes the WebGL context). Only
- * the active composition — the document living in the root iframe — is eligible;
- * a sub-comp or multi-file restore falls back to `reloadPreview`.
+ * Run ONLY applySoftReload's finalization (seek → __hfForceTimelineRebind →
+ * manual-edits reapply) against the live iframe — executing NO scripts and
+ * touching NO script elements. `__hfForceTimelineRebind` makes the runtime
+ * re-derive every clip's visibility window from the live DOM's `data-start` /
+ * `data-duration` attributes (init.ts: bindRootTimelineIfAvailable +
+ * syncTimedElementVisibility), so this is the flashless sync for a timing edit
+ * whose attributes were already live-patched and whose GSAP scripts are
+ * unchanged (`window.__timelines` still valid). Works for compositions with
+ * zero GSAP scripts too — the rebind hook is installed unconditionally by the
+ * runtime, independent of any animation library.
*
- * The restore is soft-applied when its only differences are id'd-element
- * attributes / inline-style and/or the GSAP script (see diffSoftReloadableRestore):
- * 1. Each changed element's attribute surface (inline style, data-start /
- * -duration, the studio manual-offset props + flags) is synced onto the live
- * element — so a canvas-position revert lands on the live DOM the runtime's
- * seek-reapply reads from, not just on disk.
- * 2. The restored GSAP script is re-run in place via applySoftReload, which
- * re-seeks to `currentTime` (playhead-invariant) and re-folds manual edits.
- * With no single script, the manual-edit reapply is invoked directly.
- *
- * Returns "soft" when applied in place, "full" when it escalated to reloadPreview
- * (ineligible restore, missing target, or a permanent soft-reload failure).
+ * Returns false when the iframe/runtime hook is unavailable or the run threw —
+ * the caller should escalate to a full reload.
*/
-export function applyUndoRestoreToPreview(
+export function applySoftReloadFinalization(
iframe: HTMLIFrameElement | null,
- activeCompPath: string | null,
- files: Record<string, UndoRestoreFile> | undefined,
currentTime: number,
- reloadPreview: () => void,
-): "soft" | "full" {
- const paths = files ? Object.keys(files) : [];
- // Soft path only covers the single active-comp document in the root iframe.
- if (!iframe || !activeCompPath || !files || paths.length !== 1 || paths[0] !== activeCompPath) {
- reloadPreview();
- return "full";
- }
- const doc = iframe.contentDocument;
- const win = iframe.contentWindow as IframeWindow | null;
- if (!doc || !win) {
- reloadPreview();
- return "full";
- }
- const { previous, restored } = files[activeCompPath]!;
- const diff = diffSoftReloadableRestore(previous, restored);
- if (!diff) {
- reloadPreview();
- return "full";
- }
-
- // Sync each changed element's attributes onto the live DOM from the restored
- // markup, so the runtime's seek-reapply (which reads inline offset props off
- // the live element) folds the REVERTED values, not the stale current ones.
- const restoredById = idElementMap(new DOMParser().parseFromString(restored, "text/html"));
- for (const id of diff.changedElementIds) {
- const liveEl = doc.getElementById(id);
- const restoredEl = restoredById.get(id);
- if (liveEl && restoredEl) syncElementAttributes(liveEl, restoredEl);
- }
-
- const script = extractGsapScriptText(restored);
- if (script) {
- const result = applySoftReload(iframe, script, {
- onAsyncFailure: reloadPreview,
- currentTimeOverride: currentTime,
- });
- if (result === "cannot-soft-reload") {
- reloadPreview();
- return "full";
- }
- return "soft";
- }
- // No single GSAP script to re-run — the change was pure attribute/style. Re-fold
- // manual edits and hold the playhead so the synced attributes take visible effect.
+): boolean {
+ const win = iframe?.contentWindow as IframeWindow | null;
+ if (!win?.__hfForceTimelineRebind) return false;
try {
- win.__player?.seek?.(currentTime);
- win.__hfStudioManualEditsApply?.();
+ if (win.__hfSuppressSceneMutations) {
+ win.__hfSuppressSceneMutations(() => finalizeSoftReload(win, currentTime));
+ } else {
+ finalizeSoftReload(win, currentTime);
+ }
+ return true;
} catch {
- reloadPreview();
- return "full";
+ return false;
}
- return "soft";
}
export function applySoftReload(
@@ -523,14 +420,7 @@ export function applySoftReload(
const s = doc.createElement("script");
s.textContent = `(function(){${scriptText}\n})();`;
doc.body.appendChild(s);
- // Seek BEFORE rebind: __hfForceTimelineRebind's own internal force-render
- // (see init.ts) renders the freshly-created timeline at whatever the
- // runtime's internal scrub position already is, not at whatever we pass
- // here afterward — a redundant seek() call after rebind can be a GSAP
- // no-op if the timeline already reports being at that time internally.
- win.__player?.seek?.(currentTime);
- win.__hfForceTimelineRebind?.();
- win.__hfStudioManualEditsApply?.();
+ finalizeSoftReload(win, currentTime);
};
const needsMotionPath = /motionPath\s*[:{]/.test(scriptText);
diff --git a/packages/studio/src/utils/gsapUndoRestore.test.ts b/packages/studio/src/utils/gsapUndoRestore.test.ts
new file mode 100644
index 0000000000..2c8aa6296b
--- /dev/null
+++ b/packages/studio/src/utils/gsapUndoRestore.test.ts
@@ -0,0 +1,269 @@
+// @vitest-environment happy-dom
+
+import { describe, it, expect, vi } from "vitest";
+import { applyUndoRestoreToPreview, diffSoftReloadableRestore } from "./gsapUndoRestore";
+
+// ── Bug 2: undo/redo restore soft-apply ──────────────────────────────────────
+
+const wrap = (body: string) => `<html><body>${body}</body></html>`;
+
+describe("diffSoftReloadableRestore", () => {
+ it("reports the changed id for an attribute/inline-style-only diff", () => {
+ const prev = wrap(`<div id="a" style="translate: 10px 10px">t</div>`);
+ const next = wrap(`<div id="a" style="translate: 0px 0px">t</div>`);
+ expect(diffSoftReloadableRestore(prev, next)).toEqual({ changedElementKeys: ["id:a"] });
+ });
+
+ it("identifies id-less elements by data-hf-id (selector-targeted clips)", () => {
+ const prev = wrap(`<div class="sub" data-hf-id="hf-x1" style="z-index: 3">t</div>`);
+ const next = wrap(`<div class="sub" data-hf-id="hf-x1" style="z-index: 8">t</div>`);
+ expect(diffSoftReloadableRestore(prev, next)).toEqual({ changedElementKeys: ["hf:hf-x1"] });
+ });
+
+ it("fails closed when fallback ids are duplicated without unique data-hf-ids", () => {
+ const prev = wrap(
+ `<div id="dup" style="z-index: 8">first</div><div id="dup" style="z-index: 9">last</div>`,
+ );
+ const next = wrap(
+ `<div id="dup" style="z-index: 3">first</div><div id="dup" style="z-index: 9">last</div>`,
+ );
+ expect(diffSoftReloadableRestore(prev, next)).toBeNull();
+ });
+
+ it("a child change inside an identified CONTAINER is soft (nested identities)", () => {
+ // The composition root wraps every clip — the old innerHTML comparison at
+ // the root re-detected the child's change and forced a full reload.
+ const prev = wrap(
+ `<div id="main" data-duration="42"><div class="sub" data-hf-id="hf-x1" data-start="39">t</div></div>`,
+ );
+ const next = wrap(
+ `<div id="main" data-duration="39"><div class="sub" data-hf-id="hf-x1" data-start="26">t</div></div>`,
+ );
+ expect(diffSoftReloadableRestore(prev, next)).toEqual({
+ changedElementKeys: ["id:main", "hf:hf-x1"],
+ });
+ });
+
+ it("a changed data-hf-id itself is structural — NOT soft-reloadable", () => {
+ const prev = wrap(`<div data-hf-id="hf-x1">t</div>`);
+ const next = wrap(`<div data-hf-id="hf-x2">t</div>`);
+ expect(diffSoftReloadableRestore(prev, next)).toBeNull();
+ });
+
+ it("treats a structural change (added element) as NOT soft-reloadable", () => {
+ const prev = wrap(`<div id="a">t</div>`);
+ const next = wrap(`<div id="a">t</div><div id="a-split">t</div>`);
+ expect(diffSoftReloadableRestore(prev, next)).toBeNull();
+ });
+
+ it("treats an element text/child change as NOT soft-reloadable", () => {
+ const prev = wrap(`<div id="a">one</div>`);
+ const next = wrap(`<div id="a">two</div>`);
+ expect(diffSoftReloadableRestore(prev, next)).toBeNull();
+ });
+
+ it("allows a GSAP-script-only change (no id'd-attribute diff)", () => {
+ const prev = wrap(
+ `<div id="a">t</div><script>window.__timelines["root"]=gsap.timeline().to("#a",{x:1});</script>`,
+ );
+ const next = wrap(
+ `<div id="a">t</div><script>window.__timelines["root"]=gsap.timeline().to("#a",{x:9});</script>`,
+ );
+ expect(diffSoftReloadableRestore(prev, next)).toEqual({ changedElementKeys: [] });
+ });
+});
+
+function buildLiveIframe(bodyHtml: string) {
+ const doc = document.implementation.createHTMLDocument("");
+ doc.body.innerHTML = bodyHtml;
+ const contentWindow = {
+ gsap: { timeline: () => {} },
+ __hfForceTimelineRebind: () => {},
+ __timelines: {} as Record<string, unknown>,
+ __player: { getTime: () => 3, seek: vi.fn() },
+ __hfStudioManualEditsApply: vi.fn(),
+ };
+ return {
+ iframe: { contentWindow, contentDocument: doc } as unknown as HTMLIFrameElement,
+ contentWindow,
+ doc,
+ };
+}
+
+describe("applyUndoRestoreToPreview", () => {
+ const ROOT = "index.html";
+
+ it("soft-applies an attribute/style-only restore: syncs the live element, no full reload", () => {
+ const { iframe, contentWindow, doc } = buildLiveIframe(
+ `<div id="a" style="translate: 10px 10px" data-hf-path-offset="true">t</div>`,
+ );
+ const reloadPreview = vi.fn();
+ const files = {
+ [ROOT]: {
+ previous: wrap(
+ `<div id="a" style="translate: 10px 10px" data-hf-path-offset="true">t</div>`,
+ ),
+ restored: wrap(`<div id="a" style="translate: 0px 0px" data-hf-path-offset="true">t</div>`),
+ },
+ };
+ const outcome = applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview);
+ expect(outcome).toBe("soft");
+ expect(reloadPreview).not.toHaveBeenCalled();
+ // Live element reverted to the restored inline style.
+ expect(doc.getElementById("a")!.getAttribute("style")).toBe("translate: 0px 0px");
+ // No GSAP script in the restore → the manual-edit reapply runs, playhead held.
+ expect(contentWindow.__player.seek).toHaveBeenCalledWith(3);
+ expect(contentWindow.__hfStudioManualEditsApply).toHaveBeenCalled();
+ });
+
+ it("syncs a data-hf-id-identified live element (no DOM id) without reloading", () => {
+ const { iframe, doc } = buildLiveIframe(
+ `<div class="sub" data-hf-id="hf-x1" style="z-index: 8">t</div>`,
+ );
+ const reloadPreview = vi.fn();
+ const files = {
+ [ROOT]: {
+ previous: wrap(`<div class="sub" data-hf-id="hf-x1" style="z-index: 8">t</div>`),
+ restored: wrap(`<div class="sub" data-hf-id="hf-x1" style="z-index: 3">t</div>`),
+ },
+ };
+ expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview)).toBe("soft");
+ expect(reloadPreview).not.toHaveBeenCalled();
+ expect(doc.querySelector('[data-hf-id="hf-x1"]')!.getAttribute("style")).toBe("z-index: 3");
+ });
+
+ it.each([
+ { label: "first", firstRestored: 3, lastRestored: 9 },
+ { label: "last", firstRestored: 8, lastRestored: 3 },
+ ])(
+ "soft-restores the $label element when authored ids are duplicated",
+ ({ firstRestored, lastRestored }) => {
+ const markup = (firstZ: number, lastZ: number) =>
+ `<div id="dup" data-hf-id="hf-first" style="z-index: ${firstZ}">first</div>` +
+ `<div id="dup" data-hf-id="hf-last" style="z-index: ${lastZ}">last</div>`;
+ const { iframe, doc } = buildLiveIframe(markup(8, 9));
+ const reloadPreview = vi.fn();
+ const files = {
+ [ROOT]: {
+ previous: wrap(markup(8, 9)),
+ restored: wrap(markup(firstRestored, lastRestored)),
+ },
+ };
+
+ expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview)).toBe("soft");
+ expect(reloadPreview).not.toHaveBeenCalled();
+ expect(doc.querySelector('[data-hf-id="hf-first"]')!.getAttribute("style")).toBe(
+ `z-index: ${firstRestored}`,
+ );
+ expect(doc.querySelector('[data-hf-id="hf-last"]')!.getAttribute("style")).toBe(
+ `z-index: ${lastRestored}`,
+ );
+ },
+ );
+
+ it("full-reloads without partially restoring when any changed live target is missing", () => {
+ const { iframe, doc } = buildLiveIframe(`<div id="a" style="z-index: 8">a</div>`);
+ const reloadPreview = vi.fn();
+ const files = {
+ [ROOT]: {
+ previous: wrap(
+ `<div id="a" style="z-index: 8">a</div><div id="b" style="z-index: 8">b</div>`,
+ ),
+ restored: wrap(
+ `<div id="a" style="z-index: 3">a</div><div id="b" style="z-index: 3">b</div>`,
+ ),
+ },
+ };
+
+ expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview)).toBe("full");
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ // Target a resolved first, but the preflight found missing b before syncing either.
+ expect(doc.getElementById("a")!.getAttribute("style")).toBe("z-index: 8");
+ });
+
+ it("does NOT re-run an UNCHANGED GSAP script for an attribute-only restore", () => {
+ // The live doc holds a script element; a re-run would mutate/remove it
+ // (applySoftReload removes stale script elements before re-running).
+ const script = `window.__timelines["root"]=gsap.timeline().to("#a",{x:1});`;
+ const { iframe, contentWindow, doc } = buildLiveIframe(
+ `<div id="a" style="z-index: 8">t</div><script>${script}</script>`,
+ );
+ const reloadPreview = vi.fn();
+ const files = {
+ [ROOT]: {
+ previous: wrap(`<div id="a" style="z-index: 8">t</div><script>${script}</script>`),
+ restored: wrap(`<div id="a" style="z-index: 3">t</div><script>${script}</script>`),
+ },
+ };
+ expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview)).toBe("soft");
+ expect(reloadPreview).not.toHaveBeenCalled();
+ // The live script element is untouched — rebind-only finalization ran instead.
+ expect(doc.querySelectorAll("script")).toHaveLength(1);
+ expect(doc.querySelector("script")!.textContent).toBe(script);
+ expect(contentWindow.__player.seek).toHaveBeenCalledWith(3);
+ expect(contentWindow.__hfStudioManualEditsApply).toHaveBeenCalled();
+ expect(doc.getElementById("a")!.getAttribute("style")).toBe("z-index: 3");
+ });
+
+ it("full-reloads a changed two-script restore without partially touching the live DOM", () => {
+ const previousScripts = [
+ `window.__timelines["root"]=gsap.timeline().to("#a",{x:1});`,
+ `window.__timelines["captions"]=gsap.timeline().to("#a",{y:1});`,
+ ];
+ const restoredScripts = previousScripts.map((script) => script.replace(":1", ":9"));
+ const scripts = (values: string[]) =>
+ values.map((value) => `<script>${value}</script>`).join("");
+ const { iframe, doc } = buildLiveIframe(
+ `<div id="a" style="z-index: 8">t</div>${scripts(previousScripts)}`,
+ );
+ const reloadPreview = vi.fn();
+ const files = {
+ [ROOT]: {
+ previous: wrap(`<div id="a" style="z-index: 8">t</div>${scripts(previousScripts)}`),
+ restored: wrap(`<div id="a" style="z-index: 3">t</div>${scripts(restoredScripts)}`),
+ },
+ };
+
+ expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview)).toBe("full");
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ expect(doc.getElementById("a")!.getAttribute("style")).toBe("z-index: 8");
+ expect([...doc.querySelectorAll("script")].map((script) => script.textContent)).toEqual(
+ previousScripts,
+ );
+ });
+
+ it("full-reloads a multi-file restore", () => {
+ const { iframe } = buildLiveIframe(`<div id="a">t</div>`);
+ const reloadPreview = vi.fn();
+ const files = {
+ [ROOT]: {
+ previous: wrap(`<div id="a" style="x">t</div>`),
+ restored: wrap(`<div id="a">t</div>`),
+ },
+ "scenes/intro.html": { previous: "a", restored: "b" },
+ };
+ expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview)).toBe("full");
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ });
+
+ it("full-reloads a structural restore (split/delete undo)", () => {
+ const { iframe } = buildLiveIframe(`<div id="a">t</div><div id="a-split">t</div>`);
+ const reloadPreview = vi.fn();
+ const files = {
+ [ROOT]: {
+ previous: wrap(`<div id="a">t</div><div id="a-split">t</div>`),
+ restored: wrap(`<div id="a">t</div>`),
+ },
+ };
+ expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview)).toBe("full");
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ });
+
+ it("full-reloads when the restore touches a sub-comp, not the active comp", () => {
+ const { iframe } = buildLiveIframe(`<div id="a">t</div>`);
+ const reloadPreview = vi.fn();
+ const files = { "scenes/intro.html": { previous: "a", restored: "b" } };
+ expect(applyUndoRestoreToPreview(iframe, ROOT, files, 3, reloadPreview)).toBe("full");
+ expect(reloadPreview).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/studio/src/utils/gsapUndoRestore.ts b/packages/studio/src/utils/gsapUndoRestore.ts
new file mode 100644
index 0000000000..fe2f622219
--- /dev/null
+++ b/packages/studio/src/utils/gsapUndoRestore.ts
@@ -0,0 +1,269 @@
+// Soft-apply of undo/redo restores to the live preview: diff a restored file
+// against the live one, sync attribute-only changes onto the live DOM, and
+// refresh the runtime in place — avoiding the full iframe remount (black flash
+// + WebGL context loss) whenever the restore is expressible without one.
+import {
+ applySoftReload,
+ applySoftReloadFinalization,
+ extractGsapScriptText,
+ findGsapScriptElements,
+} from "./gsapSoftReload";
+
+type PreviewWindow = Window & {
+ __player?: { seek?: (t: number) => void };
+ __hfStudioManualEditsApply?: () => void;
+};
+
+/** One file's restore from the edit-history store: before (live) / after (target) bytes. */
+export interface UndoRestoreFile {
+ previous: string;
+ restored: string;
+}
+
+/**
+ * Identity for the soft diff: `data-hf-id` when present, else `id`. Nearly
+ * every studio-editable element carries one of the two — z-order commits and
+ * timeline patches target by id OR hf-id OR stable selector, and hf-ids are
+ * stamped uniquely by the SDK — so preferring them keeps duplicate authored
+ * ids distinct and selector-targeted clips inside soft-undo's reach.
+ */
+function elementIdentityKey(el: Element): string | null {
+ const hfId = el.getAttribute("data-hf-id");
+ if (hfId) return `hf:${hfId}`;
+ const id = el.getAttribute("id");
+ if (id) return `id:${id}`;
+ return null;
+}
+
+const IDENTITY_SELECTOR = "[id], [data-hf-id]";
+
+function identityElementMap(doc: Document): Map<string, Element> | null {
+ const map = new Map<string, Element>();
+ for (const el of doc.querySelectorAll(IDENTITY_SELECTOR)) {
+ const key = elementIdentityKey(el);
+ if (!key) continue;
+ // Ambiguous identity must full-reload; silently overwriting would restore
+ // one element's attributes onto another element sharing the same key.
+ if (map.has(key)) return null;
+ map.set(key, el);
+ }
+ return map;
+}
+
+// Strip identified elements to their bare identity attributes and blank GSAP
+// scripts, in place: docs that differ only in identified-element attributes/
+// inline-style/script text normalize equal; any residual difference is beyond
+// soft-reload's reach → caller full-reloads. Both identity attributes are
+// KEPT, so a change to `id`/`data-hf-id` themselves stays a residual
+// (structural) difference.
+function normalizeSoftResidual(doc: Document): void {
+ for (const el of doc.querySelectorAll(IDENTITY_SELECTOR)) {
+ const id = el.getAttribute("id");
+ const hfId = el.getAttribute("data-hf-id");
+ for (const name of [...el.getAttributeNames()]) {
+ if (name !== "id" && name !== "data-hf-id") el.removeAttribute(name);
+ }
+ if (id) el.setAttribute("id", id);
+ if (hfId) el.setAttribute("data-hf-id", hfId);
+ }
+ for (const script of findGsapScriptElements(doc)) script.textContent = "";
+}
+
+/** Same attribute set with identical values (order-insensitive). */
+function attributesEqual(a: Element, b: Element): boolean {
+ const aNames = a.getAttributeNames();
+ if (aNames.length !== b.getAttributeNames().length) return false;
+ for (const name of aNames) {
+ if (a.getAttribute(name) !== b.getAttribute(name)) return false;
+ }
+ return true;
+}
+
+// Soft-reloadable iff the docs differ SOLELY in identified-element attributes/
+// inline style and/or the GSAP script; returns the changed identity keys to
+// sync onto the live DOM. Structural/text diffs → null → the caller
+// full-reloads. Pure.
+//
+// Change detection deliberately compares each identified element's OWN
+// attribute surface — never its innerHTML. Identified elements NEST (the
+// composition root wraps every clip), so an innerHTML comparison at the parent
+// re-detects every descendant change and rejects the restore; that was the
+// original always-full-reload undo blink. Structure/text integrity is instead
+// guaranteed by the normalize-residual pass below: with identified-element
+// attributes stripped and scripts blanked, ANY remaining difference (text,
+// added/removed/reordered nodes, un-identified element attrs) still fails the
+// docs-equal check and escalates to a full reload.
+export function diffSoftReloadableRestore(
+ previous: string,
+ restored: string,
+): { changedElementKeys: string[] } | null {
+ let prevDoc: Document;
+ let nextDoc: Document;
+ try {
+ prevDoc = new DOMParser().parseFromString(previous, "text/html");
+ nextDoc = new DOMParser().parseFromString(restored, "text/html");
+ } catch {
+ return null;
+ }
+ const prevByKey = identityElementMap(prevDoc);
+ const nextByKey = identityElementMap(nextDoc);
+ if (!prevByKey || !nextByKey) return null;
+ // A different identity set means an element was added or removed (e.g. a
+ // split, a delete) — structural, so soft-reload can't express it.
+ if (prevByKey.size !== nextByKey.size) return null;
+ const changedElementKeys: string[] = [];
+ for (const [key, nextEl] of nextByKey) {
+ const prevEl = prevByKey.get(key);
+ if (!prevEl || prevEl.tagName !== nextEl.tagName) return null;
+ if (!attributesEqual(prevEl, nextEl)) changedElementKeys.push(key);
+ }
+ // Confirm nothing OUTSIDE identified-element attributes and GSAP scripts changed.
+ normalizeSoftResidual(prevDoc);
+ normalizeSoftResidual(nextDoc);
+ if (prevDoc.documentElement.outerHTML !== nextDoc.documentElement.outerHTML) return null;
+ return { changedElementKeys };
+}
+
+/** Copy every attribute from `source` onto the live `target`, dropping extras. */
+function syncElementAttributes(target: Element, source: Element): void {
+ for (const name of [...target.getAttributeNames()]) {
+ if (!source.hasAttribute(name)) target.removeAttribute(name);
+ }
+ for (const name of source.getAttributeNames()) {
+ target.setAttribute(name, source.getAttribute(name) ?? "");
+ }
+}
+
+function readGsapScriptTexts(html: string): string[] {
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ return findGsapScriptElements(doc).map((script) => script.textContent ?? "");
+}
+
+function hasAmbiguousGsapScriptChange(previous: string, restored: string): boolean {
+ const previousScripts = readGsapScriptTexts(previous);
+ const restoredScripts = readGsapScriptTexts(restored);
+ if (previousScripts.length <= 1 && restoredScripts.length <= 1) return false;
+ return (
+ previousScripts.length !== restoredScripts.length ||
+ previousScripts.some((script, index) => script !== restoredScripts[index])
+ );
+}
+
+/**
+ * Soft-apply an undo/redo restore to the live preview WITHOUT a full iframe
+ * remount (which blanks the frame black and re-flashes the WebGL context). Only
+ * the active composition — the document living in the root iframe — is eligible;
+ * a sub-comp or multi-file restore falls back to `reloadPreview`.
+ *
+ * The restore is soft-applied when its only differences are identified-element
+ * (id / data-hf-id) attributes / inline-style and/or the GSAP script (see
+ * diffSoftReloadableRestore):
+ * 1. Each changed element's attribute surface (inline style, data-start /
+ * -duration, the studio manual-offset props + flags) is synced onto the live
+ * element — so a canvas-position revert lands on the live DOM the runtime's
+ * seek-reapply reads from, not just on disk.
+ * 2. The runtime refresh depends on what changed:
+ * - GSAP script text actually CHANGED between previous and restored → the
+ * restored script is re-run in place via applySoftReload (re-seeks to
+ * `currentTime`, re-folds manual edits).
+ * - Script unchanged or absent (the overwhelmingly common undo: z-order,
+ * lane move, timing shift, style tweak) → NO script execution — the
+ * blink-free finalization only (seek + __hfForceTimelineRebind + manual
+ * reapply, exactly the rebindPreviewTiming path), so timing-attribute
+ * reverts refresh their visibility windows. Re-running an unchanged
+ * script here used to be the biggest undo blink source: it tore down
+ * and rebuilt live timelines (and full-reloaded whenever the script
+ * couldn't be scoped) for restores that never touched it.
+ *
+ * Returns "soft" when applied in place, "full" when it escalated to reloadPreview
+ * (ineligible restore, missing target, or a permanent soft-reload failure).
+ */
+// fallow-ignore-next-line complexity
+export function applyUndoRestoreToPreview(
+ iframe: HTMLIFrameElement | null,
+ activeCompPath: string | null,
+ files: Record<string, UndoRestoreFile> | undefined,
+ currentTime: number,
+ reloadPreview: () => void,
+): "soft" | "full" {
+ // The master view carries a NULL activeCompPath but the root iframe shows
+ // index.html — the codebase-wide convention (`activeCompPath || "index.html"`).
+ // Without this normalization every master-view undo failed the path gate and
+ // full-reloaded: the original "undo always blinks".
+ const activeDocPath = activeCompPath ?? "index.html";
+ const paths = files ? Object.keys(files) : [];
+ // Soft path only covers the single active-comp document in the root iframe.
+ if (!iframe || !files || paths.length !== 1 || paths[0] !== activeDocPath) {
+ reloadPreview();
+ return "full";
+ }
+ const doc = iframe.contentDocument;
+ const win = iframe.contentWindow as PreviewWindow | null;
+ if (!doc || !win) {
+ reloadPreview();
+ return "full";
+ }
+ const { previous, restored } = files[activeDocPath]!;
+ const diff = diffSoftReloadableRestore(previous, restored);
+ if (!diff) {
+ reloadPreview();
+ return "full";
+ }
+ // A serialized snapshot cannot identify which of several GSAP scripts owns a
+ // rewrite. Keep attribute-only restores soft when every script byte is equal,
+ // but fail closed before touching the live DOM when an ambiguous script changed.
+ if (hasAmbiguousGsapScriptChange(previous, restored)) {
+ reloadPreview();
+ return "full";
+ }
+
+ // Resolve every changed pair BEFORE touching the live DOM. A missing target
+ // makes the soft restore incomplete, so escalate without leaving a partially
+ // restored preview behind.
+ const liveByKey = identityElementMap(doc);
+ const restoredByKey = identityElementMap(new DOMParser().parseFromString(restored, "text/html"));
+ if (!liveByKey || !restoredByKey) {
+ reloadPreview();
+ return "full";
+ }
+ const changedTargets: Array<{ live: Element; restored: Element }> = [];
+ for (const key of diff.changedElementKeys) {
+ const liveEl = liveByKey.get(key);
+ const restoredEl = restoredByKey.get(key);
+ if (!liveEl || !restoredEl) {
+ reloadPreview();
+ return "full";
+ }
+ changedTargets.push({ live: liveEl, restored: restoredEl });
+ }
+ // Sync each changed element's attributes onto the live DOM from the restored
+ // markup, so the runtime's seek-reapply reads the reverted values.
+ for (const target of changedTargets) syncElementAttributes(target.live, target.restored);
+
+ const restoredScript = extractGsapScriptText(restored);
+ const previousScript = extractGsapScriptText(previous);
+ if (restoredScript && restoredScript !== previousScript) {
+ const result = applySoftReload(iframe, restoredScript, {
+ onAsyncFailure: reloadPreview,
+ currentTimeOverride: currentTime,
+ });
+ if (result === "cannot-soft-reload") {
+ reloadPreview();
+ return "full";
+ }
+ return "soft";
+ }
+ // Script unchanged or absent — the live timelines are still valid; only the
+ // synced attributes need to take effect. Rebind-only finalization (zero
+ // script execution); plain seek + manual reapply as a degraded fallback when
+ // the runtime rebind hook is unavailable.
+ if (applySoftReloadFinalization(iframe, currentTime)) return "soft";
+ try {
+ win.__player?.seek?.(currentTime);
+ win.__hfStudioManualEditsApply?.();
+ } catch {
+ reloadPreview();
+ return "full";
+ }
+ return "soft";
+}
diff --git a/packages/studio/src/utils/sourceScopedSelectorIndex.ts b/packages/studio/src/utils/sourceScopedSelectorIndex.ts
new file mode 100644
index 0000000000..6627e1a5e1
--- /dev/null
+++ b/packages/studio/src/utils/sourceScopedSelectorIndex.ts
@@ -0,0 +1,29 @@
+/**
+ * Occurrence index for a selector within its source document.
+ *
+ * The preview flattens multiple composition files into one DOM, so a raw
+ * `querySelectorAll` index is not a stable source-file identity. Callers supply
+ * their existing source resolver; this helper alone owns occurrence scoping.
+ */
+export function getSourceScopedSelectorIndex(
+ doc: Document,
+ el: Element,
+ selector: string | undefined,
+ sourceFile: string | undefined,
+ resolveSourceFile: (candidate: Element) => string | undefined,
+): number | undefined {
+ if (!selector || selector.startsWith("#") || selector.startsWith("[data-composition-id=")) {
+ return undefined;
+ }
+
+ try {
+ const scope = sourceFile ?? "index.html";
+ const matches = Array.from(doc.querySelectorAll(selector)).filter(
+ (candidate) => (resolveSourceFile(candidate) ?? "index.html") === scope,
+ );
+ const matchIndex = matches.indexOf(el);
+ return matchIndex >= 0 ? matchIndex : undefined;
+ } catch {
+ return undefined;
+ }
+}