Skip to content

Write HTML. Render video. Built for agents.

feat(studio): revamps Studio + improves code quality (#2291)

Miguel Ángeldf29fa7a5e43
diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc
index 7fbf76be91..4f5f8f6b28 100644
--- a/.fallowrc.jsonc
+++ b/.fallowrc.jsonc
@@ -44,7 +44,7 @@
// Keyframe UI components — wired dynamically via EaseCurveSection/MotionPanel.
"packages/studio/src/components/editor/KeyframeDiamond.tsx",
"packages/studio/src/components/editor/SpringEaseEditor.tsx",
- // NLE notice — rendered conditionally via NLELayout when timeline is first shown.
+ // NLE notice — rendered conditionally via NLEContext/EditorShell when timeline is first shown.
"packages/studio/src/components/nle/TimelineEditorNotice.tsx",
// Zoom hook extracted for downstream razor-blade PRs (#1330, #1331).
"packages/studio/src/player/components/useTimelineZoom.ts",
@@ -53,9 +53,6 @@
"packages/studio/src/hooks/gsapTargetCache.ts",
// Preview helper consumed dynamically from the studio iframe bridge.
"packages/studio/src/hooks/gsapRuntimePreview.ts",
- // TEMP(studio-dnd): shipped unwired ahead of the NLE integration;
- // the app-shell swap PR (studio-dnd/pr22) wires the consumers and removes this block.
- "packages/studio/src/components/editor/CanvasContextMenu.tsx",
],
"ignorePatterns": [
"docs/**",
@@ -93,10 +90,52 @@
"packages/cli/src/cloud/_gen/**",
],
"ignoreExports": [
- // TEMP(studio-dnd): consumers land later in the stack; removed by studio-dnd/pr22.
+ // Part of useTimelineEditing's inferred public return type; consumers invoke
+ // handleTimelineGroupResize without importing the change type directly.
{
- "file": "packages/studio/src/components/editor/canvasContextMenuZOrder.ts",
- "exports": ["readEffectiveZIndex"],
+ "file": "packages/studio/src/hooks/useTimelineGroupEditing.ts",
+ "exports": ["TimelineGroupResizeChange"],
+ },
+ {
+ "file": "packages/studio/src/player/components/timelineGroupEditing.ts",
+ "exports": [
+ "buildTimelineGroupResizeMembers",
+ "resolveTimelineGroupResizeChanges",
+ "applyTimelineGroupResizePreview",
+ ],
+ },
+ {
+ "file": "packages/studio/src/player/components/timelineEditing.ts",
+ "exports": [
+ "selectTimelineElementsInMarquee",
+ "TimelineGroupResizeEdge",
+ "TimelineGroupTimingMember",
+ ],
+ },
+ {
+ "file": "packages/studio/src/player/lib/timelineElementHelpers.ts",
+ "exports": ["furthestClipEndFromDocument", "furthestClipEndFromSource"],
+ },
+ {
+ "file": "packages/studio/src/components/sidebar/AssetContextMenu.tsx",
+ "exports": ["DeleteConfirm"],
+ },
+ {
+ "file": "packages/studio/src/utils/timelineAssetDrop.ts",
+ "exports": [
+ "setCompositionDurationToContent",
+ "extendCompositionDurationIfNeeded",
+ "fitTimelineAssetGeometry",
+ "resolveTimelineAssetCompositionSize",
+ ],
+ },
+ {
+ "file": "packages/studio/src/components/sidebar/assetHelpers.ts",
+ "exports": ["truncateMiddle", "formatDuration"],
+ },
+ {
+ "file": "packages/studio/src/utils/studioHelpers.ts",
+ "exports": ["resolveDroppedAssetDimensions"],
},
// drawElementService is the bottom of the fast-capture Graphite stack
// (#1917): its consumers (frameCapture in #1919) land two PRs upstack, so
@@ -320,6 +359,11 @@
// and attribute tag-patchers; only the PatchOperation type gained two
// optional fields here, but the line shift makes fallow re-flag them.
"packages/studio/src/utils/sourcePatcher.ts",
+ // useGsapSelectionHandlers.ts: pre-existing parallel structure with
+ // useDomEditWiring.ts (thin useCallback wrappers guarding on selection);
+ // only gained two optional pass-through parameters here, but the line
+ // shift makes fallow re-flag the pre-existing clone.
+ "packages/studio/src/hooks/useGsapSelectionHandlers.ts",
// gsapParser.ts: recast/babel GSAP writer — intentional duplication between
// recast and acorn parallel implementations (pre-existing, moved from core).
"packages/parsers/src/gsapParser.ts",
@@ -441,13 +485,6 @@
// complexity pre-dates the computed-timeline work. Exempted at file level
// rather than refactored as scope creep.
"ignore": [
- // TEMP(studio-dnd): coexistence-window complexity flare (inherited/CRAP-no-coverage);
- // removed by studio-dnd/pr22 when the final config lands.
- "packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts",
- "packages/studio/src/components/editor/CanvasContextMenu.tsx",
- "packages/studio/src/components/editor/canvasContextMenuZOrder.test.ts",
- "packages/studio/src/player/components/timelineCollision.test.ts",
- "packages/studio/src/player/components/timelineStackingSync.test.ts",
// sourcePatcher.ts: resolveSourceFile / splitInlineStyleDeclarations /
// patch*InTag pre-date this PR; only the PatchOperation type gained two
// optional fields, but the line-shift fingerprint re-flags the inherited
@@ -587,14 +624,12 @@
"packages/studio/src/components/editor/Transform3DCube.tsx",
"packages/studio/src/components/LintModal.tsx",
"packages/studio/src/components/MediaPreview.tsx",
- "packages/studio/src/components/nle/NLELayout.tsx",
"packages/studio/src/components/nle/NLEPreview.tsx",
"packages/studio/src/components/sidebar/AudioRow.tsx",
"packages/studio/src/components/sidebar/BlocksTab.tsx",
"packages/studio/src/components/sidebar/CompositionsTab.tsx",
"packages/studio/src/components/sidebar/LeftSidebar.tsx",
"packages/studio/src/components/storyboard/StoryboardLoaded.tsx",
- "packages/studio/src/components/StudioPreviewArea.tsx",
"packages/studio/src/components/StudioRightPanel.tsx",
"packages/studio/src/components/StudioToast.tsx",
"packages/studio/src/components/ui/Tooltip.tsx",
diff --git a/packages/core/src/runtime/init.test.ts b/packages/core/src/runtime/init.test.ts
index 378a6a9bb4..9c7700b5fc 100644
--- a/packages/core/src/runtime/init.test.ts
+++ b/packages/core/src/runtime/init.test.ts
@@ -1564,6 +1564,36 @@ describe("initSandboxRuntimeModular", () => {
expect(seekTimes[seekTimes.length - 1]).toBe(0);
});
+ it("restores timed element visibility after a forced timeline rebind", () => {
+ document.body.innerHTML = `
+ <div data-composition-id="root" data-root="true" data-duration="30" data-width="1920" data-height="1080">
+ <div class="clip" id="clip-expired" data-start="0" data-duration="15.234"></div>
+ <div class="clip" id="clip-future" data-start="20.83" data-duration="3"></div>
+ <div class="clip" id="clip-control" data-start="10" data-duration="10"></div>
+ </div>
+ `;
+ const clipExpired = document.querySelector<HTMLElement>("#clip-expired");
+ const clipFuture = document.querySelector<HTMLElement>("#clip-future");
+ const clipControl = document.querySelector<HTMLElement>("#clip-control");
+ window.__timelines = { root: createMockTimeline(30) };
+
+ initSandboxRuntimeModular();
+ window.__player?.seek(16.2);
+
+ expect(clipExpired?.style.visibility).toBe("hidden");
+ expect(clipFuture?.style.visibility).toBe("hidden");
+ expect(clipControl?.style.visibility).toBe("visible");
+
+ if (clipExpired) clipExpired.style.visibility = "visible";
+ if (clipFuture) clipFuture.style.visibility = "visible";
+
+ window.__hfForceTimelineRebind?.();
+
+ expect(clipExpired?.style.visibility).toBe("hidden");
+ expect(clipFuture?.style.visibility).toBe("hidden");
+ expect(clipControl?.style.visibility).toBe("visible");
+ });
+
it("onSetMuted preserves authored muted attribute on video elements", () => {
const root = document.createElement("div");
root.setAttribute("data-composition-id", "root");
diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts
index acaf614e9e..67ace5d152 100644
--- a/packages/core/src/runtime/init.ts
+++ b/packages/core/src/runtime/init.ts
@@ -1334,6 +1334,7 @@ export function initSandboxRuntimeModular(): void {
(window as Window & { __hfForceTimelineRebind?: () => void }).__hfForceTimelineRebind = () => {
childrenBound = false;
bindRootTimelineIfAvailable();
+ syncTimedElementVisibility(state.currentTime);
};
const emitRootStageLayoutDiagnostics = () => {
@@ -1691,6 +1692,64 @@ export function initSandboxRuntimeModular(): void {
const dataHiddenDisplayRestores = new WeakMap<HTMLElement, string>();
const dataHiddenDisplayNodes = new WeakSet<HTMLElement>();
+ const syncTimedElementVisibility = (currentTime: number) => {
+ const visibilityNodes = Array.from(document.querySelectorAll("[data-start]"));
+ const rootComp = resolveRootCompositionElement();
+ for (const rawNode of visibilityNodes) {
+ if (!(rawNode instanceof HTMLElement)) continue;
+
+ if (rawNode.hasAttribute("data-hidden")) {
+ if (!dataHiddenDisplayNodes.has(rawNode)) {
+ dataHiddenDisplayRestores.set(rawNode, rawNode.style.getPropertyValue("display"));
+ dataHiddenDisplayNodes.add(rawNode);
+ }
+ rawNode.style.display = "none";
+ if (rawNode instanceof HTMLVideoElement || rawNode instanceof HTMLImageElement) {
+ colorGradingRuntime?.setSourceVisibility(rawNode, false);
+ }
+ continue;
+ }
+
+ if (dataHiddenDisplayNodes.has(rawNode)) {
+ const previousDisplay = dataHiddenDisplayRestores.get(rawNode);
+ if (previousDisplay) {
+ rawNode.style.display = previousDisplay;
+ } else {
+ rawNode.style.removeProperty("display");
+ }
+ dataHiddenDisplayRestores.delete(rawNode);
+ dataHiddenDisplayNodes.delete(rawNode);
+ }
+
+ let isVisibleNow = isTimedElementVisibleAt(rawNode, currentTime);
+ // Descendants must not override a hidden ancestor clip. CSS visibility can
+ // otherwise leak child pixels through inactive scenes because a descendant
+ // with visibility:visible escapes an ancestor's visibility:hidden.
+ if (isVisibleNow) {
+ let ancestor = rawNode.parentElement;
+ while (ancestor) {
+ if (ancestor === rootComp) break;
+ if (ancestor instanceof HTMLElement && ancestor.hasAttribute("data-start")) {
+ if (!isTimedElementVisibleAt(ancestor, currentTime)) {
+ isVisibleNow = false;
+ break;
+ }
+ }
+ ancestor = ancestor.parentElement;
+ }
+ }
+ rawNode.style.visibility = isVisibleNow ? "visible" : "hidden";
+ if (rawNode instanceof HTMLVideoElement || rawNode instanceof HTMLImageElement) {
+ colorGradingRuntime?.setSourceVisibility(rawNode, isVisibleNow);
+ }
+ if (isVisibleNow) {
+ if (isTimedClipInFlow(rawNode)) rawNode.style.removeProperty("display");
+ } else if (isTimedClipInFlow(rawNode) && isTimedClipLeaf(rawNode)) {
+ rawNode.style.display = "none";
+ }
+ }
+ };
+
const syncMediaForCurrentState = () => {
const resolveMediaCompositionContext = (element: HTMLVideoElement | HTMLAudioElement) => {
const compositionRoot = element.closest("[data-composition-id]");
@@ -1773,61 +1832,7 @@ export function initSandboxRuntimeModular(): void {
},
});
}
- const visibilityNodes = Array.from(document.querySelectorAll("[data-start]"));
- const rootComp = resolveRootCompositionElement();
- for (const rawNode of visibilityNodes) {
- if (!(rawNode instanceof HTMLElement)) continue;
-
- if (rawNode.hasAttribute("data-hidden")) {
- if (!dataHiddenDisplayNodes.has(rawNode)) {
- dataHiddenDisplayRestores.set(rawNode, rawNode.style.getPropertyValue("display"));
- dataHiddenDisplayNodes.add(rawNode);
- }
- rawNode.style.display = "none";
- if (rawNode instanceof HTMLVideoElement || rawNode instanceof HTMLImageElement) {
- colorGradingRuntime?.setSourceVisibility(rawNode, false);
- }
- continue;
- }
-
- if (dataHiddenDisplayNodes.has(rawNode)) {
- const previousDisplay = dataHiddenDisplayRestores.get(rawNode);
- if (previousDisplay) {
- rawNode.style.display = previousDisplay;
- } else {
- rawNode.style.removeProperty("display");
- }
- dataHiddenDisplayRestores.delete(rawNode);
- dataHiddenDisplayNodes.delete(rawNode);
- }
-
- let isVisibleNow = isTimedElementVisibleAt(rawNode, state.currentTime);
- // Descendants must not override a hidden ancestor clip. CSS visibility can
- // otherwise leak child pixels through inactive scenes because a descendant
- // with visibility:visible escapes an ancestor's visibility:hidden.
- if (isVisibleNow) {
- let ancestor = rawNode.parentElement;
- while (ancestor) {
- if (ancestor === rootComp) break;
- if (ancestor instanceof HTMLElement && ancestor.hasAttribute("data-start")) {
- if (!isTimedElementVisibleAt(ancestor, state.currentTime)) {
- isVisibleNow = false;
- break;
- }
- }
- ancestor = ancestor.parentElement;
- }
- }
- rawNode.style.visibility = isVisibleNow ? "visible" : "hidden";
- if (rawNode instanceof HTMLVideoElement || rawNode instanceof HTMLImageElement) {
- colorGradingRuntime?.setSourceVisibility(rawNode, isVisibleNow);
- }
- if (isVisibleNow) {
- if (isTimedClipInFlow(rawNode)) rawNode.style.removeProperty("display");
- } else if (isTimedClipInFlow(rawNode) && isTimedClipLeaf(rawNode)) {
- rawNode.style.display = "none";
- }
- }
+ syncTimedElementVisibility(state.currentTime);
};
const postState = (force: boolean) => {
diff --git a/packages/studio-server/src/helpers/sourceMutation.ts b/packages/studio-server/src/helpers/sourceMutation.ts
index b26558b9c3..ef76ef618c 100644
--- a/packages/studio-server/src/helpers/sourceMutation.ts
+++ b/packages/studio-server/src/helpers/sourceMutation.ts
@@ -2,6 +2,7 @@ import { parseHTML } from "linkedom";
import postcss from "postcss";
import selectorParser from "postcss-selector-parser";
import { isAllowedHtmlAttribute, isSafeAttributeValue } from "@hyperframes/core/html-attr-safety";
+import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
import { parseStyleDecls, patchStyleAttrString } from "./sourceStyleMutation.js";
export interface SourceMutationTarget {
@@ -349,8 +350,11 @@ export function splitElementInHtml(
el.parentElement!.appendChild(clone);
}
+ const html = wrappedFragment ? document.body.innerHTML || "" : document.toString();
return {
- html: wrappedFragment ? document.body.innerHTML || "" : document.toString(),
+ // The split owns its new nodes' stable ids. Leaving the clone unstamped makes
+ // the next preview request persist different bytes after history is recorded.
+ html: ensureHfIds(html),
matched: true,
newId,
};
diff --git a/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts b/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts
index 6bd4d92dcb..47bc557fc0 100644
--- a/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts
+++ b/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts
@@ -12,8 +12,11 @@ describe("splitElementInHtml — hfId clone isolation", () => {
const { html, matched } = splitElementInHtml(source, { id: "clip1" }, 5, "clip2");
expect(matched).toBe(true);
+ const { document } = parseHTML(html);
const occurrences = (html.match(/data-hf-id="hf-abc123"/g) ?? []).length;
expect(occurrences).toBe(1);
+ expect(document.getElementById("clip2")?.getAttribute("data-hf-id")).toMatch(/^hf-/);
+ expect(document.getElementById("clip2")?.getAttribute("data-hf-id")).not.toBe("hf-abc123");
});
});
diff --git a/packages/studio-server/src/routes/files.test.ts b/packages/studio-server/src/routes/files.test.ts
index 90699abd5a..6df7cf3672 100644
--- a/packages/studio-server/src/routes/files.test.ts
+++ b/packages/studio-server/src/routes/files.test.ts
@@ -1,6 +1,14 @@
import { afterEach, describe, expect, it } from "vitest";
import { Hono } from "hono";
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { registerFileRoutes } from "./files";
@@ -38,6 +46,14 @@ function createAdapter(projectDir: string): StudioApiAdapter {
};
}
+function postElementPatchBatch(app: Hono, file: string, patches: unknown[]): Promise<Response> {
+ return app.request(`http://localhost/projects/demo/file-mutations/patch-elements-batch/${file}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ patches }),
+ });
+}
+
describe("registerFileRoutes", () => {
it("returns empty content for missing files when caller marks the read optional", async () => {
const projectDir = createProjectDir();
@@ -116,13 +132,13 @@ describe("registerFileRoutes", () => {
}),
},
);
+ expect(response.status).toBe(200);
const payload = (await response.json()) as {
changed?: boolean;
path?: string;
backupPath?: string;
};
- expect(response.status).toBe(200);
expect(payload.changed).toBe(true);
expect(payload.path).toBe("index.html");
expect(payload.backupPath).toMatch(/^\.hyperframes\/backup\//);
@@ -132,6 +148,96 @@ describe("registerFileRoutes", () => {
expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toContain("After");
});
+ it("applies an ordered element patch batch with one file write", async () => {
+ const projectDir = createProjectDir();
+ const original =
+ '<div id="back" style="z-index: 1">Back</div><div id="front" style="z-index: 2">Front</div>';
+ writeFileSync(join(projectDir, "index.html"), original);
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+
+ const response = await postElementPatchBatch(app, "index.html", [
+ {
+ target: { id: "back" },
+ operations: [{ type: "inline-style", property: "z-index", value: "2" }],
+ },
+ {
+ target: { id: "front" },
+ operations: [{ type: "inline-style", property: "z-index", value: "1" }],
+ },
+ ]);
+ expect(response.status).toBe(200);
+ const payload = (await response.json()) as {
+ changed?: boolean;
+ matched?: boolean[];
+ content?: string;
+ backupPath?: string;
+ };
+
+ expect(response.status).toBe(200);
+ expect(payload.changed).toBe(true);
+ expect(payload.matched).toEqual([true, true]);
+ expect(payload.content).toBe(readFileSync(join(projectDir, "index.html"), "utf-8"));
+ expect(payload.content).toContain('id="back" style="z-index: 2"');
+ expect(payload.content).toContain('id="front" style="z-index: 1"');
+ expect(readFileSync(join(projectDir, payload.backupPath!), "utf-8")).toBe(original);
+ expect(readdirSync(join(projectDir, ".hyperframes", "backup"))).toHaveLength(1);
+ });
+
+ it("returns changed false without writing for a no-op element patch batch", async () => {
+ const projectDir = createProjectDir();
+ const original = '<div id="title" style="z-index: 4">Title</div>';
+ writeFileSync(join(projectDir, "index.html"), original);
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+
+ const response = await postElementPatchBatch(app, "index.html", [
+ {
+ target: { id: "title" },
+ operations: [{ type: "inline-style", property: "z-index", value: "4" }],
+ },
+ ]);
+ expect(response.status).toBe(200);
+ const payload = (await response.json()) as {
+ changed?: boolean;
+ matched?: boolean[];
+ content?: string;
+ backupPath?: string;
+ };
+
+ expect(payload.changed).toBe(false);
+ expect(payload.matched).toEqual([true]);
+ expect(payload.content).toBe(original);
+ expect(payload.backupPath).toBeUndefined();
+ expect(existsSync(join(projectDir, ".hyperframes", "backup"))).toBe(false);
+ });
+
+ 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>';
+ writeFileSync(join(projectDir, "index.html"), original);
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+
+ const response = await postElementPatchBatch(app, "index.html", [
+ {
+ target: { id: "first" },
+ operations: [{ type: "inline-style", property: "z-index", value: "2" }],
+ },
+ {
+ target: { id: "second", selectorIndex: Number.NaN },
+ operations: [{ type: "inline-style", property: "z-index", value: "1" }],
+ },
+ ]);
+ expect(response.status).toBe(400);
+ const payload = (await response.json()) as { error?: string; fields?: string[] };
+
+ expect(payload.error).toContain("unsafe values");
+ expect(payload.fields).toContain("body.target.selectorIndex");
+ expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toBe(original);
+ expect(existsSync(join(projectDir, ".hyperframes", "backup"))).toBe(false);
+ });
+
// A realistic sub-composition: markup + GSAP wrapped in a <template>, tweens
// targeting element variables resolved from querySelector, with interleaved
// gsap.set() calls. This is the shape every scaffolded composition uses.
@@ -205,6 +311,136 @@ tl.fromTo("#box", { opacity: 0, x: -50 }, { opacity: 1, x: 0, duration: 1.5, eas
return payload.animations[0];
}
+ function postGsapMutationBatch(app: Hono, file: string, body: unknown): Promise<Response> {
+ return app.request(`http://localhost/projects/demo/gsap-mutations-batch/${file}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ }
+
+ it("applies an ordered GSAP mutation batch with one before/after write result", async () => {
+ const projectDir = createProjectDir();
+ writeHtml(projectDir, "comp.html", FROMTO_COMP);
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+ const anim = await getFirstAnimation(app, "comp.html");
+
+ const res = await postGsapMutationBatch(app, "comp.html", {
+ mutations: [
+ {
+ type: "update-from-property",
+ animationId: anim.id,
+ property: "opacity",
+ value: 0.2,
+ },
+ {
+ type: "update-from-property",
+ animationId: anim.id,
+ property: "x",
+ value: -25,
+ },
+ ],
+ });
+ const result = (await res.json()) as {
+ ok: boolean;
+ changed: boolean;
+ before: string;
+ after: string;
+ backupPath: string;
+ parsed: { animations: Array<{ fromProperties?: Record<string, number | string> }> };
+ };
+
+ expect(res.status).toBe(200);
+ expect(result.ok).toBe(true);
+ expect(result.changed).toBe(true);
+ expect(result.before).toBe(FROMTO_COMP);
+ expect(result.after).toBe(readFileSync(join(projectDir, "comp.html"), "utf-8"));
+ expect(readFileSync(join(projectDir, result.backupPath), "utf-8")).toBe(FROMTO_COMP);
+ expect(result.parsed.animations[0].fromProperties).toMatchObject({ opacity: 0.2, x: -25 });
+ });
+
+ it.each(["first", "middle", "last"] as const)(
+ "rejects an invalid %s mutation without writing any part of the batch",
+ async (position) => {
+ const projectDir = createProjectDir();
+ writeHtml(projectDir, "comp.html", FROMTO_COMP);
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+ const anim = await getFirstAnimation(app, "comp.html");
+ const valid = {
+ type: "update-from-property",
+ animationId: anim.id,
+ property: "opacity",
+ value: 0.2,
+ };
+ const invalid =
+ position === "first"
+ ? {}
+ : position === "middle"
+ ? { ...valid, value: null }
+ : { type: "not-a-mutation" };
+ const mutations =
+ position === "first"
+ ? [invalid, valid, valid]
+ : position === "middle"
+ ? [valid, invalid, valid]
+ : [valid, valid, invalid];
+
+ const res = await postGsapMutationBatch(app, "comp.html", { mutations });
+
+ expect(res.status).toBe(400);
+ expect(readFileSync(join(projectDir, "comp.html"), "utf-8")).toBe(FROMTO_COMP);
+ },
+ );
+
+ it("re-syncs position holds when a batch mixes hold-sync and ordinary mutations", async () => {
+ const projectDir = createProjectDir();
+ const html = `<!DOCTYPE html><html><body><div id="box"></div><script data-hyperframes-gsap>
+const tl = gsap.timeline({ paused: true });
+</script></body></html>`;
+ writeHtml(projectDir, "hold.html", html);
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+
+ const res = await postGsapMutationBatch(app, "hold.html", {
+ mutations: [
+ {
+ type: "add-with-keyframes",
+ targetSelector: "#box",
+ position: 1,
+ duration: 1,
+ keyframes: [
+ { percentage: 0, properties: { x: 10, y: 20 } },
+ { percentage: 100, properties: { x: 30, y: 40 } },
+ ],
+ },
+ {
+ type: "add",
+ targetSelector: "#box",
+ method: "set",
+ position: 0,
+ properties: { opacity: 0.5 },
+ },
+ ],
+ });
+ const result = (await res.json()) as { scriptText: string };
+
+ expect(res.status).toBe(200);
+ expect(result.scriptText).toContain("hf-hold");
+ expect(result.scriptText.match(/hf-hold/g)).toHaveLength(1);
+ });
+
+ it.each([{}, { mutations: [] }])("rejects an empty or missing mutation batch", async (body) => {
+ const projectDir = createProjectDir();
+ const app = new Hono();
+ registerFileRoutes(app, createAdapter(projectDir));
+
+ const res = await postGsapMutationBatch(app, "index.html", body);
+
+ expect(res.status).toBe(400);
+ });
+
it("update-from-property updates a fromTo start value in place", async () => {
const projectDir = createProjectDir();
writeHtml(projectDir, "comp.html", FROMTO_COMP);
diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts
index 8ad12293ba..8aceab9aa7 100644
--- a/packages/studio-server/src/routes/files.ts
+++ b/packages/studio-server/src/routes/files.ts
@@ -106,6 +106,12 @@ interface RouteContext {
json: (data: unknown, status?: number) => Response;
}
+interface ResolvedGsapFile {
+ project: { dir: string };
+ filePath: string;
+ absPath: string;
+}
+
/** Resolve project + safe absolute path for any project-scoped route. */
async function resolveProjectPath(
c: RouteContext,
@@ -155,6 +161,25 @@ type MutationTarget = {
selectorIndex?: number;
};
+interface ElementPatchRequest {
+ target: MutationTarget;
+ operations: PatchOperation[];
+}
+
+function foldElementPatches(
+ originalContent: string,
+ patches: ElementPatchRequest[],
+): { content: string; matched: boolean[] } {
+ let content = originalContent;
+ const matched: boolean[] = [];
+ for (const patch of patches) {
+ const result = patchElementInHtml(content, patch.target, patch.operations);
+ content = result.html;
+ matched.push(result.matched);
+ }
+ return { content, matched };
+}
+
/** Write `next` to `absPath` only if it differs from `original`, returning a standardized change response. */
function writeIfChanged(
c: RouteContext,
@@ -844,6 +869,130 @@ async function executeGsapMutation(
return executeGsapMutationAcorn(body, block, respond);
}
+function validateGsapMutationRequest(
+ c: RouteContext,
+ body: GsapMutationRequest | null,
+): Response | null {
+ if (!body || typeof body !== "object" || !("type" in body) || !body.type) {
+ return c.json({ error: "mutation type required" }, 400);
+ }
+ const unsafeFields = findUnsafeMutationValues(body);
+ if (unsafeFields.length > 0) return rejectUnsafeMutationValues(c, unsafeFields);
+ if (
+ body.type === "shift-positions-batch" &&
+ (!("shifts" in body) || !Array.isArray(body.shifts))
+ ) {
+ return c.json({ error: "shift-positions-batch requires a `shifts` array" }, 400);
+ }
+ return null;
+}
+
+async function prepareGsapMutationScript(
+ c: RouteContext,
+ res: ResolvedGsapFile,
+ firstMutation: GsapMutationRequest,
+): Promise<
+ | Response
+ | {
+ html: string;
+ block: NonNullable<ReturnType<typeof extractGsapScriptBlock>>;
+ }
+> {
+ let html = readFileSync(res.absPath, "utf-8");
+ let block = extractGsapScriptBlock(html);
+ if (!block && (firstMutation.type === "add" || firstMutation.type === "add-with-keyframes")) {
+ const compId = html.match(/data-composition-id="([^"]+)"/)?.[1] ?? "main";
+ const { GSAP_CDN } = await import("@hyperframes/core");
+ const bootstrap = [
+ `<script src="${GSAP_CDN}"></script>`,
+ "<script>",
+ "window.__timelines = window.__timelines || {};",
+ "const tl = gsap.timeline({ paused: true });",
+ `window.__timelines["${compId}"] = tl;`,
+ "</script>",
+ ].join("\n");
+ html = html.includes("</body>")
+ ? html.replace("</body>", `${bootstrap}\n</body>`)
+ : `${html}\n${bootstrap}`;
+ block = extractGsapScriptBlock(html);
+ }
+ if (
+ !block &&
+ (firstMutation.type === "shift-positions" ||
+ firstMutation.type === "scale-positions" ||
+ firstMutation.type === "shift-positions-batch")
+ ) {
+ return c.json({
+ ok: true,
+ changed: false,
+ mutated: false,
+ parsed: { animations: [], timelineVar: "tl", preamble: "", postamble: "" },
+ before: html,
+ after: html,
+ scriptText: "",
+ path: res.filePath,
+ backupPath: null,
+ });
+ }
+ if (!block) return c.json({ error: "no GSAP script found in file" }, 400);
+ return { html, block };
+}
+
+async function applyGsapMutations(
+ c: RouteContext,
+ res: ResolvedGsapFile,
+ mutations: GsapMutationRequest[],
+): Promise<Response> {
+ const firstMutation = mutations[0];
+ 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 initialScript = block.scriptText;
+ const skippedSelectors = new Set<string>();
+ const respond = (data: unknown, status?: number) =>
+ status ? c.json(data, status) : c.json(data);
+
+ for (const mutation of mutations) {
+ const result = await executeGsapMutation(mutation, block, respond);
+ if (result instanceof Response) return result;
+ let newScript = typeof result === "string" ? result : result.script;
+ if (typeof result !== "string") {
+ for (const selector of result.skippedSelectors) skippedSelectors.add(selector);
+ }
+ if (HOLD_SYNC_MUTATION_TYPES.has(mutation.type)) {
+ const parser = await loadGsapParser();
+ newScript = parser.syncPositionHoldsBeforeKeyframes(newScript);
+ }
+ block.scriptText = newScript;
+ }
+
+ const changed = block.scriptText !== initialScript;
+ const newHtml = changed ? block.replaceScript(block.scriptText) : html;
+ let backupPath: string | null = null;
+ if (changed) {
+ const backup = snapshotBeforeWrite(res.project.dir, res.absPath);
+ if (backup.error) console.warn(`Failed to create backup for ${res.filePath}: ${backup.error}`);
+ backupPath = backupPathForResponse(res.project.dir, backup.backupPath);
+ writeFileSync(res.absPath, newHtml, "utf-8");
+ }
+
+ const responsePayload: Record<string, unknown> = {
+ ok: true,
+ changed,
+ mutated: changed,
+ parsed: parseGsapScriptAcorn(block.scriptText),
+ before: html,
+ after: newHtml,
+ scriptText: block.scriptText,
+ path: res.filePath,
+ backupPath,
+ };
+ if (skippedSelectors.size > 0) responsePayload.skippedSelectors = [...skippedSelectors];
+ return c.json(responsePayload);
+}
+
function executeGsapMutationAcorn(
body: GsapMutationRequest,
block: NonNullable<ReturnType<typeof extractGsapScriptBlock>>,
@@ -1801,6 +1950,58 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
});
});
+ 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;
+
+ const body = (await c.req.json().catch(() => null)) as {
+ patches?: ElementPatchRequest[];
+ } | null;
+ if (
+ !body ||
+ !Array.isArray(body.patches) ||
+ body.patches.length === 0 ||
+ body.patches.some(
+ (patch) =>
+ !patch?.target || !Array.isArray(patch.operations) || patch.operations.length === 0,
+ )
+ ) {
+ return c.json({ error: "patches with target and operations required" }, 400);
+ }
+ const unsafeFields = body.patches.flatMap((patch) => findUnsafeDomPatchValues(patch));
+ 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 = 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");
+ return c.json({
+ ok: true,
+ changed: true,
+ matched: result.matched,
+ content: result.content,
+ path: ctx.filePath,
+ backupPath: backupPathForResponse(ctx.project.dir, backup.backupPath),
+ });
+ });
+
api.post("/projects/:id/file-mutations/wrap-elements/*", async (c) => {
const ctx = await resolveFileMutationContext(c, adapter, "wrap-elements");
if ("error" in ctx) return ctx.error;
@@ -2042,104 +2243,31 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
if ("error" in res) return res.error;
const body = (await c.req.json().catch(() => null)) as GsapMutationRequest | null;
- if (!body || !body.type) {
- return c.json({ error: "mutation type required" }, 400);
- }
- const unsafeFields = findUnsafeMutationValues(body);
- if (unsafeFields.length > 0) {
- return rejectUnsafeMutationValues(c, unsafeFields);
- }
- // Defensive shape guard: a malformed shift-positions-batch (missing/non-array
- // `shifts`) would otherwise TypeError inside `for (const s of body.shifts)`.
- if (body.type === "shift-positions-batch" && !Array.isArray(body.shifts)) {
- return c.json({ error: "shift-positions-batch requires a `shifts` array" }, 400);
- }
-
- let html = readFileSync(res.absPath, "utf-8");
- let block = extractGsapScriptBlock(html);
- if (!block && (body.type === "add" || body.type === "add-with-keyframes")) {
- const compId = html.match(/data-composition-id="([^"]+)"/)?.[1] ?? "main";
- const { GSAP_CDN } = await import("@hyperframes/core");
- const gsapCdn = `<script src="${GSAP_CDN}"></script>`;
- const bootstrap = [
- gsapCdn,
- "<script>",
- "window.__timelines = window.__timelines || {};",
- `const tl = gsap.timeline({ paused: true });`,
- `window.__timelines["${compId}"] = tl;`,
- "</script>",
- ].join("\n");
- if (html.includes("</body>")) {
- html = html.replace("</body>", `${bootstrap}\n</body>`);
- } else {
- html += `\n${bootstrap}`;
- }
- block = extractGsapScriptBlock(html);
- }
- if (
- !block &&
- (body.type === "shift-positions" ||
- body.type === "scale-positions" ||
- body.type === "shift-positions-batch")
- ) {
- return c.json({
- ok: true,
- changed: false,
- mutated: false,
- parsed: { animations: [], timelineVar: "tl", preamble: "", postamble: "" },
- before: html,
- after: html,
- scriptText: "",
- path: res.filePath,
- backupPath: null,
- });
- }
- if (!block) {
- return c.json({ error: "no GSAP script found in file" }, 400);
- }
-
- const respond = (data: unknown, status?: number) =>
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- bridge between generic status and Hono's literal union
- status ? c.json(data, status as any) : c.json(data);
+ if (!body) return c.json({ error: "mutation type required" }, 400);
+ const error = validateGsapMutationRequest(c, body);
+ if (error) return error;
+ return applyGsapMutations(c, res, [body]);
+ });
- const result = await executeGsapMutation(body, block, respond);
- if (result instanceof Response) return result;
+ api.post("/projects/:id/gsap-mutations-batch/*", async (c) => {
+ const res = await resolveProjectPath(
+ c,
+ adapter,
+ (id) => `/projects/${id}/gsap-mutations-batch/`,
+ { mustExist: true },
+ );
+ if ("error" in res) return res.error;
- let newScript = typeof result === "string" ? result : result.script;
- // Keep the "hold before first keyframe" sets in sync after any mutation that can
- // change a position tween's first keyframe or its existence. Without it, an
- // element snaps to its CSS base before the tween starts instead of holding its
- // first keyframe (the universal NLE behavior).
- if (HOLD_SYNC_MUTATION_TYPES.has(body.type)) {
- const parser = await loadGsapParser();
- newScript = parser.syncPositionHoldsBeforeKeyframes(newScript);
- }
- const changed = newScript !== block.scriptText;
- const newHtml = changed ? block.replaceScript(newScript) : html;
- let backupPath: string | null = null;
- if (changed) {
- const backup = snapshotBeforeWrite(res.project.dir, res.absPath);
- if (backup.error)
- console.warn(`Failed to create backup for ${res.filePath}: ${backup.error}`);
- backupPath = backupPathForResponse(res.project.dir, backup.backupPath);
- writeFileSync(res.absPath, newHtml, "utf-8");
+ const body = (await c.req.json().catch(() => null)) as {
+ mutations?: GsapMutationRequest[];
+ } | null;
+ if (!body || !Array.isArray(body.mutations) || body.mutations.length === 0) {
+ return c.json({ error: "mutations array required" }, 400);
}
-
- const freshParsed = parseGsapScriptAcorn(newScript);
- const responsePayload: Record<string, unknown> = {
- ok: true,
- changed,
- mutated: changed,
- parsed: freshParsed,
- before: html,
- after: newHtml,
- scriptText: newScript,
- path: res.filePath,
- backupPath,
- };
- if (typeof result !== "string" && result.skippedSelectors.length > 0) {
- responsePayload.skippedSelectors = result.skippedSelectors;
+ for (const mutation of body.mutations) {
+ const error = validateGsapMutationRequest(c, mutation);
+ if (error) return error;
}
- return c.json(responsePayload);
+ return applyGsapMutations(c, res, body.mutations);
});
}
diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsx
index 2bac2f857c..4cb09db319 100644
--- a/packages/studio/src/App.tsx
+++ b/packages/studio/src/App.tsx
@@ -1,7 +1,7 @@
import { useState, useCallback, useRef, useMemo, useEffect, useLayoutEffect } from "react";
import type { LeftSidebarHandle, SidebarTab } from "./components/sidebar/LeftSidebar";
import { useRenderQueue } from "./components/renders/useRenderQueue";
-import { usePlayerStore } from "./player";
+import { usePlayerStore, type TimelineElement } from "./player";
import { StudioOverlays } from "./components/StudioOverlays";
import { SaveQueuePausedBanner } from "./components/SaveQueuePausedBanner";
import { useCaptionStore } from "./captions/store";
@@ -10,17 +10,21 @@ import { usePersistentEditHistory } from "./hooks/usePersistentEditHistory";
import { usePanelLayout } from "./hooks/usePanelLayout";
import { useFileManager } from "./hooks/useFileManager";
import { usePreviewPersistence } from "./hooks/usePreviewPersistence";
+import { usePreviewDocumentVersion } from "./hooks/usePreviewDocumentVersion";
import { useTimelineEditing } from "./hooks/useTimelineEditing";
+import {
+ persistTimelineMoveEditsAtomically,
+ type TimelineMoveOperation,
+} from "./hooks/timelineMoveAdapter";
import type { TimelineZIndexReorderCommit } from "./hooks/useTimelineEditingTypes";
+import type { TimelineStackingReorderIntent } from "./player/components/timelineStacking";
import type { BlockPreviewInfo } from "./components/sidebar/BlocksTab";
import { useDomEditSession } from "./hooks/useDomEditSession";
import { useSdkSelectionSync } from "./hooks/useSdkSelectionSync";
import { useStudioSdkSessions } from "./hooks/useStudioSdkSessions";
-import { usePreviewDocumentVersion } from "./hooks/usePreviewDocumentVersion";
import { useBlockHandlers } from "./hooks/useBlockHandlers";
import { useAppHotkeys } from "./hooks/useAppHotkeys";
import { useClipboard } from "./hooks/useClipboard";
-import { readStudioUiPreferences, writeStudioUiPreferences } from "./utils/studioUiPreferences";
import { deleteSelectedKeyframes } from "./hooks/timelineEditingHelpers";
import { useCaptionDetection } from "./hooks/useCaptionDetection";
import { useRenderClipContent } from "./hooks/useRenderClipContent";
@@ -33,7 +37,7 @@ import { useCompositionContentLoader } from "./hooks/useCompositionContentLoader
import { useStudioUrlState } from "./hooks/useStudioUrlState";
import {
buildStudioContextValue,
- useDragOverlay,
+ useGlobalFileDrop,
useInspectorState,
} from "./hooks/useStudioContextValue";
import type { DomEditSelection } from "./components/editor/domEditing";
@@ -42,7 +46,7 @@ import { useGestureCommit } from "./hooks/useGestureCommit";
import { STUDIO_KEYFRAMES_ENABLED } from "./components/editor/manualEditingAvailability";
import { GestureTrailOverlay } from "./components/editor/GestureTrailOverlay";
import { StudioLeftSidebar } from "./components/StudioLeftSidebar";
-import { StudioPreviewArea } from "./components/StudioPreviewArea";
+import { EditorShell } from "./components/EditorShell";
import { StudioRightPanel } from "./components/StudioRightPanel";
import { TimelineToolbar } from "./components/TimelineToolbar";
import { StudioPlaybackProvider, StudioShellProvider } from "./contexts/StudioContext";
@@ -108,18 +112,6 @@ export function StudioApp() {
: 0;
return Math.max(timelineDuration, maxEnd);
}, [timelineDuration, timelineElements]);
- const [timelineVisible, setTimelineVisible] = useState(
- () =>
- initialUrlStateRef.current.timelineVisible ??
- readStudioUiPreferences().timelineVisible ??
- true,
- );
- const toggleTimelineVisibility = useCallback(() => {
- setTimelineVisible((v) => {
- writeStudioUiPreferences({ timelineVisible: !v });
- return !v;
- });
- }, []);
const { toasts, showToast, dismissToast } = useToast();
const panelLayout = usePanelLayout({
rightCollapsed: initialUrlStateRef.current.rightCollapsed,
@@ -187,6 +179,31 @@ export function StudioApp() {
forceReloadSdkSession: sdkHandle.forceReload,
handleDomZIndexReorderCommitRef,
});
+ const handleTimelineElementsMove = useCallback(
+ async (
+ edits: Array<{
+ element: TimelineElement;
+ updates: Pick<TimelineElement, "start" | "track"> & {
+ stackingReorder?: TimelineStackingReorderIntent | null;
+ };
+ }>,
+ coalesceKey?: string,
+ operation: TimelineMoveOperation = "timing",
+ ) => {
+ await persistTimelineMoveEditsAtomically(edits, coalesceKey, operation, {
+ handleTimelineGroupMove: timelineEditing.handleTimelineGroupMove,
+ });
+ },
+ [timelineEditing.handleTimelineGroupMove],
+ );
+ const handleAddAssetAtPlayhead = useCallback(
+ (assetPath: string) =>
+ timelineEditing.handleTimelineAssetDrop(assetPath, {
+ start: usePlayerStore.getState().currentTime,
+ track: 0,
+ }),
+ [timelineEditing],
+ );
const {
activeBlockParams,
setActiveBlockParams,
@@ -232,7 +249,6 @@ export function StudioApp() {
previewIframeRef,
});
const appHotkeys = useAppHotkeys({
- toggleTimelineVisibility,
handleTimelineElementDelete: timelineEditing.handleTimelineElementDelete,
handleTimelineElementSplit: timelineEditing.handleTimelineElementSplit,
handleDomEditElementDelete: domEditDeleteBridge,
@@ -348,7 +364,7 @@ export function StudioApp() {
setConsoleErrors,
resetErrors: resetConsoleErrors,
} = useConsoleErrorCapture(previewIframe);
- const dragOverlay = useDragOverlay(fileManager.handleImportFiles);
+ const dragOverlay = useGlobalFileDrop(timelineEditing.handleTimelineFileDrop);
const handleToggleRecordingRef = useRef<() => void>(() => {});
const domEditSessionRef = useRef(domEditSession);
domEditSessionRef.current = domEditSession;
@@ -369,7 +385,6 @@ export function StudioApp() {
const r = previewIframe.getBoundingClientRect();
canvasRectRef.current = { left: r.left, top: r.top, width: r.width, height: r.height };
}, [gestureState, previewIframe]);
-
const handlePreviewIframeRef = useCallback(
(iframe: HTMLIFrameElement | null) => {
previewIframeRef.current = iframe;
@@ -410,7 +425,6 @@ export function StudioApp() {
previewIframeRef,
rightPanelTab: panelLayout.rightPanelTab,
rightCollapsed: panelLayout.rightCollapsed,
- timelineVisible,
activeCompPathHydrated,
domEditSelection: domEditSession.domEditSelection,
buildDomSelectionFromTarget: domEditSession.buildDomSelectionFromTarget,
@@ -438,18 +452,15 @@ export function StudioApp() {
waitForPendingDomEditSaves: previewPersistence.waitForPendingDomEditSaves,
handlePreviewIframeRef,
refreshPreviewDocumentVersion,
- timelineVisible,
- toggleTimelineVisibility,
});
const timelineToolbar = useMemo(
() => (
<TimelineToolbar
- toggleTimelineVisibility={toggleTimelineVisibility}
domEditSession={domEditSession}
onSplitElement={timelineEditing.handleTimelineElementSplit}
/>
),
- [toggleTimelineVisibility, domEditSession, timelineEditing.handleTimelineElementSplit],
+ [domEditSession, timelineEditing.handleTimelineElementSplit],
);
if (resolving || waitingForServer || !projectId)
return <StudioSplash waiting={waitingForServer} />;
@@ -494,78 +505,77 @@ export function StudioApp() {
onSelectComposition={handleSelectComposition}
/>
)}
- <div
- className={`flex flex-1 min-h-0${
- viewModeValue.viewMode === "storyboard" ? " hidden" : ""
- }`}
- >
- <StudioLeftSidebar
- leftSidebarRef={leftSidebarRef}
- onSelectComposition={handleSelectComposition}
- onAddBlock={handleAddBlock}
- onPreviewBlock={setBlockPreview}
- onLint={handleLint}
- linting={linting}
- lintFindingCount={lintModal?.length ?? findingsByFile.size}
- lintFindingsByFile={findingsByFile}
- />
- <StudioPreviewArea
- timelineToolbar={timelineToolbar}
- renderClipContent={renderClipContent}
- handleTimelineElementDelete={timelineEditing.handleTimelineElementDelete}
- handleTimelineAssetDrop={timelineEditing.handleTimelineAssetDrop}
- handleTimelineBlockDrop={handleTimelineBlockDrop}
- handlePreviewBlockDrop={handlePreviewBlockDrop}
- handleTimelineFileDrop={timelineEditing.handleTimelineFileDrop}
- handleTimelineElementMove={timelineEditing.handleTimelineElementMove}
- handleTimelineElementResize={timelineEditing.handleTimelineElementResize}
- handleTimelineGroupMove={timelineEditing.handleTimelineGroupMove}
- handleTimelineGroupResize={timelineEditing.handleTimelineGroupResize}
- handleToggleTrackHidden={timelineEditing.handleToggleTrackHidden}
- handleToggleElementHidden={timelineEditing.handleToggleElementHidden}
- handleBlockedTimelineEdit={timelineEditing.handleBlockedTimelineEdit}
- handleTimelineElementSplit={timelineEditing.handleTimelineElementSplit}
- handleRazorSplit={timelineEditing.handleRazorSplit}
- handleRazorSplitAll={timelineEditing.handleRazorSplitAll}
- setCompIdToSrc={setCompIdToSrc}
- setCompositionLoading={setCompositionLoading}
- shouldShowSelectedDomBounds={shouldShowSelectedDomBounds}
- isGestureRecording={gestureState === "recording"}
- recordingState={gestureState}
- onToggleRecording={recordingToggle}
- blockPreview={blockPreview}
- gestureOverlay={
- gestureState === "recording" && previewIframe ? (
- <GestureTrailOverlay
- samples={gestureRecording.samplesRef.current}
- sampleCount={gestureRecording.samplesRef.current.length}
- trail={gestureRecording.trailRef.current}
- canvasRect={canvasRectRef.current!}
- compositionSize={compositionDimensions ?? undefined}
- mode="recording"
- />
- ) : undefined
- }
- />
- {!panelLayout.rightCollapsed && (
- <StudioRightPanel
- designPanelActive={designPanelActive}
- activeBlockParams={activeBlockParams}
- onCloseBlockParams={() => {
- setActiveBlockParams(null);
- panelLayout.setRightPanelTab("design");
- }}
- recordingState={gestureState}
- recordingDuration={gestureRecording.recordingDuration}
- onToggleRecording={recordingToggle}
- sdkSession={sdkHandle.session}
- reloadPreview={reloadPreview}
- domEditSaveTimestampRef={domEditSaveTimestampRef}
- recordEdit={editHistory.recordEdit}
- onToggleElementHidden={timelineEditing.handleToggleElementHidden}
+ <EditorShell
+ hidden={viewModeValue.viewMode === "storyboard"}
+ left={
+ <StudioLeftSidebar
+ leftSidebarRef={leftSidebarRef}
+ onSelectComposition={handleSelectComposition}
+ onAddBlock={handleAddBlock}
+ onPreviewBlock={setBlockPreview}
+ onLint={handleLint}
+ linting={linting}
+ lintFindingCount={lintModal?.length ?? findingsByFile.size}
+ lintFindingsByFile={findingsByFile}
+ onAddAssetToTimeline={handleAddAssetAtPlayhead}
/>
- )}
- </div>
+ }
+ right={
+ panelLayout.rightCollapsed ? null : (
+ <StudioRightPanel
+ designPanelActive={designPanelActive}
+ activeBlockParams={activeBlockParams}
+ onCloseBlockParams={() => {
+ setActiveBlockParams(null);
+ panelLayout.setRightPanelTab("design");
+ }}
+ recordingState={gestureState}
+ recordingDuration={gestureRecording.recordingDuration}
+ onToggleRecording={recordingToggle}
+ sdkSession={sdkHandle.session}
+ reloadPreview={reloadPreview}
+ domEditSaveTimestampRef={domEditSaveTimestampRef}
+ recordEdit={editHistory.recordEdit}
+ onToggleElementHidden={timelineEditing.handleToggleElementHidden}
+ />
+ )
+ }
+ timelineToolbar={timelineToolbar}
+ renderClipContent={renderClipContent}
+ handleTimelineElementDelete={timelineEditing.handleTimelineElementDelete}
+ handleTimelineAssetDrop={timelineEditing.handleTimelineAssetDrop}
+ handleTimelineBlockDrop={handleTimelineBlockDrop}
+ handlePreviewBlockDrop={handlePreviewBlockDrop}
+ handleTimelineFileDrop={timelineEditing.handleTimelineFileDrop}
+ handleTimelineElementMove={timelineEditing.handleTimelineElementMove}
+ handleTimelineElementsMove={handleTimelineElementsMove}
+ handleTimelineElementResize={timelineEditing.handleTimelineElementResize}
+ handleTimelineGroupResize={timelineEditing.handleTimelineGroupResize}
+ handleToggleTrackHidden={timelineEditing.handleToggleTrackHidden}
+ handleBlockedTimelineEdit={timelineEditing.handleBlockedTimelineEdit}
+ handleTimelineElementSplit={timelineEditing.handleTimelineElementSplit}
+ handleRazorSplit={timelineEditing.handleRazorSplit}
+ handleRazorSplitAll={timelineEditing.handleRazorSplitAll}
+ setCompIdToSrc={setCompIdToSrc}
+ setCompositionLoading={setCompositionLoading}
+ shouldShowSelectedDomBounds={shouldShowSelectedDomBounds}
+ isGestureRecording={gestureState === "recording"}
+ recordingState={gestureState}
+ onToggleRecording={recordingToggle}
+ blockPreview={blockPreview}
+ gestureOverlay={
+ gestureState === "recording" && previewIframe ? (
+ <GestureTrailOverlay
+ samples={gestureRecording.samplesRef.current}
+ sampleCount={gestureRecording.samplesRef.current.length}
+ trail={gestureRecording.trailRef.current}
+ canvasRect={canvasRectRef.current!}
+ compositionSize={compositionDimensions ?? undefined}
+ mode="recording"
+ />
+ ) : undefined
+ }
+ />
<StudioOverlays
projectId={projectId}
projectDir={fileManager.projectDir}
diff --git a/packages/studio/src/components/EditorShell.tsx b/packages/studio/src/components/EditorShell.tsx
new file mode 100644
index 0000000000..a5d42e732c
--- /dev/null
+++ b/packages/studio/src/components/EditorShell.tsx
@@ -0,0 +1,253 @@
+import { useCallback, type ReactNode } from "react";
+import { PreviewPane } from "./nle/PreviewPane";
+import { TimelinePane } from "./nle/TimelinePane";
+import { PreviewOverlays } from "./nle/PreviewOverlays";
+import {
+ useTimelineEditCallbacks,
+ type TimelineEditCallbackDeps,
+} from "./nle/useTimelineEditCallbacks";
+import { NLEProvider, useNLEContext } from "./nle/NLEContext";
+import { CaptionTimeline } from "../captions/components/CaptionTimeline";
+import { StudioFeedbackBar } from "./StudioFeedbackBar";
+import { useStudioPlaybackContext, useStudioShellContext } from "../contexts/StudioContext";
+import { useDomEditActionsContext } from "../contexts/DomEditContext";
+import { TimelineEditProvider } from "../contexts/TimelineEditContext";
+import type { TimelineElement } from "../player";
+import type { BlockPreviewInfo } from "./sidebar/BlocksTab";
+import type { GestureRecordingState } from "./editor/GestureRecordControl";
+
+type RenderClipContent = (
+ element: TimelineElement,
+ style: { clip: string; label: string },
+) => ReactNode;
+type TimelineDropPlacement = Pick<TimelineElement, "start" | "track">;
+
+// The seven move/resize/split/razor handlers come from TimelineEditCallbackDeps
+// (shared with useTimelineEditCallbacks); the rest are drop + wiring props.
+export interface EditorShellProps extends TimelineEditCallbackDeps {
+ /** Left sidebar (media/library), rendered in the top row. */
+ left: ReactNode;
+ /** Right panel (inspector/design) or null when collapsed, in the top row. */
+ right: ReactNode;
+ /** Hide the whole shell (e.g. while the storyboard view is active). */
+ hidden?: boolean;
+ timelineToolbar: ReactNode;
+ renderClipContent: RenderClipContent;
+ handleTimelineElementDelete: (element: TimelineElement) => Promise<void> | void;
+ handleTimelineAssetDrop: (
+ assetPath: string,
+ placement: TimelineDropPlacement,
+ ) => Promise<void> | void;
+ handleTimelineBlockDrop?: (
+ blockName: string,
+ placement: TimelineDropPlacement,
+ ) => Promise<void> | void;
+ handlePreviewBlockDrop?: (
+ blockName: string,
+ position: { left: number; top: number },
+ ) => Promise<void> | void;
+ handleTimelineFileDrop: (
+ files: File[],
+ placement?: TimelineDropPlacement,
+ ) => Promise<void> | void;
+ setCompIdToSrc: (map: Map<string, string>) => void;
+ setCompositionLoading: (loading: boolean) => void;
+ shouldShowSelectedDomBounds: boolean;
+ blockPreview?: BlockPreviewInfo | null;
+ isGestureRecording?: boolean;
+ recordingState?: GestureRecordingState;
+ onToggleRecording?: () => void;
+ gestureOverlay?: ReactNode;
+}
+
+// The CapCut-style shell: [left | preview | right] in a top row, with a
+// full-width timeline spanning the bottom. Owns the shared player +
+// composition-stack state via NLEProvider so both rows share one player.
+export function EditorShell({
+ left,
+ right,
+ hidden,
+ timelineToolbar,
+ renderClipContent,
+ handleTimelineElementDelete,
+ handleTimelineAssetDrop,
+ handleTimelineBlockDrop,
+ handlePreviewBlockDrop,
+ handleTimelineFileDrop,
+ handleTimelineElementMove,
+ handleTimelineElementsMove,
+ handleTimelineElementResize,
+ handleTimelineGroupResize,
+ handleToggleTrackHidden,
+ handleBlockedTimelineEdit,
+ handleTimelineElementSplit,
+ handleRazorSplit,
+ handleRazorSplitAll,
+ setCompIdToSrc,
+ setCompositionLoading,
+ shouldShowSelectedDomBounds,
+ isGestureRecording,
+ recordingState,
+ onToggleRecording,
+ blockPreview,
+ gestureOverlay,
+}: EditorShellProps) {
+ const { projectId, activeCompPath, setActiveCompPath, handlePreviewIframeRef } =
+ useStudioShellContext();
+ const { refreshKey, captionEditMode, refreshPreviewDocumentVersion } = useStudioPlaybackContext();
+ const { handleTimelineElementSelect } = useDomEditActionsContext();
+
+ const timelineEditCallbacks = useTimelineEditCallbacks({
+ handleTimelineElementMove,
+ handleTimelineElementsMove,
+ handleTimelineElementResize,
+ handleTimelineGroupResize,
+ handleToggleTrackHidden,
+ handleBlockedTimelineEdit,
+ handleTimelineElementSplit,
+ handleRazorSplit,
+ handleRazorSplitAll,
+ });
+
+ return (
+ <div className={`flex flex-col flex-1 min-h-0${hidden ? " hidden" : ""}`}>
+ <TimelineEditProvider value={timelineEditCallbacks}>
+ <NLEProvider
+ projectId={projectId}
+ refreshKey={refreshKey}
+ activeCompositionPath={activeCompPath}
+ onIframeRef={handlePreviewIframeRef}
+ onCompIdToSrcChange={setCompIdToSrc}
+ onCompositionLoadingChange={setCompositionLoading}
+ onCompositionChange={(compPath) => {
+ // Sync activeCompPath when the user drills down via the timeline or
+ // navigates back — keeps sidebar + thumbnails in sync. Guard no-ops to
+ // avoid circular refresh cascades (activeCompPath → stack → onChange).
+ if (compPath !== activeCompPath) {
+ setActiveCompPath(compPath);
+ refreshPreviewDocumentVersion();
+ }
+ }}
+ >
+ <EditorShellBody
+ left={left}
+ right={right}
+ captionEditMode={captionEditMode}
+ onSelectTimelineElement={handleTimelineElementSelect}
+ onPreviewBlockDrop={handlePreviewBlockDrop}
+ timelineToolbar={timelineToolbar}
+ renderClipContent={renderClipContent}
+ onFileDrop={handleTimelineFileDrop}
+ onAssetDrop={handleTimelineAssetDrop}
+ onBlockDrop={handleTimelineBlockDrop}
+ onDeleteElement={handleTimelineElementDelete}
+ previewOverlay={
+ <PreviewOverlays
+ shouldShowSelectedDomBounds={shouldShowSelectedDomBounds}
+ blockPreview={blockPreview}
+ isGestureRecording={isGestureRecording}
+ recordingState={recordingState}
+ onToggleRecording={onToggleRecording}
+ gestureOverlay={gestureOverlay}
+ />
+ }
+ />
+ </NLEProvider>
+ </TimelineEditProvider>
+ <StudioFeedbackBar />
+ </div>
+ );
+}
+
+interface EditorShellBodyProps {
+ left: ReactNode;
+ right: ReactNode;
+ captionEditMode: boolean;
+ previewOverlay: ReactNode;
+ onSelectTimelineElement: (element: TimelineElement | null) => void;
+ onPreviewBlockDrop?: (
+ blockName: string,
+ position: { left: number; top: number },
+ ) => Promise<void> | void;
+ timelineToolbar: ReactNode;
+ renderClipContent: RenderClipContent;
+ onFileDrop: (files: File[], placement?: TimelineDropPlacement) => Promise<void> | void;
+ onAssetDrop: (assetPath: string, placement: TimelineDropPlacement) => Promise<void> | void;
+ onBlockDrop?: (blockName: string, placement: TimelineDropPlacement) => Promise<void> | void;
+ onDeleteElement: (element: TimelineElement) => Promise<void> | void;
+}
+
+function EditorShellBody({
+ left,
+ right,
+ captionEditMode,
+ previewOverlay,
+ onSelectTimelineElement,
+ onPreviewBlockDrop,
+ timelineToolbar,
+ renderClipContent,
+ onFileDrop,
+ onAssetDrop,
+ onBlockDrop,
+ onDeleteElement,
+}: EditorShellBodyProps) {
+ const { compositionStack, updateCompositionStack, containerRef } = useNLEContext();
+
+ // Keyboard: Escape to pop composition level
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (e.key === "Escape" && compositionStack.length > 1) {
+ updateCompositionStack((prev) => prev.slice(0, -1));
+ }
+ },
+ [compositionStack.length, updateCompositionStack],
+ );
+
+ return (
+ <div
+ ref={containerRef}
+ // Shell canvas is a step LIGHTER than the near-black panel cards so the
+ // gaps between panels read as visible seams (CapCut-style).
+ className="flex flex-col flex-1 min-h-0 bg-[#18181B]"
+ onKeyDown={handleKeyDown}
+ tabIndex={-1}
+ >
+ {/* Top row: [left | preview | right] — outer padding + the 8px resize
+ seams give the panels CapCut-style separation on the dark canvas. */}
+ <div className="flex flex-row flex-1 min-h-0 px-px pt-px">
+ {left}
+ <div className="flex-1 min-w-0 flex flex-col relative">
+ <PreviewPane
+ previewOverlay={previewOverlay}
+ onSelectTimelineElement={onSelectTimelineElement}
+ onPreviewBlockDrop={onPreviewBlockDrop}
+ />
+ </div>
+ {right}
+ </div>
+
+ {/* Full-width timeline row */}
+ <TimelinePane
+ timelineToolbar={timelineToolbar}
+ renderClipContent={renderClipContent}
+ onFileDrop={onFileDrop}
+ onAssetDrop={onAssetDrop}
+ onBlockDrop={onBlockDrop}
+ onDeleteElement={onDeleteElement}
+ onSelectTimelineElement={onSelectTimelineElement}
+ timelineFooter={
+ captionEditMode ? (
+ <div className="border-t border-neutral-800/30 flex-shrink-0" style={{ height: 60 }}>
+ <div className="flex items-center gap-1.5 px-2 py-0.5">
+ <span className="text-[9px] font-medium text-neutral-500 uppercase tracking-wider">
+ Captions
+ </span>
+ </div>
+ <CaptionTimeline pixelsPerSecond={100} />
+ </div>
+ ) : undefined
+ }
+ />
+ </div>
+ );
+}
diff --git a/packages/studio/src/components/StudioGlobalDragOverlay.tsx b/packages/studio/src/components/StudioGlobalDragOverlay.tsx
index ecd65cb614..00e562af33 100644
--- a/packages/studio/src/components/StudioGlobalDragOverlay.tsx
+++ b/packages/studio/src/components/StudioGlobalDragOverlay.tsx
@@ -17,9 +17,7 @@ export function StudioGlobalDragOverlay() {
<polyline points="7 10 12 15 17 10" />
<line x1="12" y1="15" x2="12" y2="3" />
</svg>
- <span className="text-sm font-medium text-studio-accent">
- Drop files to import into project
- </span>
+ <span className="text-sm font-medium text-studio-accent">Drop to add at the playhead</span>
</div>
</div>
);
diff --git a/packages/studio/src/components/StudioLeftSidebar.tsx b/packages/studio/src/components/StudioLeftSidebar.tsx
index c4643c5300..d1ebda1387 100644
--- a/packages/studio/src/components/StudioLeftSidebar.tsx
+++ b/packages/studio/src/components/StudioLeftSidebar.tsx
@@ -18,6 +18,7 @@ export interface StudioLeftSidebarProps {
linting: boolean;
lintFindingCount?: number;
lintFindingsByFile?: Map<string, { count: number; messages: string[] }>;
+ onAddAssetToTimeline?: (path: string) => void;
}
// fallow-ignore-next-line complexity
@@ -30,6 +31,7 @@ export function StudioLeftSidebar({
linting,
lintFindingCount,
lintFindingsByFile,
+ onAddAssetToTimeline,
}: StudioLeftSidebarProps) {
const {
leftCollapsed,
@@ -69,7 +71,7 @@ export function StudioLeftSidebar({
if (leftCollapsed) {
return (
- <div className="flex w-10 flex-shrink-0 flex-col items-center border-r border-neutral-800/50 bg-neutral-950 pt-1">
+ <div className="mr-0.5 flex w-10 flex-shrink-0 flex-col items-center rounded-lg border border-neutral-800/50 bg-neutral-950 pt-1">
<button
type="button"
onClick={toggleLeftSidebar}
@@ -147,13 +149,18 @@ export function StudioLeftSidebar({
onToggleCollapse={toggleLeftSidebar}
onAddBlock={onAddBlock}
onPreviewBlock={onPreviewBlock}
+ onAddAssetToTimeline={onAddAssetToTimeline}
/>
+ {/* Vertical resize divider: 3px visible seam, 8px pointer-capture zone via
+ the absolutely-positioned inner hit area. The outer element is w-[3px] so
+ it contributes only 3px of gap in the flex row; the inner -left-[2.5px]
+ element widens the hit area to 8px without affecting layout. */}
<div
role="separator"
aria-label="Resize sidebar"
aria-orientation="vertical"
tabIndex={0}
- className="group w-2 flex-shrink-0 cursor-col-resize flex items-center justify-center outline-none focus-visible:bg-studio-accent/20"
+ className="group relative w-[3px] flex-shrink-0 cursor-col-resize outline-none focus-visible:bg-studio-accent/20"
style={{ touchAction: "none" }}
onPointerDown={(e) => handlePanelResizeStart("left", e)}
onPointerMove={handlePanelResizeMove}
@@ -167,7 +174,10 @@ export function StudioLeftSidebar({
setLeftWidth(Math.max(160, Math.min(maxLeft, leftWidth + delta)));
}}
>
- <div className="h-[52px] w-px bg-white/12 transition-colors group-hover:bg-white/18 group-active:bg-white/24" />
+ {/* Expanded hit zone: 8px wide, centered on the 3px seam */}
+ <div className="absolute inset-y-0 -left-[2.5px] w-2" />
+ {/* Visible hairline */}
+ <div className="absolute top-1/2 left-0 h-[52px] w-[3px] -translate-y-1/2 bg-white/12 transition-colors group-hover:bg-white/18 group-active:bg-white/24" />
</div>
</>
);
diff --git a/packages/studio/src/components/StudioPreviewArea.tsx b/packages/studio/src/components/StudioPreviewArea.tsx
deleted file mode 100644
index c033c828e4..0000000000
--- a/packages/studio/src/components/StudioPreviewArea.tsx
+++ /dev/null
@@ -1,500 +0,0 @@
-import { useState, useMemo, useCallback, type ReactNode } from "react";
-import { NLELayout } from "./nle/NLELayout";
-import { CaptionOverlay } from "../captions/components/CaptionOverlay";
-import { CaptionTimeline } from "../captions/components/CaptionTimeline";
-import { DomEditOverlay } from "./editor/DomEditOverlay";
-import { MotionPathOverlay } from "./editor/MotionPathOverlay";
-import { useCompositionDimensions } from "../hooks/useCompositionDimensions";
-import { SnapToolbar } from "./editor/SnapToolbar";
-import { StudioFeedbackBar } from "./StudioFeedbackBar";
-import type { TimelineElement } from "../player";
-import { usePlayerStore } from "../player/store/playerStore";
-import type { BlockedTimelineEditIntent } from "../player/components/timelineEditing";
-import {
- STUDIO_INSPECTOR_PANELS_ENABLED,
- STUDIO_KEYFRAMES_ENABLED,
- STUDIO_PREVIEW_MANUAL_EDITING_ENABLED,
- STUDIO_PREVIEW_SELECTION_ENABLED,
-} from "./editor/manualEditingAvailability";
-import { useStudioPlaybackContext, useStudioShellContext } from "../contexts/StudioContext";
-import { useDomEditActionsContext, useDomEditSelectionContext } from "../contexts/DomEditContext";
-import { resolveTweenStart, resolveTweenDuration } from "../utils/globalTimeCompiler";
-import { resolveClipTimingBasis } from "../hooks/useGsapTweenCache";
-import { resolveKeyframeRetime } from "./editor/keyframeRetime";
-import { TimelineEditProvider } from "../contexts/TimelineEditContext";
-import type { BlockPreviewInfo } from "./sidebar/BlocksTab";
-import { readStudioUiPreferences } from "../utils/studioUiPreferences";
-import type { GestureRecordingState } from "./editor/GestureRecordControl";
-import { useTimelineSelectionPreviewSync } from "../hooks/useTimelineSelectionPreviewSync";
-import type {
- TimelineGroupMoveChange,
- TimelineGroupResizeChange,
-} from "../hooks/useTimelineGroupEditing";
-import {
- formatTimelineAttributeNumber,
- patchIframeDomTiming,
-} from "../hooks/timelineEditingHelpers";
-
-export interface StudioPreviewAreaProps {
- timelineToolbar: ReactNode;
- renderClipContent: (
- element: TimelineElement,
- style: { clip: string; label: string },
- ) => ReactNode;
- // Timeline editing
- handleTimelineElementDelete: (element: TimelineElement) => Promise<void> | void;
- handleTimelineAssetDrop: (
- assetPath: string,
- placement: Pick<TimelineElement, "start" | "track">,
- ) => Promise<void> | void;
- handleTimelineBlockDrop?: (
- blockName: string,
- placement: Pick<TimelineElement, "start" | "track">,
- ) => Promise<void> | void;
- handlePreviewBlockDrop?: (
- blockName: string,
- position: { left: number; top: number },
- ) => Promise<void> | void;
- handleTimelineFileDrop: (
- files: File[],
- placement?: Pick<TimelineElement, "start" | "track">,
- ) => Promise<void> | void;
- handleTimelineElementMove: (
- element: TimelineElement,
- updates: Pick<TimelineElement, "start" | "track">,
- ) => Promise<void> | void;
- handleTimelineElementResize: (
- element: TimelineElement,
- updates: Pick<TimelineElement, "start" | "duration" | "playbackStart">,
- ) => Promise<void> | void;
- handleTimelineGroupMove: (changes: TimelineGroupMoveChange[]) => Promise<void> | void;
- handleTimelineGroupResize: (changes: TimelineGroupResizeChange[]) => Promise<void> | void;
- handleToggleTrackHidden: (track: number, hidden: boolean) => Promise<void> | void;
- handleToggleElementHidden: (elementKey: string, hidden: boolean) => Promise<void> | void;
- handleBlockedTimelineEdit: (element: TimelineElement, intent: BlockedTimelineEditIntent) => void;
- handleTimelineElementSplit: (element: TimelineElement, splitTime: number) => Promise<void> | void;
- handleRazorSplit: (element: TimelineElement, splitTime: number) => Promise<void> | void;
- handleRazorSplitAll: (splitTime: number) => Promise<void> | void;
- setCompIdToSrc: (map: Map<string, string>) => void;
- setCompositionLoading: (loading: boolean) => void;
- shouldShowSelectedDomBounds: boolean;
- blockPreview?: BlockPreviewInfo | null;
- isGestureRecording?: boolean;
- recordingState?: GestureRecordingState;
- onToggleRecording?: () => void;
- gestureOverlay?: ReactNode;
-}
-
-// fallow-ignore-next-line complexity
-export function StudioPreviewArea({
- timelineToolbar,
- renderClipContent,
- handleTimelineElementDelete,
- handleTimelineAssetDrop,
- handleTimelineBlockDrop,
- handlePreviewBlockDrop,
- handleTimelineFileDrop,
- handleTimelineElementMove,
- handleTimelineElementResize,
- handleTimelineGroupMove,
- handleTimelineGroupResize,
- handleToggleTrackHidden,
- handleToggleElementHidden,
- handleBlockedTimelineEdit,
- handleTimelineElementSplit,
- handleRazorSplit,
- handleRazorSplitAll,
- setCompIdToSrc,
- setCompositionLoading,
- shouldShowSelectedDomBounds,
- isGestureRecording,
- recordingState,
- onToggleRecording,
- blockPreview,
- gestureOverlay,
-}: StudioPreviewAreaProps) {
- const {
- projectId,
- activeCompPath,
- setActiveCompPath,
- previewIframeRef,
- handlePreviewIframeRef,
- timelineVisible,
- toggleTimelineVisibility,
- } = useStudioShellContext();
- const {
- refreshKey,
- captionEditMode,
- compositionLoading,
- isPlaying,
- refreshPreviewDocumentVersion,
- } = useStudioPlaybackContext();
- const compositionDimensions = useCompositionDimensions();
-
- const {
- domEditHoverSelection,
- domEditSelection,
- domEditGroupSelections,
- selectedGsapAnimations,
- } = useDomEditSelectionContext();
- const {
- handleTimelineElementSelect,
- handlePreviewCanvasMouseDown,
- handlePreviewCanvasPointerMove,
- handlePreviewCanvasPointerLeave,
- applyDomSelection,
- handleBlockedDomMove,
- handleDomManualDragStart,
- handleDomPathOffsetCommit,
- handleDomGroupPathOffsetCommit,
- handleDomBoxSizeCommit,
- handleDomRotationCommit,
- handleDomStyleCommit,
- handleGsapRemoveKeyframe,
- handleGsapMoveKeyframeToPlayhead,
- handleGsapMoveKeyframe,
- handleGsapResizeKeyframedTween,
- handleGsapUpdateMeta,
- handleGsapAddKeyframe,
- handleGsapConvertToKeyframes,
- handleGsapRemoveAllKeyframes,
- buildDomSelectionForTimelineElement,
- applyMarqueeSelection,
- } = useDomEditActionsContext();
- const selectedElementId = usePlayerStore((s) => s.selectedElementId);
- const selectedElementIds = usePlayerStore((s) => s.selectedElementIds);
- const timelineElements = usePlayerStore((s) => s.elements);
-
- // fallow-ignore-next-line complexity
- const [snapPrefs, setSnapPrefs] = useState(() => {
- const p = readStudioUiPreferences();
- return {
- snapEnabled: p.snapEnabled ?? true,
- gridVisible: p.gridVisible ?? false,
- gridSpacing: p.gridSpacing ?? 50,
- snapToGrid: p.snapToGrid ?? false,
- };
- });
-
- useTimelineSelectionPreviewSync({
- selectedElementId,
- selectedElementIds,
- timelineElements,
- domEditSelection,
- domEditGroupSelections,
- activeCompPath,
- buildDomSelectionForTimelineElement,
- applyDomSelection,
- applyMarqueeSelection,
- });
-
- // Resolve a timeline-diamond callback's clip-% to the keyframe's anim id + its
- // tween-relative percentage (shared by the delete/move keyframe callbacks): the
- // diamond reports a clip-% but the script ops key on the tween-%. Prefers the
- // anim in the keyframe's property group, falling back to the first keyframed one.
- const resolveKeyframeTarget = useCallback(
- // fallow-ignore-next-line complexity
- (pct: number): { animId: string; tweenPct: number } | null => {
- const cached = usePlayerStore.getState().keyframeCache.get(domEditSelection?.id ?? "");
- const kf = cached?.keyframes.find((k) => Math.abs(k.percentage - pct) < 0.2);
- const group = kf?.propertyGroup;
- const anim =
- (group ? selectedGsapAnimations.find((a) => a.propertyGroup === group) : undefined) ??
- selectedGsapAnimations.find((a) => a.keyframes);
- return anim ? { animId: anim.id, tweenPct: kf?.tweenPercentage ?? pct } : null;
- },
- [domEditSelection?.id, selectedGsapAnimations],
- );
-
- const handleTimelineGroupMovePreview = useCallback(
- (changes: TimelineGroupMoveChange[]) => {
- for (const change of changes) {
- patchIframeDomTiming(previewIframeRef.current, change.element, [
- ["data-start", formatTimelineAttributeNumber(change.start)],
- ]);
- }
- },
- [previewIframeRef],
- );
-
- const handleTimelineGroupResizePreview = useCallback(
- (changes: TimelineGroupResizeChange[]) => {
- for (const change of changes) {
- const attrs: Array<[string, string]> = [
- ["data-start", formatTimelineAttributeNumber(change.start)],
- ["data-duration", formatTimelineAttributeNumber(change.duration)],
- ];
- if (change.playbackStart != null) {
- attrs.push([
- change.element.playbackStartAttr === "playback-start"
- ? "data-playback-start"
- : "data-media-start",
- formatTimelineAttributeNumber(change.playbackStart),
- ]);
- }
- patchIframeDomTiming(previewIframeRef.current, change.element, attrs);
- }
- },
- [previewIframeRef],
- );
-
- // fallow-ignore-next-line complexity
- const timelineEditCallbacks = useMemo(
- () => ({
- onMoveElement: handleTimelineElementMove,
- onResizeElement: handleTimelineElementResize,
- onMoveElements: handleTimelineGroupMove,
- onResizeElements: handleTimelineGroupResize,
- onPreviewMoveElements: handleTimelineGroupMovePreview,
- onPreviewResizeElements: handleTimelineGroupResizePreview,
- onToggleTrackHidden: handleToggleTrackHidden,
- onToggleElementHidden: handleToggleElementHidden,
- onBlockedEditAttempt: handleBlockedTimelineEdit,
- onSplitElement: handleTimelineElementSplit,
- onRazorSplit: handleRazorSplit,
- onRazorSplitAll: handleRazorSplitAll,
- onDeleteAllKeyframes: () => {
- // Hold the element where it is (collapse keyframes to a static set) rather
- // than deleting the whole animation, deleting strands a stale GSAP base
- // that the next drag adds to, flinging the element off-screen.
- const anim = selectedGsapAnimations.find((a) => a.keyframes);
- if (!anim) return;
- handleGsapRemoveAllKeyframes(anim.id);
- },
- onDeleteKeyframe: (_elId: string, pct: number) => {
- const target = resolveKeyframeTarget(pct);
- if (target) handleGsapRemoveKeyframe(target.animId, target.tweenPct);
- },
- // Retime the keyframe to the playhead, preserving its value + ease.
- onMoveKeyframeToPlayhead: (_elId: string, pct: number) => {
- const target = resolveKeyframeTarget(pct);
- if (target) handleGsapMoveKeyframeToPlayhead(target.animId, target.tweenPct);
- },
- // Drag-to-retime. The diamond reports clip-%s; resolveKeyframeTarget gives
- // the dragged keyframe's anim + tween-%. We convert the clip-% drop to an
- // absolute time (via the clip's timing basis) and let resolveKeyframeRetime
- // decide: a drop inside the tween window is a plain move (re-key tween-%); a
- // drop past the boundary (last keyframe past the end, first before the start)
- // resizes the tween, position/duration grow so the dragged keyframe lands at
- // the drop while every other keyframe keeps its absolute time (value+ease too).
- // fallow-ignore-next-line complexity
- onMoveKeyframe: (_elId: string, fromClipPct: number, toClipPct: number) => {
- const target = resolveKeyframeTarget(fromClipPct);
- const sel = domEditSelection;
- if (!target || !sel) return;
- const anim = selectedGsapAnimations.find((a) => a.id === target.animId);
- const tweenStart = anim ? resolveTweenStart(anim) : null;
- if (!anim || tweenStart === null) return;
- const tweenDuration = anim.duration ?? resolveTweenDuration(anim);
- const sourceFile = sel.sourceFile || activeCompPath || "index.html";
- const { elements, domClipChildren } = usePlayerStore.getState();
- const { elStart, elDuration } = resolveClipTimingBasis(
- sel.id ?? "",
- sourceFile,
- elements,
- domClipChildren,
- );
- const dropAbsTime = elStart + (toClipPct / 100) * elDuration;
- const decision = resolveKeyframeRetime({
- keyframes: anim.keyframes?.keyframes ?? [],
- draggedTweenPct: target.tweenPct,
- tweenStart,
- tweenDuration,
- dropAbsTime,
- });
- if (decision.kind === "move" && decision.toTweenPct != null) {
- handleGsapMoveKeyframe(target.animId, target.tweenPct, decision.toTweenPct);
- } else if (
- decision.kind === "resize" &&
- decision.pctRemap &&
- decision.position != null &&
- decision.duration != null
- ) {
- handleGsapResizeKeyframedTween(
- target.animId,
- decision.position,
- decision.duration,
- decision.pctRemap,
- );
- }
- },
- onChangeKeyframeEase: (_elId: string, _pct: number, ease: string) => {
- for (const anim of selectedGsapAnimations) {
- if (anim.keyframes) handleGsapUpdateMeta(anim.id, { ease });
- }
- },
- // fallow-ignore-next-line complexity
- onToggleKeyframeAtPlayhead: (el: TimelineElement) => {
- const currentTime = usePlayerStore.getState().currentTime;
- const pct =
- el.duration > 0
- ? Math.max(0, Math.min(100, Math.round(((currentTime - el.start) / el.duration) * 100)))
- : 0;
- const anim = selectedGsapAnimations.find((a) => a.keyframes);
- if (anim?.keyframes) {
- const existing = anim.keyframes.keyframes.find((k) => Math.abs(k.percentage - pct) <= 1);
- if (existing) {
- handleGsapRemoveKeyframe(anim.id, existing.percentage);
- } else {
- handleGsapAddKeyframe(anim.id, pct, "x", 0);
- }
- } else {
- const flatAnim = selectedGsapAnimations.find((a) => !a.keyframes);
- if (flatAnim) handleGsapConvertToKeyframes(flatAnim.id);
- }
- },
- }),
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [
- handleTimelineElementMove,
- handleTimelineElementResize,
- handleTimelineGroupMove,
- handleTimelineGroupMovePreview,
- handleTimelineGroupResize,
- handleTimelineGroupResizePreview,
- handleToggleTrackHidden,
- handleToggleElementHidden,
- handleBlockedTimelineEdit,
- handleTimelineElementSplit,
- handleRazorSplit,
- handleRazorSplitAll,
- handleGsapRemoveAllKeyframes,
- resolveKeyframeTarget,
- selectedGsapAnimations,
- handleGsapRemoveKeyframe,
- handleGsapMoveKeyframeToPlayhead,
- handleGsapMoveKeyframe,
- handleGsapResizeKeyframedTween,
- handleGsapUpdateMeta,
- handleGsapAddKeyframe,
- handleGsapConvertToKeyframes,
- buildDomSelectionForTimelineElement,
- projectId,
- activeCompPath,
- domEditSelection,
- ],
- );
-
- return (
- <div className="flex-1 flex flex-col relative min-w-0">
- <div className="flex-1 min-h-0 relative">
- <TimelineEditProvider value={timelineEditCallbacks}>
- <NLELayout
- projectId={projectId}
- refreshKey={refreshKey}
- activeCompositionPath={activeCompPath}
- timelineToolbar={timelineToolbar}
- renderClipContent={renderClipContent}
- onDeleteElement={handleTimelineElementDelete}
- onAssetDrop={handleTimelineAssetDrop}
- onBlockDrop={handleTimelineBlockDrop}
- onPreviewBlockDrop={handlePreviewBlockDrop}
- onFileDrop={handleTimelineFileDrop}
- onSelectTimelineElement={handleTimelineElementSelect}
- onCompIdToSrcChange={setCompIdToSrc}
- onCompositionLoadingChange={setCompositionLoading}
- onCompositionChange={(compPath) => {
- // Sync activeCompPath when user drills down via timeline double-click
- // or navigates back via breadcrumb, keeps sidebar + thumbnails in sync.
- // Guard against no-op updates to prevent circular refresh cascades
- // between activeCompPath → compositionStack → onCompositionChange.
- if (compPath !== activeCompPath) {
- setActiveCompPath(compPath);
- refreshPreviewDocumentVersion();
- }
- }}
- onIframeRef={handlePreviewIframeRef}
- previewOverlay={
- blockPreview ? (
- <div className="absolute inset-0 z-30 bg-black pointer-events-none">
- {blockPreview.videoUrl ? (
- <video
- src={blockPreview.videoUrl}
- autoPlay
- muted
- loop
- playsInline
- className="w-full h-full object-contain"
- />
- ) : blockPreview.posterUrl ? (
- <img
- src={blockPreview.posterUrl}
- alt={blockPreview.title}
- className="w-full h-full object-contain"
- />
- ) : null}
- </div>
- ) : captionEditMode ? (
- <CaptionOverlay iframeRef={previewIframeRef} />
- ) : STUDIO_INSPECTOR_PANELS_ENABLED ? (
- <>
- <DomEditOverlay
- iframeRef={previewIframeRef}
- activeCompositionPath={activeCompPath}
- hoverSelection={
- STUDIO_PREVIEW_SELECTION_ENABLED &&
- !captionEditMode &&
- !compositionLoading &&
- !isPlaying
- ? domEditHoverSelection
- : null
- }
- selection={shouldShowSelectedDomBounds ? domEditSelection : null}
- groupSelections={shouldShowSelectedDomBounds ? domEditGroupSelections : []}
- allowCanvasMovement={
- STUDIO_PREVIEW_MANUAL_EDITING_ENABLED && !isGestureRecording
- }
- onCanvasMouseDown={handlePreviewCanvasMouseDown}
- onCanvasPointerMove={handlePreviewCanvasPointerMove}
- onCanvasPointerLeave={handlePreviewCanvasPointerLeave}
- onSelectionChange={applyDomSelection}
- onBlockedMove={handleBlockedDomMove}
- onManualDragStart={handleDomManualDragStart}
- onPathOffsetCommit={handleDomPathOffsetCommit}
- onGroupPathOffsetCommit={handleDomGroupPathOffsetCommit}
- onBoxSizeCommit={handleDomBoxSizeCommit}
- onRotationCommit={handleDomRotationCommit}
- onStyleCommit={handleDomStyleCommit}
- gridVisible={snapPrefs.gridVisible}
- gridSpacing={snapPrefs.gridSpacing}
- recordingState={recordingState}
- onToggleRecording={onToggleRecording}
- onMarqueeSelect={applyMarqueeSelection}
- />
- <SnapToolbar onSnapChange={setSnapPrefs} />
- {STUDIO_KEYFRAMES_ENABLED && (
- <MotionPathOverlay
- iframeRef={previewIframeRef}
- selection={shouldShowSelectedDomBounds ? domEditSelection : null}
- compositionSize={compositionDimensions}
- isPlaying={isPlaying}
- />
- )}
- {gestureOverlay}
- </>
- ) : null
- }
- timelineFooter={
- captionEditMode ? (
- <div
- className="border-t border-neutral-800/30 flex-shrink-0"
- style={{ height: 60 }}
- >
- <div className="flex items-center gap-1.5 px-2 py-0.5">
- <span className="text-[9px] font-medium text-neutral-500 uppercase tracking-wider">
- Captions
- </span>
- </div>
- <CaptionTimeline pixelsPerSecond={100} />
- </div>
- ) : undefined
- }
- timelineVisible={timelineVisible}
- onToggleTimeline={toggleTimelineVisibility}
- />
- </TimelineEditProvider>
- </div>
- <StudioFeedbackBar />
- </div>
- );
-}
diff --git a/packages/studio/src/components/StudioRightPanel.tsx b/packages/studio/src/components/StudioRightPanel.tsx
index c65fd3d0c4..652876c2bb 100644
--- a/packages/studio/src/components/StudioRightPanel.tsx
+++ b/packages/studio/src/components/StudioRightPanel.tsx
@@ -446,12 +446,14 @@ export function StudioRightPanel({
return (
<>
+ {/* Vertical resize divider: 3px visible seam, 8px pointer-capture zone via
+ the absolutely-positioned inner hit area. */}
<div
role="separator"
aria-label="Resize inspector panel"
aria-orientation="vertical"
tabIndex={0}
- className="group w-2 flex-shrink-0 cursor-col-resize flex items-center justify-center outline-none focus-visible:bg-studio-accent/20"
+ className="group relative w-[3px] flex-shrink-0 cursor-col-resize outline-none focus-visible:bg-studio-accent/20"
style={{ touchAction: "none" }}
onPointerDown={(e) => handlePanelResizeStart("right", e)}
onPointerMove={handlePanelResizeMove}
@@ -465,10 +467,13 @@ export function StudioRightPanel({
setRightWidth(Math.max(160, Math.min(600, rightWidth + delta)));
}}
>
- <div className="h-[52px] w-px bg-white/12 transition-colors group-hover:bg-white/18 group-active:bg-white/24" />
+ {/* Expanded hit zone: 8px wide, centered on the 3px seam */}
+ <div className="absolute inset-y-0 -left-[2.5px] w-2" />
+ {/* Visible hairline */}
+ <div className="absolute top-1/2 left-0 h-[52px] w-[3px] -translate-y-1/2 bg-white/12 transition-colors group-hover:bg-white/18 group-active:bg-white/24" />
</div>
<div
- className="flex min-w-0 flex-shrink-0 flex-col overflow-hidden border-l border-neutral-800 bg-neutral-900"
+ className="flex min-w-0 flex-shrink-0 flex-col overflow-hidden rounded-lg border border-neutral-800 bg-neutral-900"
style={{ width: rightWidth }}
>
{captionEditMode ? (
diff --git a/packages/studio/src/components/TimelineToolbar.test.tsx b/packages/studio/src/components/TimelineToolbar.test.tsx
index 5ee23d5af3..0c21e5e043 100644
--- a/packages/studio/src/components/TimelineToolbar.test.tsx
+++ b/packages/studio/src/components/TimelineToolbar.test.tsx
@@ -2,7 +2,7 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it } from "vitest";
import { usePlayerStore } from "../player/store/playerStore";
import { TimelineToolbar } from "./TimelineToolbar";
@@ -18,7 +18,7 @@ function renderToolbar() {
document.body.append(host);
const root = createRoot(host);
act(() => {
- root.render(<TimelineToolbar toggleTimelineVisibility={vi.fn()} />);
+ root.render(<TimelineToolbar />);
});
return { host, root };
}
diff --git a/packages/studio/src/components/TimelineToolbar.tsx b/packages/studio/src/components/TimelineToolbar.tsx
index eff6db2062..1e314ed4ef 100644
--- a/packages/studio/src/components/TimelineToolbar.tsx
+++ b/packages/studio/src/components/TimelineToolbar.tsx
@@ -1,4 +1,5 @@
-import { useRef } from "react";
+import { useEffect, useRef } from "react";
+import { Magnet, MagnifyingGlassMinus, MagnifyingGlassPlus } from "@phosphor-icons/react";
import {
useEnableKeyframes,
isPlayheadWithinTween,
@@ -9,9 +10,10 @@ import { useKeyframeKeyboard } from "../hooks/useKeyframeKeyboard";
import {
getNextTimelineZoomPercent,
getTimelineZoomPercent,
+ timelineZoomPercentToSlider,
+ timelineSliderToZoomPercent,
} from "../player/components/timelineZoom";
import { useTimelineZoom } from "../player/components/useTimelineZoom";
-import { getTimelineToggleTitle } from "../utils/timelineDiscovery";
import { usePlayerStore, type TimelineElement } from "../player";
import {
STUDIO_KEYFRAMES_ENABLED,
@@ -30,7 +32,6 @@ interface DomEditSessionSlice extends EnableKeyframesSession {
}
interface TimelineToolbarProps {
- toggleTimelineVisibility: () => void;
domEditSession?: DomEditSessionSlice;
onSplitElement?: (element: TimelineElement, splitTime: number) => void;
}
@@ -72,18 +73,20 @@ function useKeyframeToggle(session?: DomEditSessionSlice) {
}
// fallow-ignore-next-line complexity
-export function TimelineToolbar({
- toggleTimelineVisibility,
- domEditSession,
- onSplitElement,
-}: TimelineToolbarProps) {
+export function TimelineToolbar({ domEditSession, onSplitElement }: TimelineToolbarProps) {
const activeTool = usePlayerStore((s) => s.activeTool);
const setActiveTool = usePlayerStore((s) => s.setActiveTool);
+ const timelineSnapEnabled = usePlayerStore((s) => s.timelineSnapEnabled);
+ const setTimelineSnapEnabled = usePlayerStore((s) => s.setTimelineSnapEnabled);
const autoKeyframeEnabled = usePlayerStore((s) => s.autoKeyframeEnabled);
const setAutoKeyframeEnabled = usePlayerStore((s) => s.setAutoKeyframeEnabled);
// Subscribe so the add-beat button reacts to playhead movement and analysis load.
const currentTime = usePlayerStore((s) => s.currentTime);
const beatAnalysisReady = usePlayerStore((s) => s.beatAnalysis !== null);
+ // Subscribe (not getState) so the split button enables/disables the moment
+ // the selection changes, not only on the next playhead tick.
+ const selectedElementId = usePlayerStore((s) => s.selectedElementId);
+ const elements = usePlayerStore((s) => s.elements);
const { zoomMode, manualZoomPercent, setZoomMode, setManualZoomPercent } = useTimelineZoom();
const displayedTimelineZoomPercent = getTimelineZoomPercent(zoomMode, manualZoomPercent);
const {
@@ -99,28 +102,48 @@ export function TimelineToolbar({
onAddKeyframe: onToggleKeyframe,
});
+ // "N" toggles timeline snapping (industry convention: Resolve/FCP).
+ // Skip when typing in an input/contenteditable.
+ useEffect(() => {
+ // fallow-ignore-next-line complexity
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.key !== "n" && e.key !== "N") return;
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
+ const target = e.target instanceof HTMLElement ? e.target : null;
+ if (target?.isContentEditable) return;
+ const tag = target?.tagName?.toLowerCase() ?? "";
+ if (tag === "input" || tag === "textarea" || tag === "select") return;
+ const store = usePlayerStore.getState();
+ store.setTimelineSnapEnabled(!store.timelineSnapEnabled);
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, []);
+
+ // CapCut-flat icon buttons: no per-button border/box chrome — a transparent
+ // 28px hit area with a subtle rounded hover wash, consistent 16px glyphs.
+ const flatBtn = "flex h-7 w-7 items-center justify-center rounded-md transition-colors";
+ const flatIdle = `${flatBtn} text-neutral-400 hover:bg-white/[0.06] hover:text-neutral-200 active:scale-[0.98]`;
+ const flatActive = `${flatBtn} bg-white/[0.08] text-neutral-100 active:scale-[0.98]`;
+ const flatDisabled = `${flatBtn} text-neutral-700 cursor-not-allowed`;
+
return (
- <div className="border-b border-neutral-800/40 bg-neutral-950/96">
- <div className="flex items-center justify-between px-3 py-2">
- <div className="flex items-center gap-3">
- <div className="text-[10px] font-medium uppercase tracking-[0.16em] text-neutral-500">
- Timeline
- </div>
+ // The "TIMELINE" label is dropped for CapCut-like density — the pane's
+ // position (tracks right below) makes it self-evident.
+ <div className="border-b border-neutral-800/60">
+ <div className="flex items-center justify-between px-2 py-0.5">
+ <div className="flex items-center gap-0.5">
{STUDIO_RAZOR_TOOL_ENABLED && (
- <div className="flex items-center border border-neutral-800 rounded overflow-hidden">
+ <>
<Tooltip label="Selection tool (V)">
<button
type="button"
onClick={() => setActiveTool("select")}
aria-label="Selection tool"
aria-pressed={activeTool === "select"}
- className={`flex h-6 w-6 items-center justify-center transition-colors active:scale-[0.98] ${
- activeTool === "select"
- ? "bg-neutral-700 text-neutral-200"
- : "text-neutral-500 hover:text-neutral-300"
- }`}
+ className={activeTool === "select" ? flatActive : flatIdle}
>
- <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
+ <svg width="16" height="16" viewBox="0 0 12 12" fill="currentColor">
<path d="M2 0.5L10 6L6.5 6.5L8.5 11L6.5 11.5L4.5 7L2 9Z" />
</svg>
</button>
@@ -131,46 +154,65 @@ export function TimelineToolbar({
onClick={() => setActiveTool("razor")}
aria-label="Razor tool"
aria-pressed={activeTool === "razor"}
- className={`flex h-6 w-6 items-center justify-center transition-colors active:scale-[0.98] ${
- activeTool === "razor"
- ? "bg-neutral-700 text-neutral-200"
- : "text-neutral-500 hover:text-neutral-300"
- }`}
+ className={activeTool === "razor" ? flatActive : flatIdle}
>
- <Scissors size={11} />
+ <Scissors size={16} />
</button>
</Tooltip>
- </div>
+ {/* Divider: tool-mode | editing-actions */}
+ <div aria-hidden="true" className="mx-1 h-4 w-px bg-neutral-800" />
+ </>
)}
- {STUDIO_KEYFRAMES_ENABLED && onToggleKeyframe && (
+ <Tooltip label={timelineSnapEnabled ? "Snapping on (N)" : "Snapping off (N)"}>
+ <button
+ type="button"
+ onClick={() => setTimelineSnapEnabled(!timelineSnapEnabled)}
+ aria-label="Toggle timeline snapping"
+ aria-pressed={timelineSnapEnabled}
+ className={timelineSnapEnabled ? flatActive : flatIdle}
+ >
+ <Magnet size={16} weight="bold" aria-hidden="true" />
+ </button>
+ </Tooltip>
+ {STUDIO_KEYFRAMES_ENABLED && (
+ // Always rendered (CapCut-style): with no keyframeable selection the
+ // button fades to a disabled state instead of unmounting, so the
+ // toolbar layout never shifts.
<Tooltip
label={
- keyframeState === "active"
- ? "Remove keyframe at playhead (K)"
- : keyframeState === "inactive"
- ? keyframeWillExtend
- ? "Add keyframe at playhead, extends animation (K)"
- : "Add keyframe at playhead (K)"
- : "Add keyframe (K)"
+ !onToggleKeyframe
+ ? "Select an animated element to add keyframes"
+ : keyframeState === "active"
+ ? "Remove keyframe at playhead (K)"
+ : keyframeState === "inactive"
+ ? keyframeWillExtend
+ ? "Add keyframe at playhead, extends animation (K)"
+ : "Add keyframe at playhead (K)"
+ : "Add keyframe (K)"
}
>
<button
type="button"
+ disabled={!onToggleKeyframe}
onClick={onToggleKeyframe}
aria-label={
keyframeState === "active"
? "Remove keyframe at playhead"
: "Add keyframe at playhead"
}
- className={`flex h-7 w-7 items-center justify-center rounded transition-colors active:scale-[0.98] ${
- keyframeState === "active"
- ? "text-studio-accent"
- : keyframeState === "inactive"
- ? "text-neutral-400 hover:text-studio-accent"
- : "text-neutral-600 hover:text-neutral-400"
- }`}
+ className={
+ !onToggleKeyframe
+ ? flatDisabled
+ : `${flatBtn} active:scale-[0.98] hover:bg-white/[0.06] ${
+ keyframeState === "active"
+ ? "text-studio-accent"
+ : keyframeState === "inactive"
+ ? "text-neutral-400 hover:text-studio-accent"
+ : "text-neutral-600 hover:text-neutral-400"
+ }`
+ }
>
- <svg width="18" height="18" viewBox="0 0 10 10" fill="currentColor">
+ <svg width="16" height="16" viewBox="0 0 10 10" fill="currentColor">
{keyframeState === "active" ? (
<path d="M5 0.5L9.5 5L5 9.5L0.5 5Z" />
) : (
@@ -198,13 +240,13 @@ export function TimelineToolbar({
onClick={() => setAutoKeyframeEnabled(!autoKeyframeEnabled)}
aria-label="Auto-record manual edits as keyframes"
aria-pressed={autoKeyframeEnabled}
- className={`flex h-7 w-7 items-center justify-center rounded transition-colors active:scale-[0.98] ${
+ className={`${flatBtn} active:scale-[0.98] hover:bg-white/[0.06] ${
autoKeyframeEnabled
? "text-red-400 hover:text-red-300"
: "text-neutral-600 hover:text-neutral-400"
}`}
>
- <svg width="18" height="18" viewBox="0 0 10 10" fill="none">
+ <svg width="16" height="16" viewBox="0 0 10 10" fill="none">
{/* Same diamond outline as the Add-keyframe icon, with a
record-style dot inside: filled = auto-recording,
hollow = manual edits won't be keyframed. */}
@@ -225,7 +267,7 @@ export function TimelineToolbar({
(() => {
// Render the button unconditionally (disabled when unusable):
// mounting/unmounting mid-task shifts the neighboring controls.
- const { selectedElementId, elements, currentTime } = usePlayerStore.getState();
+ // Mirrors the S-key gate: selected clip + playhead strictly inside it.
const el = selectedElementId
? elements.find((e) => (e.key ?? e.id) === selectedElementId)
: null;
@@ -236,7 +278,7 @@ export function TimelineToolbar({
<Tooltip
label={
canSplit
- ? "Split clip at playhead (S)"
+ ? "Split at playhead (S)"
: splittable
? "Move the playhead inside the clip to split"
: "Select a clip to split"
@@ -245,64 +287,84 @@ export function TimelineToolbar({
<button
type="button"
disabled={!canSplit}
- aria-label="Split clip at playhead"
+ aria-label="Split at playhead"
onClick={() => {
if (canSplit && el) onSplitElement(el, currentTime);
}}
- className={`flex h-7 w-7 items-center justify-center rounded transition-colors ${
- canSplit
- ? "text-neutral-500 hover:text-neutral-200 active:scale-[0.98]"
- : "text-neutral-700 cursor-not-allowed"
- }`}
- >
- <Scissors size={15} />
- </button>
- </Tooltip>
- );
- })()}
- {beatAnalysisReady &&
- (() => {
- const canAdd = canAddBeatAt(currentTime);
- return (
- <Tooltip
- label={canAdd ? "Add beat at playhead" : "A beat already exists at the playhead"}
- >
- <button
- type="button"
- disabled={!canAdd}
- aria-label="Add beat at playhead"
- onClick={() => {
- if (canAdd) addBeatAtCompositionTime(currentTime);
- }}
- className={`flex h-7 w-7 items-center justify-center rounded transition-colors ${
- canAdd
- ? "text-neutral-500 hover:text-[#22c55e] active:scale-[0.98]"
- : "text-neutral-700 cursor-not-allowed"
- }`}
+ className={canSplit ? flatIdle : flatDisabled}
>
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
- <path
- d="M21 10C21 12.2091 16.9706 14 12 14M21 10C21 7.79086 16.9706 6 12 6C7.02944 6 3 7.79086 3 10M21 10V16C21 18.2091 16.9706 20 12 20M12 14C7.02944 14 3 12.2091 3 10M12 14V20M3 10V16C3 18.2091 7.02944 20 12 20M7 19.3264V13.3264M17 19.3264V13.3264M12 10L20 4"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
+ {/* "][" split glyph: two outward-facing brackets with a center gap */}
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 16 16"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.6"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden="true"
+ >
+ {/* Right bracket of left half: ] */}
+ <path d="M5 3 L7 3 L7 13 L5 13" />
+ {/* Left bracket of right half: [ */}
+ <path d="M11 3 L9 3 L9 13 L11 13" />
</svg>
</button>
</Tooltip>
);
})()}
+ {(() => {
+ // Always rendered (CapCut-style): before beat analysis loads (or when
+ // the project has no analyzed music) the button fades to a disabled
+ // state instead of unmounting, so the toolbar layout never shifts.
+ const canAdd = beatAnalysisReady && canAddBeatAt(currentTime);
+ return (
+ <Tooltip
+ label={
+ !beatAnalysisReady
+ ? "Add a music track with beat analysis to place beats"
+ : canAdd
+ ? "Add beat at playhead"
+ : "A beat already exists at the playhead"
+ }
+ >
+ <button
+ type="button"
+ disabled={!canAdd}
+ aria-label="Add beat at playhead"
+ onClick={() => {
+ if (canAdd) addBeatAtCompositionTime(currentTime);
+ }}
+ className={
+ canAdd
+ ? `${flatBtn} text-neutral-400 hover:bg-white/[0.06] hover:text-[#22c55e] active:scale-[0.98]`
+ : flatDisabled
+ }
+ >
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
+ <path
+ d="M21 10C21 12.2091 16.9706 14 12 14M21 10C21 7.79086 16.9706 6 12 6C7.02944 6 3 7.79086 3 10M21 10V16C21 18.2091 16.9706 20 12 20M12 14C7.02944 14 3 12.2091 3 10M12 14V20M3 10V16C3 18.2091 7.02944 20 12 20M7 19.3264V13.3264M17 19.3264V13.3264M12 10L20 4"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ </button>
+ </Tooltip>
+ );
+ })()}
</div>
- <div className="flex items-center gap-1">
+ <div className="flex items-center gap-0.5">
<Tooltip label="Fit timeline to width">
<button
type="button"
onClick={() => setZoomMode("fit")}
- className={`h-7 px-2.5 rounded-md border text-[11px] font-medium transition-colors ${
+ className={`h-7 px-2 rounded-md text-[11px] font-medium transition-colors ${
zoomMode === "fit"
- ? "border-studio-accent/30 bg-studio-accent/10 text-studio-accent"
- : "border-neutral-800 text-neutral-400 hover:border-neutral-700 hover:text-neutral-200"
+ ? "bg-studio-accent/10 text-studio-accent"
+ : "text-neutral-400 hover:bg-white/[0.06] hover:text-neutral-200"
}`}
>
Fit
@@ -311,55 +373,51 @@ export function TimelineToolbar({
<Tooltip label="Zoom out">
<button
type="button"
+ aria-label="Zoom out"
onClick={() => {
setZoomMode("manual");
setManualZoomPercent(
getNextTimelineZoomPercent("out", zoomMode, manualZoomPercent),
);
}}
- className="h-7 w-7 rounded-md border border-neutral-800 text-neutral-400 transition-colors hover:border-neutral-700 hover:text-neutral-200"
+ className={flatIdle}
>
- -
+ <MagnifyingGlassMinus size={16} aria-hidden="true" />
</button>
</Tooltip>
- <div className="min-w-[58px] text-center text-[10px] font-medium tabular-nums text-neutral-500">
- {`${displayedTimelineZoomPercent}%`}
- </div>
+ <input
+ type="range"
+ min="0"
+ max="100"
+ value={timelineZoomPercentToSlider(displayedTimelineZoomPercent)}
+ title={`${displayedTimelineZoomPercent}%`}
+ aria-label="Timeline zoom"
+ onChange={(e) => {
+ setZoomMode("manual");
+ setManualZoomPercent(timelineSliderToZoomPercent(Number(e.target.value)));
+ }}
+ className="mx-1 w-[96px] cursor-pointer appearance-none bg-transparent [&::-webkit-slider-runnable-track]:h-[2px] [&::-webkit-slider-runnable-track]:rounded-full [&::-webkit-slider-runnable-track]:bg-neutral-700 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-[10px] [&::-webkit-slider-thumb]:h-[10px] [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:-mt-1 [&::-webkit-slider-thumb]:shadow-[0_0_0_2px_#0a0a0a,0_1px_3px_rgba(0,0,0,0.5)] [&::-webkit-slider-thumb]:cursor-grab [&::-webkit-slider-thumb:active]:cursor-grabbing"
+ />
<Tooltip label="Zoom in">
<button
type="button"
+ aria-label="Zoom in"
onClick={() => {
setZoomMode("manual");
setManualZoomPercent(getNextTimelineZoomPercent("in", zoomMode, manualZoomPercent));
}}
- className="h-7 w-7 rounded-md border border-neutral-800 text-neutral-400 transition-colors hover:border-neutral-700 hover:text-neutral-200"
+ className={flatIdle}
>
- +
- </button>
- </Tooltip>
- <Tooltip label={getTimelineToggleTitle(true)}>
- <button
- type="button"
- onClick={toggleTimelineVisibility}
- className="ml-1 flex h-7 w-7 items-center justify-center rounded-md text-neutral-500 transition-colors hover:bg-neutral-900 hover:text-neutral-200"
- aria-label="Hide timeline editor"
- >
- <svg
- width="14"
- height="14"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.8"
- strokeLinecap="round"
- strokeLinejoin="round"
- aria-hidden="true"
- >
- <path d="M5 7h14" />
- <path d="m8 11 4 4 4-4" />
- </svg>
+ <MagnifyingGlassPlus size={16} aria-hidden="true" />
</button>
</Tooltip>
+ {/* Numeric zoom readout (main-parity): "Fit" in fit mode, N% in manual. */}
+ <span
+ className="ml-1 w-[38px] text-right font-mono text-[11px] tabular-nums text-neutral-500 select-none"
+ aria-label="Timeline zoom level"
+ >
+ {zoomMode === "fit" ? "Fit" : `${displayedTimelineZoomPercent}%`}
+ </span>
</div>
</div>
</div>
diff --git a/packages/studio/src/components/editor/DomEditCropHandles.test.tsx b/packages/studio/src/components/editor/DomEditCropHandles.test.tsx
index 09c73deccd..1ea0381352 100644
--- a/packages/studio/src/components/editor/DomEditCropHandles.test.tsx
+++ b/packages/studio/src/components/editor/DomEditCropHandles.test.tsx
@@ -1,7 +1,7 @@
// @vitest-environment happy-dom
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import type { DomEditSelection } from "./domEditing";
import type { OverlayRect } from "./domEditOverlayGeometry";
import { DomEditCropHandles } from "./DomEditCropHandles";
@@ -33,7 +33,10 @@ function makeEl(id: string, clip: string): HTMLElement {
return el;
}
-function render(el: HTMLElement): { root: Root; rerender: (next: HTMLElement) => void } {
+function render(
+ el: HTMLElement,
+ onStyleCommit: (property: string, value: string) => Promise<void> | void = () => undefined,
+): { root: Root; rerender: (next: HTMLElement) => void } {
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
@@ -43,7 +46,7 @@ function render(el: HTMLElement): { root: Root; rerender: (next: HTMLElement) =>
<DomEditCropHandles
selection={selectionFor(target)}
overlayRect={overlayRect}
- onStyleCommit={() => undefined}
+ onStyleCommit={onStyleCommit}
/>,
);
});
@@ -83,4 +86,72 @@ describe("DomEditCropHandles clip lift/restore", () => {
act(() => root.unmount());
expect(a.style.getPropertyValue("clip-path")).toBe("circle(50% at 50% 50%)");
});
+
+ it("re-lifts synchronously after the commit path re-applies the cropped value", async () => {
+ const a = makeEl("a", "inset(10px)");
+ let resolveCommit: (() => void) | undefined;
+ const pendingCommit = new Promise<void>((resolve) => {
+ resolveCommit = resolve;
+ });
+ const onStyleCommit = vi.fn((property: string, value: string) => {
+ a.style.setProperty(property, value);
+ return pendingCommit;
+ });
+ const { root } = render(a, onStyleCommit);
+ const handle = document.querySelector<HTMLButtonElement>('[aria-label="Crop right"]');
+ expect(handle).toBeTruthy();
+
+ act(() =>
+ handle!.dispatchEvent(
+ new PointerEvent("pointerdown", { bubbles: true, pointerId: 1, clientX: 100 }),
+ ),
+ );
+ act(() =>
+ handle!.dispatchEvent(
+ new PointerEvent("pointermove", { bubbles: true, pointerId: 1, clientX: 80 }),
+ ),
+ );
+ act(() =>
+ handle!.dispatchEvent(
+ new PointerEvent("pointerup", { bubbles: true, pointerId: 1, clientX: 80 }),
+ ),
+ );
+
+ expect(onStyleCommit).toHaveBeenCalledWith("clip-path", "inset(10px 30px 10px 10px)");
+ expect(a.style.getPropertyValue("clip-path")).toBe("none");
+ resolveCommit?.();
+ await act(async () => pendingCommit);
+ act(() => root.unmount());
+ expect(a.style.getPropertyValue("clip-path")).toBe("inset(10px 30px 10px 10px)");
+ });
+
+ it("re-lifts when the crop commit rejects", async () => {
+ const a = makeEl("a", "inset(10px)");
+ const onStyleCommit = vi.fn((property: string, value: string) => {
+ a.style.setProperty(property, value);
+ return Promise.reject(new Error("persist failed"));
+ });
+ const { root } = render(a, onStyleCommit);
+ const handle = document.querySelector<HTMLButtonElement>('[aria-label="Crop right"]');
+
+ act(() =>
+ handle!.dispatchEvent(
+ new PointerEvent("pointerdown", { bubbles: true, pointerId: 2, clientX: 100 }),
+ ),
+ );
+ act(() =>
+ handle!.dispatchEvent(
+ new PointerEvent("pointermove", { bubbles: true, pointerId: 2, clientX: 80 }),
+ ),
+ );
+ await act(async () => {
+ handle!.dispatchEvent(
+ new PointerEvent("pointerup", { bubbles: true, pointerId: 2, clientX: 80 }),
+ );
+ await Promise.resolve();
+ });
+
+ expect(a.style.getPropertyValue("clip-path")).toBe("none");
+ act(() => root.unmount());
+ });
});
diff --git a/packages/studio/src/components/editor/DomEditCropHandles.tsx b/packages/studio/src/components/editor/DomEditCropHandles.tsx
index 7ac3b485b0..5dc5050c30 100644
--- a/packages/studio/src/components/editor/DomEditCropHandles.tsx
+++ b/packages/studio/src/components/editor/DomEditCropHandles.tsx
@@ -31,12 +31,16 @@ interface DomEditCropHandlesProps {
onStyleCommit?: (property: string, value: string) => Promise<void> | void;
}
-// Gap (px) between an edge handle and the element edge, so the handle sits
-// clear of the element body and can't intercept a move-drag.
-const EDGE_HANDLE_GAP = 8;
+// Hit-strip size (px) for an edge crop handle: THICKNESS extends outward from
+// the crop edge (flush against it, never over the element body, so a body
+// drag always MOVES), LENGTH runs along the edge. The visible pill is smaller
+// and centered inside the strip.
+const EDGE_HIT_THICKNESS = 12;
+const EDGE_HIT_LENGTH = 32;
-/** Place an edge handle just OUTSIDE the given crop edge (translate pushes it
- * fully past the boundary). Keeps the element body free for moving. */
+/** Place an edge handle's hit strip just OUTSIDE the given crop edge
+ * (translate pushes it fully past the boundary). Keeps the element body free
+ * for moving. Corners stay free for the selection's own resize handles. */
function edgeHandlePlacement(
edge: CropEdge,
rect: { left: number; top: number; width: number; height: number },
@@ -44,27 +48,36 @@ function edgeHandlePlacement(
const cx = rect.left + rect.width / 2;
const cy = rect.top + rect.height / 2;
if (edge === "top") {
- return { left: cx, top: rect.top - EDGE_HANDLE_GAP, transform: "translate(-50%, -100%)" };
+ return { left: cx, top: rect.top, transform: "translate(-50%, -100%)" };
}
if (edge === "bottom") {
- return {
- left: cx,
- top: rect.top + rect.height + EDGE_HANDLE_GAP,
- transform: "translate(-50%, 0)",
- };
+ return { left: cx, top: rect.top + rect.height, transform: "translate(-50%, 0)" };
}
if (edge === "left") {
- return { left: rect.left - EDGE_HANDLE_GAP, top: cy, transform: "translate(-100%, -50%)" };
+ return { left: rect.left, top: cy, transform: "translate(-100%, -50%)" };
}
- return {
- left: rect.left + rect.width + EDGE_HANDLE_GAP,
- top: cy,
- transform: "translate(0, -50%)",
- };
+ return { left: rect.left + rect.width, top: cy, transform: "translate(0, -50%)" };
}
const EDGES: CropEdge[] = ["top", "right", "bottom", "left"];
+/** Hit-strip + pill dimensions for an edge handle, keyed on its orientation. */
+function edgeHandleMetrics(vertical: boolean): {
+ hitWidth: number;
+ hitHeight: number;
+ cursor: string;
+ pillWidth: number;
+ pillHeight: number;
+} {
+ return {
+ hitWidth: vertical ? EDGE_HIT_THICKNESS : EDGE_HIT_LENGTH,
+ hitHeight: vertical ? EDGE_HIT_LENGTH : EDGE_HIT_THICKNESS,
+ cursor: vertical ? "ew-resize" : "ns-resize",
+ pillWidth: vertical ? 4 : 24,
+ pillHeight: vertical ? 24 : 4,
+ };
+}
+
/**
* Always-on crop, integrated with the selection (no crop "mode"): while a
* croppable element is selected its clip is lifted so the FULL content shows and
@@ -83,6 +96,7 @@ export function DomEditCropHandles({
}: DomEditCropHandlesProps) {
const gestureRef = useRef<CropGestureState | null>(null);
const [dragging, setDragging] = useState(false);
+ const [hotEdge, setHotEdge] = useState<CropEdge | null>(null);
// readElementCropInsets returns null for a clip this tool can't represent
// (circle/polygon/non-px inset): the crop UI must fully stand down for that
// element — no lift, no handles — or select+deselect replaces the authored
@@ -209,10 +223,9 @@ export function DomEditCropHandles({
setDragging(false);
if (!gesture.didMove) return;
// Commit to the file. The commit path re-applies the value to the live
- // element, so re-lift afterwards to keep showing the full content + dim while
- // the element stays selected. Re-lift on both fulfilment and rejection so a
- // failed commit still restores the crop-mode presentation (and the rejection
- // is handled rather than left unhandled).
+ // element synchronously, so re-lift in the same turn to keep showing the full
+ // content + dim while selected. Re-lift again on rejection so a failed commit
+ // still restores crop-mode presentation without an unhandled rejection.
const el = selection.element;
const reLift = () => {
if (liftedRef.current) el.style.setProperty("clip-path", "none");
@@ -223,12 +236,16 @@ export function DomEditCropHandles({
state.insets.right > 0 ||
state.insets.bottom > 0 ||
state.insets.left > 0;
- void Promise.resolve(onStyleCommit?.("clip-path", committedValue)).then(() => {
+ const commit = onStyleCommit?.("clip-path", committedValue);
+ // handleDomStyleCommit applies the persisted value to the live element
+ // synchronously before its first await. Restore the crop-mode lift in this
+ // same turn so the browser never paints that intermediate cropped state.
+ reLift();
+ void Promise.resolve(commit).then(() => {
// Only a landed commit makes the rebuilt inset the restore value; a
// failed one keeps restoring the pre-lift clip. Store the value itself —
// by deselect time, render state describes the next selection.
committedClipRef.current = cropped ? committedValue : "";
- reLift();
}, reLift);
};
@@ -304,6 +321,7 @@ export function DomEditCropHandles({
<button
type="button"
aria-label="Reposition crop"
+ title="Reposition crop"
data-dom-edit-crop-handle="true"
className="pointer-events-auto absolute rounded-full border-2 border-studio-accent bg-studio-accent/30 shadow-[0_0_0_1px_rgba(0,0,0,0.4)]"
style={{
@@ -323,31 +341,48 @@ export function DomEditCropHandles({
)}
{/* Edge handles — drag a side to crop it. Positioned just OUTSIDE the crop
edge (via edgeHandlePlacement) so they never overlap the element body:
- dragging the body always MOVES, only a handle crops. */}
+ dragging the body always MOVES, only a handle crops. The pill is
+ hover-revealed (or shown while dragging / once a crop exists) so the
+ resting selection chrome stays uncluttered; the hit strip is always
+ live, and the title names the affordance. */}
{EDGES.map((edge) => {
const vertical = edge === "left" || edge === "right";
const place = edgeHandlePlacement(edge, cropRect);
+ const revealed = dragging || hasCrop || hotEdge === edge;
+ const m = edgeHandleMetrics(vertical);
return (
<button
key={edge}
type="button"
aria-label={`Crop ${edge}`}
+ title="Crop"
data-dom-edit-crop-handle="true"
- className="pointer-events-auto absolute rounded-full bg-studio-accent shadow-[0_0_0_1px_rgba(0,0,0,0.4)]"
+ className="pointer-events-auto absolute flex items-center justify-center border-0 bg-transparent p-0"
style={{
left: place.left,
top: place.top,
- width: vertical ? 5 : 26,
- height: vertical ? 26 : 5,
+ width: m.hitWidth,
+ height: m.hitHeight,
transform: place.transform,
- cursor: vertical ? "ew-resize" : "ns-resize",
+ cursor: m.cursor,
touchAction: "none",
}}
+ onPointerEnter={() => setHotEdge(edge)}
+ onPointerLeave={() => setHotEdge((prev) => (prev === edge ? null : prev))}
onPointerDown={(event) => startCropGesture(edge, event)}
onPointerMove={updateCropGesture}
onPointerUp={finishCropGesture}
onPointerCancel={cancelCropGesture}
- />
+ >
+ <span
+ className="pointer-events-none rounded-full bg-studio-accent/90 shadow-[0_0_0_1px_rgba(0,0,0,0.4)] transition-opacity duration-100"
+ style={{
+ width: m.pillWidth,
+ height: m.pillHeight,
+ opacity: revealed ? 1 : 0,
+ }}
+ />
+ </button>
);
})}
</div>
diff --git a/packages/studio/src/components/editor/DomEditOverlay.test.ts b/packages/studio/src/components/editor/DomEditOverlay.test.ts
index fbc8eccb26..736bd7ecb2 100644
--- a/packages/studio/src/components/editor/DomEditOverlay.test.ts
+++ b/packages/studio/src/components/editor/DomEditOverlay.test.ts
@@ -11,10 +11,10 @@ import {
hasDomEditRotationChanged,
resolveDomEditCoordinateScale,
resolveDomEditGroupOverlayRect,
- resolveDomEditResizeGesture,
resolveDomEditRotationGesture,
} from "./DomEditOverlay";
import type { DomEditSelection } from "./domEditing";
+import { resolveResizeCenterAnchorOffset } from "./domEditOverlayGestures";
// React 19 warns unless the test environment opts into act().
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
@@ -84,21 +84,37 @@ vi.mock("./useDomEditOverlayRects", async () => {
};
});
+const previewHelperSpies = vi.hoisted(() => ({
+ getPreviewTargetFromPointer: vi.fn<() => HTMLElement | null>(() => null),
+}));
+
+vi.mock("../../utils/studioPreviewHelpers", async () => {
+ const actual = await vi.importActual<typeof import("../../utils/studioPreviewHelpers")>(
+ "../../utils/studioPreviewHelpers",
+ );
+ return {
+ ...actual,
+ getPreviewTargetFromPointer: previewHelperSpies.getPreviewTargetFromPointer,
+ };
+});
+
vi.mock("./domEditOverlayGeometry", async () => {
const actual = await vi.importActual<typeof import("./domEditOverlayGeometry")>(
"./domEditOverlayGeometry",
);
+ const stubRect = {
+ left: 24,
+ top: 36,
+ width: 180,
+ height: 72,
+ editScaleX: 1,
+ editScaleY: 1,
+ };
return {
...actual,
- toOverlayRect: () => ({
- left: 24,
- top: 36,
- width: 180,
- height: 72,
- editScaleX: 1,
- editScaleY: 1,
- }),
+ toOverlayRect: () => stubRect,
+ orientedOverlayRect: () => stubRect,
};
});
@@ -126,6 +142,103 @@ function createOverlayProps(args: {
};
}
+/**
+ * Stub element-level getBoundingClientRect to a fixed 800×450 rect (happy-dom
+ * returns all-zeros for unlaid-out elements, which gates the RAF compRect
+ * update). Returns a restore function to call in teardown.
+ */
+function stubViewportRect(): () => void {
+ const original = Element.prototype.getBoundingClientRect;
+ Element.prototype.getBoundingClientRect = function (): DOMRect {
+ return {
+ left: 0,
+ top: 0,
+ right: 800,
+ bottom: 450,
+ width: 800,
+ height: 450,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ };
+ };
+ return () => {
+ Element.prototype.getBoundingClientRect = original;
+ };
+}
+
+/**
+ * Flush the mount's RAF ticks so the compRect update lands. Two animation-frame
+ * ticks: the first scheduled by useMountEffect's update(), the second by
+ * update()'s tail recursion.
+ */
+async function flushOverlayRaf(): Promise<void> {
+ await act(async () => {
+ await new Promise<void>((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
+ });
+ });
+}
+
+/** A fully-populated DomEditSelection with per-test overrides (capabilities are
+ * merged so a test can flip a single flag without restating the whole set). */
+function makeDomEditSelection(
+ overrides: Partial<DomEditSelection> = {},
+ capabilityOverrides: Partial<DomEditSelection["capabilities"]> = {},
+): DomEditSelection {
+ const base: DomEditSelection = {
+ element: document.createElement("div"),
+ id: "hero-title",
+ selector: ".hero-title",
+ selectorIndex: 0,
+ sourceFile: "index.html",
+ tagName: "div",
+ label: "Hero Title",
+ textContent: "Hello",
+ textFields: [],
+ capabilities: {
+ canEditText: true,
+ canEditLayout: true,
+ canMove: true,
+ canApplyManualOffset: true,
+ canApplyManualSize: false,
+ canApplyManualRotation: false,
+ canAdjustOpacity: true,
+ canAdjustFill: true,
+ canAdjustBorderRadius: true,
+ canAdjustStroke: true,
+ canAdjustShadow: true,
+ canAdjustZIndex: true,
+ },
+ computedStyle: {
+ display: "block",
+ position: "absolute",
+ },
+ };
+ return {
+ ...base,
+ ...overrides,
+ capabilities: { ...base.capabilities, ...capabilityOverrides },
+ };
+}
+
+/** Query the composition-canvas overlay and assert it mounted. */
+function getOverlay(host: HTMLElement): HTMLDivElement {
+ const overlay = host.querySelector<HTMLDivElement>('[aria-label="Composition canvas"]');
+ expect(overlay).toBeTruthy();
+ if (!overlay) throw new Error("Expected composition canvas overlay");
+ return overlay;
+}
+
+/** Dispatch a left-button pointerdown at (clientX, clientY) inside act(). */
+function dispatchOverlayPointerDown(target: Element, clientX = 120, clientY = 80): void {
+ act(() => {
+ target.dispatchEvent(
+ new PointerEvent("pointerdown", { bubbles: true, button: 0, clientX, clientY }),
+ );
+ });
+}
+
describe("focusDomEditOverlayElement", () => {
it("focuses the canvas overlay without scrolling", () => {
const calls: Array<FocusOptions | undefined> = [];
@@ -144,41 +257,84 @@ describe("DomEditOverlay", () => {
gestureSpies.onPointerMove.mockClear();
gestureSpies.onPointerUp.mockClear();
gestureSpies.clearPointerState.mockClear();
+ previewHelperSpies.getPreviewTargetFromPointer.mockReset();
+ previewHelperSpies.getPreviewTargetFromPointer.mockReturnValue(null);
+ });
+
+ it("selects on the first click over an element even before a hover is resolved", async () => {
+ // Regression: this used to start a marquee whenever hoverSelectionRef was null.
+ // The RAF hover loop populates that ref ASYNCHRONOUSLY, so a genuine first
+ // click over an element read null and was misread as empty canvas — the
+ // marquee swallowed the selecting onMouseDown, so nothing selected until the
+ // SECOND click. With a synchronous pointer hit-test finding an element, the
+ // marquee must NOT start and onCanvasMouseDown must fire on the first click.
+ const restoreRect = stubViewportRect();
+ const originalPointerCapture = HTMLDivElement.prototype.setPointerCapture;
+ HTMLDivElement.prototype.setPointerCapture = () => {};
+
+ // An element IS under the pointer, but no hover has been resolved yet.
+ previewHelperSpies.getPreviewTargetFromPointer.mockReturnValue(document.createElement("div"));
+
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ const iframeRef = { current: document.createElement("iframe") as HTMLIFrameElement | null };
+ const onCanvasMouseDown = vi.fn();
+ const onMarqueeSelect = vi.fn();
+
+ function Harness() {
+ return React.createElement(DomEditOverlay, {
+ ...createOverlayProps({
+ iframeRef,
+ selection: null,
+ hoverSelection: null,
+ onSelectionChange: () => {},
+ }),
+ onCanvasMouseDown,
+ onMarqueeSelect,
+ });
+ }
+
+ act(() => {
+ root.render(React.createElement(Harness));
+ });
+ await flushOverlayRaf();
+
+ const overlay = getOverlay(host);
+
+ act(() => {
+ overlay.dispatchEvent(
+ new PointerEvent("pointerdown", { bubbles: true, button: 0, clientX: 120, clientY: 80 }),
+ );
+ overlay.dispatchEvent(
+ new MouseEvent("mousedown", { bubbles: true, button: 0, clientX: 120, clientY: 80 }),
+ );
+ });
+
+ // No marquee started; the click reached the selecting mouse-down handler.
+ expect(onMarqueeSelect).not.toHaveBeenCalled();
+ expect(onCanvasMouseDown).toHaveBeenCalledTimes(1);
+
+ act(() => {
+ root.unmount();
+ });
+ HTMLDivElement.prototype.setPointerCapture = originalPointerCapture;
+ restoreRect();
+ host.remove();
});
it("does not start a drag from a stale hover target on canvas pointer-down", () => {
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
- const selection: DomEditSelection = {
- element: document.createElement("div"),
+ const selection = makeDomEditSelection({
id: "cta-label",
selector: ".cta-label",
- selectorIndex: 0,
- sourceFile: "index.html",
tagName: "span",
label: "CTA Label",
textContent: "Add to basket",
- textFields: [],
- capabilities: {
- canEditText: true,
- canEditLayout: true,
- canMove: true,
- canApplyManualOffset: true,
- canApplyManualSize: false,
- canApplyManualRotation: false,
- canAdjustOpacity: true,
- canAdjustFill: true,
- canAdjustBorderRadius: true,
- canAdjustStroke: true,
- canAdjustShadow: true,
- canAdjustZIndex: true,
- },
- computedStyle: {
- display: "inline",
- position: "static",
- },
- };
+ computedStyle: { display: "inline", position: "static" },
+ });
let currentSelection: DomEditSelection | null = null;
const iframeRef = { current: document.createElement("iframe") as HTMLIFrameElement | null };
@@ -202,19 +358,9 @@ describe("DomEditOverlay", () => {
root.render(React.createElement(Harness));
});
- const overlay = host.querySelector('[aria-label="Composition canvas"]') as HTMLDivElement;
- expect(overlay).toBeTruthy();
+ const overlay = getOverlay(host);
- act(() => {
- overlay.dispatchEvent(
- new PointerEvent("pointerdown", {
- bubbles: true,
- button: 0,
- clientX: 120,
- clientY: 80,
- }),
- );
- });
+ dispatchOverlayPointerDown(overlay);
expect(gestureSpies.startGesture).not.toHaveBeenCalled();
expect(currentSelection).toBe(null);
@@ -233,53 +379,12 @@ describe("DomEditOverlay", () => {
// box (and other bounded UI) behind `compRect.width > 0` (added in the
// keyframes PR a468550f). Stub element-level getBoundingClientRect for
// the test so the RAF compRect update produces a real width.
- const originalGetBoundingClientRect = Element.prototype.getBoundingClientRect;
- Element.prototype.getBoundingClientRect = function (): DOMRect {
- return {
- left: 0,
- top: 0,
- right: 800,
- bottom: 450,
- width: 800,
- height: 450,
- x: 0,
- y: 0,
- toJSON: () => ({}),
- };
- };
+ const restoreRect = stubViewportRect();
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
- const selection: DomEditSelection = {
- element: document.createElement("div"),
- id: "hero-title",
- selector: ".hero-title",
- selectorIndex: 0,
- sourceFile: "index.html",
- tagName: "div",
- label: "Hero Title",
- textContent: "Hello",
- textFields: [],
- capabilities: {
- canEditText: true,
- canEditLayout: true,
- canMove: true,
- canApplyManualOffset: true,
- canApplyManualSize: false,
- canApplyManualRotation: false,
- canAdjustOpacity: true,
- canAdjustFill: true,
- canAdjustBorderRadius: true,
- canAdjustStroke: true,
- canAdjustShadow: true,
- canAdjustZIndex: true,
- },
- computedStyle: {
- display: "block",
- position: "absolute",
- },
- };
+ const selection = makeDomEditSelection();
let currentSelection: DomEditSelection | null = selection;
const iframeRef = { current: document.createElement("iframe") as HTMLIFrameElement | null };
@@ -307,30 +412,16 @@ describe("DomEditOverlay", () => {
// Flush the mount's RAF tick so the compRect update lands before the
// pointer-down. Two animation-frame ticks: the first scheduled by
// useMountEffect's update(), the second by update()'s tail recursion.
- await act(async () => {
- await new Promise<void>((resolve) => {
- requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
- });
- });
+ await flushOverlayRaf();
- const overlay = host.querySelector('[aria-label="Composition canvas"]') as HTMLDivElement;
- expect(overlay).toBeTruthy();
+ getOverlay(host);
const selectionBox = host.querySelector(
'[data-dom-edit-selection-box="true"]',
) as HTMLDivElement;
expect(selectionBox).toBeTruthy();
- act(() => {
- selectionBox.dispatchEvent(
- new PointerEvent("pointerdown", {
- bubbles: true,
- button: 0,
- clientX: 120,
- clientY: 80,
- }),
- );
- });
+ dispatchOverlayPointerDown(selectionBox);
expect(currentSelection).toBe(selection);
expect(gestureSpies.startGesture).toHaveBeenCalledWith(
@@ -342,58 +433,17 @@ describe("DomEditOverlay", () => {
root.unmount();
});
HTMLDivElement.prototype.setPointerCapture = originalPointerCapture;
- Element.prototype.getBoundingClientRect = originalGetBoundingClientRect;
+ restoreRect();
host.remove();
});
it("passes the tracked hover selection when clicking the existing selection box", async () => {
- const originalGetBoundingClientRect = Element.prototype.getBoundingClientRect;
- Element.prototype.getBoundingClientRect = function (): DOMRect {
- return {
- left: 0,
- top: 0,
- right: 800,
- bottom: 450,
- width: 800,
- height: 450,
- x: 0,
- y: 0,
- toJSON: () => ({}),
- };
- };
+ const restoreRect = stubViewportRect();
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
- const selection: DomEditSelection = {
- element: document.createElement("div"),
- id: "hero-title",
- selector: ".hero-title",
- selectorIndex: 0,
- sourceFile: "index.html",
- tagName: "div",
- label: "Hero Title",
- textContent: "Hello",
- textFields: [],
- capabilities: {
- canEditText: true,
- canEditLayout: true,
- canMove: false,
- canApplyManualOffset: false,
- canApplyManualSize: false,
- canApplyManualRotation: false,
- canAdjustOpacity: true,
- canAdjustFill: true,
- canAdjustBorderRadius: true,
- canAdjustStroke: true,
- canAdjustShadow: true,
- canAdjustZIndex: true,
- },
- computedStyle: {
- display: "block",
- position: "absolute",
- },
- };
+ const selection = makeDomEditSelection({}, { canMove: false, canApplyManualOffset: false });
const hoverSelection: DomEditSelection = { ...selection, id: "hovered-sibling" };
const onCanvasMouseDown = vi.fn();
const iframeRef = { current: document.createElement("iframe") as HTMLIFrameElement | null };
@@ -414,11 +464,7 @@ describe("DomEditOverlay", () => {
root.render(React.createElement(Harness));
});
- await act(async () => {
- await new Promise<void>((resolve) => {
- requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
- });
- });
+ await flushOverlayRaf();
const selectionBox = host.querySelector(
'[data-dom-edit-selection-box="true"]',
@@ -437,7 +483,7 @@ describe("DomEditOverlay", () => {
act(() => {
root.unmount();
});
- Element.prototype.getBoundingClientRect = originalGetBoundingClientRect;
+ restoreRect();
host.remove();
});
});
@@ -513,130 +559,10 @@ describe("filterNestedDomEditGroupItems", () => {
});
});
-describe("resolveDomEditResizeGesture", () => {
- it("resizes width and height independently by default", () => {
- expect(
- resolveDomEditResizeGesture({
- originWidth: 240,
- originHeight: 120,
- actualWidth: 240,
- actualHeight: 120,
- scaleX: 1,
- scaleY: 1,
- dx: 30,
- dy: 12,
- uniform: false,
- }),
- ).toEqual({
- overlayWidth: 270,
- overlayHeight: 132,
- width: 270,
- height: 132,
- });
- });
-
- it("divides the cursor delta by the element's content scale (rescaled element)", () => {
- // Element renders at 2x via a GSAP scale: a 30px cursor delta must grow the
- // CSS box by only 15px so the RENDERED box tracks the pointer 1:1.
- const next = resolveDomEditResizeGesture({
- originWidth: 480, // 240 css x 2 content scale (overlay px at editScale 1)
- originHeight: 240,
- actualWidth: 240,
- actualHeight: 120,
- scaleX: 1,
- scaleY: 1,
- contentScaleX: 2,
- contentScaleY: 2,
- dx: 30,
- dy: 12,
- uniform: false,
- });
- expect(next.width).toBe(255);
- expect(next.height).toBe(126);
- // The overlay box keeps tracking the raw cursor.
- expect(next.overlayWidth).toBe(510);
- expect(next.overlayHeight).toBe(252);
- });
-
- it("treats a missing/invalid content scale as 1 (unscaled element)", () => {
- const next = resolveDomEditResizeGesture({
- originWidth: 240,
- originHeight: 120,
- actualWidth: 240,
- actualHeight: 120,
- scaleX: 1,
- scaleY: 1,
- contentScaleX: 0,
- contentScaleY: Number.NaN,
- dx: 30,
- dy: 12,
- uniform: false,
- });
- expect(next.width).toBe(270);
- expect(next.height).toBe(132);
- });
-
- it("snaps width and height to the same value when Shift is held", () => {
- expect(
- resolveDomEditResizeGesture({
- originWidth: 240,
- originHeight: 120,
- actualWidth: 240,
- actualHeight: 120,
- scaleX: 1,
- scaleY: 1,
- dx: 30,
- dy: 12,
- uniform: true,
- }),
- ).toEqual({
- overlayWidth: 270,
- overlayHeight: 270,
- width: 270,
- height: 270,
- });
- });
-
- it("uses the dominant pointer delta for uniform shrink", () => {
- expect(
- resolveDomEditResizeGesture({
- originWidth: 300,
- originHeight: 180,
- actualWidth: 300,
- actualHeight: 180,
- scaleX: 1,
- scaleY: 1,
- dx: 8,
- dy: -40,
- uniform: true,
- }),
- ).toMatchObject({
- width: 260,
- height: 260,
- });
- });
-
- it("writes source-local dimensions when the edited source is scaled down in master view", () => {
- expect(
- resolveDomEditResizeGesture({
- originWidth: 100,
- originHeight: 50,
- actualWidth: 400,
- actualHeight: 200,
- scaleX: 0.25,
- scaleY: 0.25,
- dx: 25,
- dy: 10,
- uniform: false,
- }),
- ).toEqual({
- overlayWidth: 125,
- overlayHeight: 60,
- width: 500,
- height: 240,
- });
- });
-});
+// Note: the resize SIZE math moved from the AABB screen-space
+// resolveDomEditResizeGesture (removed) to the local-space (OBB) model in
+// domEditResizeLocal.ts — see domEditResizeLocal.test.ts, which re-covers the
+// independent-axis, aspect-lock, and scaled-master-view cases plus rotated axes.
describe("resolveDomEditRotationGesture", () => {
it("rotates by the pointer angle around the element center", () => {
@@ -701,3 +627,43 @@ describe("resolveDomEditRotationGesture", () => {
expect(hasDomEditRotationChanged(0, 0)).toBe(false);
});
});
+
+// resolveResizeCenterAnchorOffset is the UNROTATED (AABB) fallback used only when
+// the element's real transformed corners can't be measured. Center-anchored: a
+// width/height change grows the box from its top-left, drifting the center by half
+// the size change per axis, so the pin translates back by that half-delta. It is
+// handle-independent — all four corners scale about the same center.
+describe("resolveResizeCenterAnchorOffset", () => {
+ it("grow: translates back by half the size change on both axes", () => {
+ expect(
+ resolveResizeCenterAnchorOffset({
+ originWidth: 200,
+ originHeight: 100,
+ overlayWidth: 230,
+ overlayHeight: 112,
+ }),
+ ).toEqual({ dx: -15, dy: -6 });
+ });
+
+ it("shrink: translates forward by half the (positive) size change", () => {
+ expect(
+ resolveResizeCenterAnchorOffset({
+ originWidth: 200,
+ originHeight: 100,
+ overlayWidth: 160,
+ overlayHeight: 80,
+ }),
+ ).toEqual({ dx: 20, dy: 10 });
+ });
+
+ it("no size change: zero offset", () => {
+ expect(
+ resolveResizeCenterAnchorOffset({
+ originWidth: 200,
+ originHeight: 100,
+ overlayWidth: 200,
+ overlayHeight: 100,
+ }),
+ ).toEqual({ dx: 0, dy: 0 });
+ });
+});
diff --git a/packages/studio/src/components/editor/DomEditOverlay.tsx b/packages/studio/src/components/editor/DomEditOverlay.tsx
index c0adaef18c..e410f2c9d6 100644
--- a/packages/studio/src/components/editor/DomEditOverlay.tsx
+++ b/packages/studio/src/components/editor/DomEditOverlay.tsx
@@ -1,5 +1,4 @@
-import { memo, useEffect, useMemo, useRef, useState, type RefObject } from "react";
-import { getPreviewTargetFromPointer } from "../../utils/studioPreviewHelpers";
+import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import { type DomEditSelection } from "./domEditing";
import type { PreviewMouseDownOptions } from "../../hooks/usePreviewInteraction";
import { useMarqueeGestures } from "./marqueeCommit";
@@ -16,17 +15,20 @@ import {
import { useDomEditOverlayRects } from "./useDomEditOverlayRects";
import { OffCanvasIndicators, type OffCanvasRect } from "./OffCanvasIndicators";
import { createDomEditOverlayGestureHandlers } from "./useDomEditOverlayGestures";
+import { useDomEditNudge } from "./useDomEditNudge";
import { SnapGuideOverlay, type SnapGuidesState } from "./SnapGuideOverlay";
import { GridOverlay } from "./GridOverlay";
import type { GestureRecordingState } from "./GestureRecordControl";
-import { DomEditCropHandles } from "./DomEditCropHandles";
-import { DomEditRotateHandle } from "./DomEditRotateHandle";
+import { DomEditGroupChrome, DomEditSelectionChrome } from "./DomEditSelectionChrome";
import { hugRectForElement } from "./domEditOverlayCrop";
import { useCropOverlay } from "../../hooks/useCropOverlay";
import { readDomEditSelectionShapeStyles, resolveBoxChromeClass } from "./domEditOverlayShape";
import { useDomEditCompositionRect } from "./useDomEditCompositionRect";
import { useMountEffect } from "../../hooks/useMountEffect";
import { startOffCanvasIndicatorRefresh } from "./offCanvasIndicatorRefresh";
+import { CanvasContextMenu } from "./CanvasContextMenu";
+import type { ZOrderPatch } from "./canvasContextMenuZOrder";
+import { getPreviewTargetFromPointer } from "../../utils/studioPreviewHelpers";
// Re-exports for external consumers — preserving existing import paths.
export {
@@ -37,7 +39,6 @@ export {
export {
focusDomEditOverlayElement,
hasDomEditRotationChanged,
- resolveDomEditResizeGesture,
resolveDomEditRotationGesture,
} from "./domEditOverlayGestures";
export type { DomEditGroupPathOffsetCommit } from "./domEditOverlayGestures";
@@ -73,6 +74,8 @@ interface DomEditOverlayProps {
onBoxSizeCommit: (
selection: DomEditSelection,
next: { width: number; height: number },
+ offset?: { x: number; y: number },
+ restore?: () => void,
) => Promise<void> | void;
onRotationCommit: (selection: DomEditSelection, next: { angle: number }) => Promise<void> | void;
onStyleCommit?: (property: string, value: string) => Promise<void> | void;
@@ -81,6 +84,19 @@ interface DomEditOverlayProps {
recordingState?: GestureRecordingState;
onToggleRecording?: () => void;
onMarqueeSelect?: (selections: DomEditSelection[], additive: boolean) => void;
+ /**
+ * Delete the selected canvas element.
+ * Wire to handleDomEditElementDelete from useDomEditActionsContext —
+ * same handler the Delete/Backspace hotkey uses.
+ */
+ onDeleteSelection?: (selection: DomEditSelection) => void;
+ /**
+ * Called with the resolved z-order patch list after an optimistic DOM update.
+ * The patch list is tie-aware and may include sibling elements (see
+ * canvasContextMenuZOrder). Wire to handleDomZIndexReorderCommit from
+ * useDomEditActionsContext. See CanvasContextMenu.tsx module comment.
+ */
+ onApplyZIndex?: (selection: DomEditSelection, patches: ZOrderPatch[]) => void;
}
// fallow-ignore-next-line complexity
@@ -105,6 +121,8 @@ export const DomEditOverlay = memo(function DomEditOverlay({
onRotationCommit,
onStyleCommit,
onMarqueeSelect,
+ onDeleteSelection,
+ onApplyZIndex,
}: DomEditOverlayProps) {
const overlayRef = useRef<HTMLDivElement | null>(null);
const boxRef = useRef<HTMLDivElement | null>(null);
@@ -121,8 +139,31 @@ export const DomEditOverlay = memo(function DomEditOverlay({
const snapGuidesRef = useRef<SnapGuidesState | null>(null);
const rafPausedRef = useRef(false);
+ // Context menu state: position of the right-click that opened it.
+ // contextMenuSelection is the element the menu targets — captured at right-click
+ // time so the menu can open even before the React selection state settles.
+ const [contextMenu, setContextMenu] = useState<{
+ x: number;
+ y: number;
+ sel: DomEditSelection;
+ } | null>(null);
+
const selectionRef = useRef(selection);
selectionRef.current = selection;
+
+ // Close the context menu whenever the selection moves off the element the menu
+ // targets (a click that reselects elsewhere, a deselect, or a preview reload
+ // that rebuilds the selection). Without this the menu can linger — orphaned —
+ // over a stale target after the underlying element is gone. A right-click that
+ // OPENS the menu also selects its target, so the common open path keeps the
+ // menu (same element) rather than immediately dismissing it.
+ useEffect(() => {
+ if (!contextMenu) return;
+ if (!selection || selection.element !== contextMenu.sel.element) {
+ setContextMenu(null);
+ }
+ }, [selection, contextMenu]);
+
const activeCompositionPathRef = useRef(activeCompositionPath);
activeCompositionPathRef.current = activeCompositionPath;
const groupSelectionsRef = useRef(groupSelections);
@@ -241,6 +282,23 @@ export const DomEditOverlay = memo(function DomEditOverlay({
snapGuidesRef,
});
+ // Arrow-key nudge (1px, Shift = 10px) — commits through the same
+ // path-offset callbacks as a drag, one undo entry per key burst.
+ const { flushNudge } = useDomEditNudge({
+ selection,
+ groupSelections,
+ allowCanvasMovement,
+ selectionRef,
+ overlayRectRef,
+ groupOverlayItemsRef,
+ gestureRef,
+ groupGestureRef,
+ blockedMoveRef,
+ onManualDragStartRef,
+ onPathOffsetCommitRef,
+ onGroupPathOffsetCommitRef,
+ });
+
const marquee = useMarqueeGestures({
iframeRef,
overlayRef,
@@ -370,6 +428,38 @@ export const DomEditOverlay = memo(function DomEditOverlay({
e.stopPropagation();
};
+ // Right-click: select element first (if not already selected), then open menu.
+ const handleContextMenu = useCallback(
+ async (event: React.MouseEvent<HTMLDivElement>) => {
+ event.preventDefault();
+
+ // If no element is selected yet, resolve it from the pointer position first.
+ const currentSel = selectionRef.current;
+ let activeSel: DomEditSelection | null = currentSel;
+ if (!currentSel) {
+ const pointerEvent = event as unknown as React.PointerEvent<HTMLDivElement>;
+ const resolved = await onCanvasPointerMoveRef.current(pointerEvent);
+ if (!resolved) return; // Nothing under the cursor — skip menu.
+ onSelectionChangeRef.current(resolved, { revealPanel: true });
+ // Use `resolved` directly: React state (and therefore selectionRef) won't
+ // update synchronously after onSelectionChange — we'd be reading stale null.
+ activeSel = resolved;
+ } else {
+ // Check if the user right-clicked on an unselected element (hover target).
+ const hover = hoverSelectionRef.current;
+ if (hover && hover.element !== currentSel.element) {
+ onSelectionChangeRef.current(hover, { revealPanel: true });
+ activeSel = hover;
+ }
+ }
+
+ if (!activeSel) return;
+ setContextMenu({ x: event.clientX, y: event.clientY, sel: activeSel });
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [],
+ );
+
return (
<div
ref={overlayRef}
@@ -378,142 +468,59 @@ export const DomEditOverlay = memo(function DomEditOverlay({
aria-label="Composition canvas"
// Cursor follows marquee rect *state* (re-renders), not the mutable ref.
style={marquee.marqueeRect ? { cursor: "crosshair" } : undefined}
- onPointerDownCapture={(event) =>
- focusDomEditOverlayElement(event.currentTarget as FocusableDomEditOverlay)
- }
+ onPointerDownCapture={(event) => {
+ // A pointer gesture supersedes a pending nudge burst — commit it first
+ // so the gesture's member snapshot starts from the nudged position.
+ flushNudge();
+ focusDomEditOverlayElement(event.currentTarget as FocusableDomEditOverlay);
+ }}
onPointerDown={handleOverlayPointerDown}
onMouseDown={handleOverlayMouseDown}
onPointerMove={marquee.onPointerMove}
onPointerLeave={() => onCanvasPointerLeaveRef.current()}
onPointerUp={marquee.onPointerUp}
onPointerCancel={marquee.onPointerCancel}
+ onContextMenu={handleContextMenu}
>
{hoverSelection && hoverRect && compRect.width > 0 && (
<div
aria-hidden="true"
data-dom-edit-hover-box="true"
className="pointer-events-none absolute rounded-md border border-studio-accent/80 shadow-[0_0_0_1px_rgba(60,230,172,0.25)]"
- style={hugRectForElement(hoverRect, hoverSelection.element)}
+ style={{
+ ...hugRectForElement(hoverRect, hoverSelection.element),
+ transform: hoverRect.angle ? `rotate(${hoverRect.angle}deg)` : undefined,
+ }}
/>
)}
{hasGroupSelection && groupOverlayItems.length > 1 && groupBounds && compRect.width > 0 && (
- <>
- {groupOverlayItems.map((item) => (
- <div
- key={item.key}
- aria-hidden="true"
- className="pointer-events-none absolute rounded-xl border border-studio-accent/70"
- style={{
- left: item.rect.left,
- top: item.rect.top,
- width: item.rect.width,
- height: item.rect.height,
- }}
- />
- ))}
- <div
- data-dom-edit-selection-box="true"
- className="pointer-events-auto absolute rounded-xl border border-studio-accent shadow-[0_0_0_1px_rgba(60,230,172,0.3)]"
- style={{
- left: groupBounds.left,
- top: groupBounds.top,
- width: groupBounds.width,
- height: groupBounds.height,
- cursor: allowCanvasMovement && groupCanMove ? "move" : "default",
- }}
- onPointerDown={(e) => {
- if (!allowCanvasMovement || !groupCanMove || e.shiftKey) return;
- gestures.startGroupDrag(e);
- }}
- onMouseDown={suppressBoxMouseDown}
- onClick={handleBoxClick}
- />
- </>
+ <DomEditGroupChrome
+ groupOverlayItems={groupOverlayItems}
+ groupBounds={groupBounds}
+ allowCanvasMovement={allowCanvasMovement}
+ groupCanMove={groupCanMove}
+ gestures={gestures}
+ onBoxMouseDown={suppressBoxMouseDown}
+ onBoxClick={handleBoxClick}
+ />
)}
{!hasGroupSelection && selection && overlayRect && compRect.width > 0 && (
- <>
- {allowCanvasMovement && selection.capabilities.canApplyManualRotation && (
- <DomEditRotateHandle
- overlayRect={overlayRect}
- cropOutlineInsetPx={cropOutlineInsetPx}
- onStartRotate={(e) => {
- e.stopPropagation();
- gestures.startGesture("rotate", e);
- }}
- />
- )}
- <div
- key={selectionKey}
- ref={boxRef}
- data-dom-edit-selection-box="true"
- className={`pointer-events-auto absolute rounded-md ${boxChromeClass}`}
- style={{
- left: overlayRect.left,
- top: overlayRect.top,
- width: overlayRect.width,
- height: overlayRect.height,
- clipPath: boxClipPath,
- cursor:
- allowCanvasMovement && selection.capabilities.canApplyManualOffset
- ? "move"
- : "default",
- }}
- onPointerDown={(e) => {
- if (!allowCanvasMovement || e.shiftKey) return;
- if (selection.capabilities.canApplyManualOffset) {
- gestures.startGesture("drag", e);
- return;
- }
- e.preventDefault();
- e.stopPropagation();
- e.currentTarget.setPointerCapture(e.pointerId);
- blockedMoveRef.current = {
- pointerId: e.pointerId,
- startX: e.clientX,
- startY: e.clientY,
- notified: false,
- };
- }}
- onMouseDown={suppressBoxMouseDown}
- onClick={handleBoxClick}
- >
- {cropOutlineInsetPx && (
- <div
- className="pointer-events-none absolute rounded-md border border-studio-accent/80 shadow-[0_0_0_1px_rgba(60,230,172,0.25)]"
- style={{
- left: cropOutlineInsetPx.left,
- top: cropOutlineInsetPx.top,
- right: cropOutlineInsetPx.right,
- bottom: cropOutlineInsetPx.bottom,
- }}
- />
- )}
- {allowCanvasMovement && selection.capabilities.canApplyManualSize && (
- <div
- className="absolute -right-1.5 -bottom-1.5 w-3 h-3 rounded-sm bg-studio-accent border border-studio-accent/60"
- style={{
- cursor: "se-resize",
- touchAction: "none",
- ...(cropOutlineInsetPx && {
- right: cropOutlineInsetPx.right - 6,
- bottom: cropOutlineInsetPx.bottom - 6,
- }),
- }}
- onPointerDown={(e) => {
- e.stopPropagation();
- gestures.startGesture("resize", e);
- }}
- />
- )}
- </div>
- {selection.capabilities.canCrop && groupSelections.length <= 1 && (
- <DomEditCropHandles
- selection={selection}
- overlayRect={overlayRect}
- onStyleCommit={onStyleCommitRef.current}
- />
- )}
- </>
+ <DomEditSelectionChrome
+ selection={selection}
+ overlayRect={overlayRect}
+ allowCanvasMovement={allowCanvasMovement}
+ cropOutlineInsetPx={cropOutlineInsetPx ?? undefined}
+ boxRef={boxRef}
+ boxChromeClass={boxChromeClass}
+ boxClipPath={boxClipPath}
+ selectionKey={selectionKey}
+ groupSelectionCount={groupSelections.length}
+ blockedMoveRef={blockedMoveRef}
+ gestures={gestures}
+ onStyleCommit={onStyleCommitRef.current}
+ onBoxMouseDown={suppressBoxMouseDown}
+ onBoxClick={handleBoxClick}
+ />
)}
{childRects.length > 0 &&
compRect.width > 0 &&
@@ -539,6 +546,29 @@ export const DomEditOverlay = memo(function DomEditOverlay({
onSelectionChangeRef={onSelectionChangeRef}
/>
<MarqueeOverlay candidateRects={marquee.candidateRects} marqueeRect={marquee.marqueeRect} />
+ {contextMenu && (
+ <CanvasContextMenu
+ x={contextMenu.x}
+ y={contextMenu.y}
+ selection={contextMenu.sel}
+ onClose={() => setContextMenu(null)}
+ onDelete={
+ onDeleteSelection
+ ? (sel) => {
+ setContextMenu(null);
+ onDeleteSelection(sel);
+ }
+ : undefined
+ }
+ onApplyZIndex={
+ onApplyZIndex
+ ? (patches) => {
+ onApplyZIndex(contextMenu.sel, patches);
+ }
+ : undefined
+ }
+ />
+ )}
<GridOverlay
visible={gridVisible}
spacing={gridSpacing}
@@ -551,8 +581,10 @@ export const DomEditOverlay = memo(function DomEditOverlay({
/>
<SnapGuideOverlay
snapGuidesRef={snapGuidesRef}
- overlayWidth={compRect.width}
- overlayHeight={compRect.height}
+ compositionLeft={compRect.left}
+ compositionTop={compRect.top}
+ compositionWidth={compRect.width}
+ compositionHeight={compRect.height}
/>
</div>
);
diff --git a/packages/studio/src/components/editor/DomEditOverlayHover.test.tsx b/packages/studio/src/components/editor/DomEditOverlayHover.test.tsx
new file mode 100644
index 0000000000..c7e82693ec
--- /dev/null
+++ b/packages/studio/src/components/editor/DomEditOverlayHover.test.tsx
@@ -0,0 +1,90 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it, vi } from "vitest";
+import type { DomEditSelection } from "./domEditing";
+import { DomEditOverlay } from "./DomEditOverlay";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const hoverState = vi.hoisted(() => ({ angle: 0 }));
+
+vi.mock("./useDomEditOverlayRects", () => ({
+ useDomEditOverlayRects: ({ hoverSelectionRef }: { hoverSelectionRef: { current: unknown } }) => ({
+ overlayRect: null,
+ overlayRectRef: { current: null },
+ setOverlayRect: () => undefined,
+ hoverRect: hoverSelectionRef.current
+ ? {
+ left: 20,
+ top: 30,
+ width: 100,
+ height: 40,
+ editScaleX: 1,
+ editScaleY: 1,
+ angle: hoverState.angle,
+ }
+ : null,
+ groupOverlayItems: [],
+ groupOverlayItemsRef: { current: [] },
+ setGroupOverlayItems: () => undefined,
+ childRects: [],
+ }),
+}));
+
+vi.mock("./useDomEditCompositionRect", () => ({
+ useDomEditCompositionRect: () => ({
+ left: 0,
+ top: 0,
+ width: 800,
+ height: 450,
+ scaleX: 1,
+ scaleY: 1,
+ }),
+}));
+
+vi.mock("./offCanvasIndicatorRefresh", () => ({
+ startOffCanvasIndicatorRefresh: () => () => undefined,
+}));
+
+function renderHover(angle: number): string {
+ hoverState.angle = angle;
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ const element = document.createElement("div");
+ const hoverSelection = { element } as unknown as DomEditSelection;
+ act(() => {
+ root.render(
+ <DomEditOverlay
+ iframeRef={{ current: document.createElement("iframe") }}
+ activeCompositionPath={null}
+ selection={null}
+ hoverSelection={hoverSelection}
+ onCanvasMouseDown={() => undefined}
+ onCanvasPointerMove={() => Promise.resolve(null)}
+ onCanvasPointerLeave={() => undefined}
+ onSelectionChange={() => undefined}
+ onBlockedMove={() => undefined}
+ onPathOffsetCommit={() => undefined}
+ onGroupPathOffsetCommit={() => undefined}
+ onBoxSizeCommit={() => undefined}
+ onRotationCommit={() => undefined}
+ />,
+ );
+ });
+ const box = host.querySelector<HTMLElement>('[data-dom-edit-hover-box="true"]');
+ const transform = box?.style.transform ?? "";
+ act(() => root.unmount());
+ host.remove();
+ return transform;
+}
+
+it("rotates the hover box with the element", () => {
+ expect(renderHover(30)).toBe("rotate(30deg)");
+});
+
+it("leaves the hover box untransformed at angle zero", () => {
+ expect(renderHover(0)).toBe("");
+});
diff --git a/packages/studio/src/components/editor/DomEditRotateHandle.tsx b/packages/studio/src/components/editor/DomEditRotateHandle.tsx
index 846539c50c..fbc19448c4 100644
--- a/packages/studio/src/components/editor/DomEditRotateHandle.tsx
+++ b/packages/studio/src/components/editor/DomEditRotateHandle.tsx
@@ -1,8 +1,12 @@
import type { PointerEvent as ReactPointerEvent } from "react";
import type { OverlayRect } from "./domEditOverlayGeometry";
-/** Rotate grab-handle above the selection. Anchors to the crop outline when
- * the element is cropped so it stays next to what's visible on screen. */
+/** Rotate handle below the selection: an attached circular-arrows icon chip
+ * (no connecting stem). Anchors to the crop outline when the element is
+ * cropped so it stays next to what's visible on screen. Presentation only —
+ * the rotation gesture measures pointer angles from the element CENTER
+ * (resolveDomEditRotationGesture), so the handle position doesn't affect the
+ * math. Sits 12px below the bbox, past the bottom crop handle's hit strip. */
export function DomEditRotateHandle({
overlayRect,
cropOutlineInsetPx,
@@ -15,27 +19,43 @@ export function DomEditRotateHandle({
const inset = cropOutlineInsetPx ?? { top: 0, right: 0, bottom: 0, left: 0 };
const visibleLeft = overlayRect.left + inset.left;
const visibleWidth = Math.max(0, overlayRect.width - inset.left - inset.right);
- const visibleTop = overlayRect.top + inset.top;
+ const visibleBottom = overlayRect.top + overlayRect.height - inset.bottom;
return (
- <div
- className="pointer-events-none absolute"
+ <button
+ type="button"
+ className="pointer-events-auto absolute flex items-center justify-center border-0 bg-transparent p-0"
style={{
left: visibleLeft + visibleWidth / 2,
- top: visibleTop - 34,
- width: 28,
- height: 34,
+ top: visibleBottom + 12,
+ width: 22,
+ height: 22,
transform: "translateX(-50%)",
+ touchAction: "none",
+ // Closed-hand grab cursor: this handle is grabbed and dragged to rotate.
+ cursor: "grabbing",
}}
+ title="Rotate"
+ aria-label="Rotate selection"
+ onPointerDown={onStartRotate}
>
- <div className="absolute left-1/2 top-3 bottom-0 w-px -translate-x-1/2 bg-studio-accent/60" />
- <button
- type="button"
- className="pointer-events-auto absolute left-1/2 top-0 h-3 w-3 -translate-x-1/2 rounded-full border border-studio-accent bg-studio-accent p-0 shadow-[0_0_0_2px_rgba(60,230,172,0.18)]"
- style={{ cursor: "grab", touchAction: "none" }}
- title="Rotate"
- aria-label="Rotate selection"
- onPointerDown={onStartRotate}
- />
- </div>
+ <span className="pointer-events-none flex h-[18px] w-[18px] items-center justify-center rounded-full border border-studio-accent/70 bg-studio-surface text-studio-accent shadow-[0_0_3px_rgba(0,0,0,0.45)]">
+ <svg
+ width="11"
+ height="11"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden="true"
+ >
+ <path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" />
+ <path d="M21 3v5h-5" />
+ <path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" />
+ <path d="M8 16H3v5" />
+ </svg>
+ </span>
+ </button>
);
}
diff --git a/packages/studio/src/components/editor/DomEditSelectionChrome.test.tsx b/packages/studio/src/components/editor/DomEditSelectionChrome.test.tsx
new file mode 100644
index 0000000000..cfdc392ebf
--- /dev/null
+++ b/packages/studio/src/components/editor/DomEditSelectionChrome.test.tsx
@@ -0,0 +1,80 @@
+// @vitest-environment happy-dom
+
+import React, { act, createRef } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it, vi } from "vitest";
+import type { DomEditSelection } from "./domEditing";
+import { DomEditSelectionChrome } from "./DomEditSelectionChrome";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("DomEditSelectionChrome crop composition", () => {
+ it("places rotated crop UI in exactly one oriented coordinate plane", () => {
+ const element = document.createElement("div");
+ element.id = "clip";
+ element.style.clipPath = "inset(10px)";
+ Object.defineProperties(element, {
+ offsetWidth: { value: 200 },
+ offsetHeight: { value: 100 },
+ });
+ document.body.append(element);
+ vi.spyOn(window, "getComputedStyle").mockReturnValue({
+ clipPath: "inset(10px)",
+ transform: "matrix(0.8660254, 0.5, -0.5, 0.8660254, 0, 0)",
+ } as CSSStyleDeclaration);
+ const selection = {
+ element,
+ id: "clip",
+ selector: "#clip",
+ capabilities: {
+ canCrop: true,
+ canApplyManualOffset: true,
+ canApplyManualSize: true,
+ canApplyManualRotation: true,
+ },
+ } as unknown as DomEditSelection;
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ act(() => {
+ root.render(
+ <DomEditSelectionChrome
+ selection={selection}
+ overlayRect={{
+ left: 100,
+ top: 50,
+ width: 220,
+ height: 130,
+ editScaleX: 1,
+ editScaleY: 1,
+ angle: 30,
+ }}
+ allowCanvasMovement={true}
+ boxRef={createRef()}
+ boxChromeClass=""
+ boxClipPath={undefined}
+ selectionKey="clip"
+ groupSelectionCount={0}
+ blockedMoveRef={createRef()}
+ gestures={{ startGesture: vi.fn() } as never}
+ onStyleCommit={vi.fn()}
+ onBoxMouseDown={vi.fn()}
+ onBoxClick={vi.fn()}
+ />,
+ );
+ });
+
+ const cropFrame = host.querySelector<HTMLElement>("[data-dom-edit-crop-frame]")!;
+ const rotations: string[] = [];
+ for (
+ let node: HTMLElement | null = cropFrame;
+ node && node !== host;
+ node = node.parentElement
+ ) {
+ if (node.style.transform.includes("rotate(")) rotations.push(node.style.transform);
+ }
+ expect(rotations).toHaveLength(1);
+ expect(Number.parseFloat(rotations[0]!.slice("rotate(".length))).toBeCloseTo(30, 5);
+ act(() => root.unmount());
+ });
+});
diff --git a/packages/studio/src/components/editor/DomEditSelectionChrome.tsx b/packages/studio/src/components/editor/DomEditSelectionChrome.tsx
new file mode 100644
index 0000000000..acbde93f69
--- /dev/null
+++ b/packages/studio/src/components/editor/DomEditSelectionChrome.tsx
@@ -0,0 +1,257 @@
+import type { RefObject } from "react";
+import { type DomEditSelection } from "./domEditing";
+import type { GroupOverlayItem, OverlayRect } from "./domEditOverlayGeometry";
+import type { BlockedMoveState, ResizeHandle } from "./domEditOverlayGestures";
+import type { createDomEditOverlayGestureHandlers } from "./useDomEditOverlayGestures";
+import { DomEditCropHandles } from "./DomEditCropHandles";
+import { DomEditRotateHandle } from "./DomEditRotateHandle";
+import { resolveRotatedResizeCursor } from "./domEditResizeLocal";
+
+// Corner resize handles, Canva-style: one per corner, diagonal cursors.
+// Corners scale about the element center; the translate keeps the center
+// planted, so they need the manual-offset capability in addition to manual-size.
+const RESIZE_HANDLE_DEFS: Array<{
+ handle: ResizeHandle;
+ cursor: string;
+ x: "left" | "right";
+ y: "top" | "bottom";
+}> = [
+ { handle: "nw", cursor: "nwse-resize", x: "left", y: "top" },
+ { handle: "ne", cursor: "nesw-resize", x: "right", y: "top" },
+ { handle: "sw", cursor: "nesw-resize", x: "left", y: "bottom" },
+ { handle: "se", cursor: "nwse-resize", x: "right", y: "bottom" },
+];
+
+// Visible dot is 9px; the pointer target is a 16px invisible square centered
+// on the corner so click targets don't shrink with the smaller dot.
+const RESIZE_HANDLE_HIT_PX = 16;
+
+type CropInset = { top: number; right: number; bottom: number; left: number };
+const NO_CROP_INSET: CropInset = { top: 0, right: 0, bottom: 0, left: 0 };
+
+function resizeHandleStyle(
+ def: (typeof RESIZE_HANDLE_DEFS)[number],
+ overlayRect: { left: number; top: number; width: number; height: number },
+ cropInset?: CropInset,
+): React.CSSProperties {
+ const half = RESIZE_HANDLE_HIT_PX / 2;
+ const inset = cropInset ?? NO_CROP_INSET;
+ const style: React.CSSProperties = { cursor: def.cursor, touchAction: "none" };
+ // Position relative to the overlay container (not the selection box).
+ // This ensures the dots render as siblings of the box border div — strictly
+ // above it — rather than as children where the parent border can visually
+ // overlap the dot circle at the corner.
+ style.left =
+ def.x === "left"
+ ? overlayRect.left + inset.left - half
+ : overlayRect.left + overlayRect.width - inset.right - half;
+ style.top =
+ def.y === "top"
+ ? overlayRect.top + inset.top - half
+ : overlayRect.top + overlayRect.height - inset.bottom - half;
+ return style;
+}
+
+type GestureHandlers = ReturnType<typeof createDomEditOverlayGestureHandlers>;
+
+interface DomEditGroupChromeProps {
+ groupOverlayItems: GroupOverlayItem[];
+ groupBounds: OverlayRect;
+ allowCanvasMovement: boolean;
+ groupCanMove: boolean;
+ gestures: GestureHandlers;
+ onBoxMouseDown: (e: React.MouseEvent) => void;
+ onBoxClick: (event: React.MouseEvent<HTMLDivElement>) => void;
+}
+
+// Multi-selection chrome: per-member outlines plus a single draggable bounding
+// box spanning the union of the members.
+export function DomEditGroupChrome({
+ groupOverlayItems,
+ groupBounds,
+ allowCanvasMovement,
+ groupCanMove,
+ gestures,
+ onBoxMouseDown,
+ onBoxClick,
+}: DomEditGroupChromeProps) {
+ return (
+ <>
+ {groupOverlayItems.map((item) => (
+ <div
+ key={item.key}
+ aria-hidden="true"
+ className="pointer-events-none absolute rounded-xl border border-studio-accent/70"
+ style={{
+ left: item.rect.left,
+ top: item.rect.top,
+ width: item.rect.width,
+ height: item.rect.height,
+ }}
+ />
+ ))}
+ <div
+ data-dom-edit-selection-box="true"
+ className="pointer-events-auto absolute rounded-xl border border-studio-accent shadow-[0_0_0_1px_rgba(60,230,172,0.3)]"
+ style={{
+ left: groupBounds.left,
+ top: groupBounds.top,
+ width: groupBounds.width,
+ height: groupBounds.height,
+ cursor: allowCanvasMovement && groupCanMove ? "move" : "default",
+ }}
+ onPointerDown={(e) => {
+ if (!allowCanvasMovement || !groupCanMove || e.shiftKey) return;
+ gestures.startGroupDrag(e);
+ }}
+ onMouseDown={onBoxMouseDown}
+ onClick={onBoxClick}
+ />
+ </>
+ );
+}
+
+interface DomEditSelectionChromeProps {
+ selection: DomEditSelection;
+ overlayRect: OverlayRect;
+ allowCanvasMovement: boolean;
+ cropOutlineInsetPx?: { top: number; right: number; bottom: number; left: number };
+ boxRef: RefObject<HTMLDivElement | null>;
+ boxChromeClass: string;
+ boxClipPath: string | undefined;
+ selectionKey: string;
+ groupSelectionCount: number;
+ blockedMoveRef: RefObject<BlockedMoveState | null>;
+ gestures: GestureHandlers;
+ onStyleCommit?: (property: string, value: string) => Promise<void> | void;
+ onBoxMouseDown: (e: React.MouseEvent) => void;
+ onBoxClick: (event: React.MouseEvent<HTMLDivElement>) => void;
+}
+
+// Oriented selection chrome: a rotation wrapper spanning the overlay, rotated by
+// the element's live angle about the selection box CENTER. Its children (border
+// box, corner dots, and rotate handle) keep their existing
+// overlay-absolute positions — rotating the whole plane about the box center
+// lands them on the element's real transformed corners for free. At angle 0 the
+// transform is a no-op, so the chrome is pixel-identical.
+export function DomEditSelectionChrome({
+ selection,
+ overlayRect,
+ allowCanvasMovement,
+ cropOutlineInsetPx,
+ boxRef,
+ boxChromeClass,
+ boxClipPath,
+ selectionKey,
+ groupSelectionCount,
+ blockedMoveRef,
+ gestures,
+ onStyleCommit,
+ onBoxMouseDown,
+ onBoxClick,
+}: DomEditSelectionChromeProps) {
+ return (
+ <>
+ <div
+ className="pointer-events-none absolute inset-0"
+ style={{
+ transformOrigin: `${overlayRect.left + overlayRect.width / 2}px ${overlayRect.top + overlayRect.height / 2}px`,
+ transform: overlayRect.angle ? `rotate(${overlayRect.angle}deg)` : undefined,
+ }}
+ >
+ {allowCanvasMovement && selection.capabilities.canApplyManualRotation && (
+ <DomEditRotateHandle
+ overlayRect={overlayRect}
+ cropOutlineInsetPx={cropOutlineInsetPx}
+ onStartRotate={(e) => {
+ e.stopPropagation();
+ gestures.startGesture("rotate", e);
+ }}
+ />
+ )}
+ <div
+ key={selectionKey}
+ ref={boxRef}
+ data-dom-edit-selection-box="true"
+ className={`pointer-events-auto absolute rounded-md ${boxChromeClass}`}
+ style={{
+ left: overlayRect.left,
+ top: overlayRect.top,
+ width: overlayRect.width,
+ height: overlayRect.height,
+ clipPath: boxClipPath,
+ cursor:
+ allowCanvasMovement && selection.capabilities.canApplyManualOffset
+ ? "move"
+ : "default",
+ }}
+ onPointerDown={(e) => {
+ if (!allowCanvasMovement || e.shiftKey) return;
+ if (selection.capabilities.canApplyManualOffset) {
+ gestures.startGesture("drag", e);
+ return;
+ }
+ e.preventDefault();
+ e.stopPropagation();
+ e.currentTarget.setPointerCapture(e.pointerId);
+ blockedMoveRef.current = {
+ pointerId: e.pointerId,
+ startX: e.clientX,
+ startY: e.clientY,
+ notified: false,
+ };
+ }}
+ onMouseDown={onBoxMouseDown}
+ onClick={onBoxClick}
+ >
+ {cropOutlineInsetPx && (
+ <div
+ className="pointer-events-none absolute rounded-md border border-studio-accent/80 shadow-[0_0_0_1px_rgba(60,230,172,0.25)]"
+ style={{
+ left: cropOutlineInsetPx.left,
+ top: cropOutlineInsetPx.top,
+ right: cropOutlineInsetPx.right,
+ bottom: cropOutlineInsetPx.bottom,
+ }}
+ />
+ )}
+ </div>
+ {/* Resize-handle dots rendered as siblings of the selection box, not
+ children, so they paint strictly above the box border. Each handle
+ is positioned relative to the overlay container using the
+ overlayRect origin, matching the old child-relative offsets. */}
+ {allowCanvasMovement &&
+ selection.capabilities.canApplyManualSize &&
+ RESIZE_HANDLE_DEFS.map((def) =>
+ def.handle !== "se" && !selection.capabilities.canApplyManualOffset ? null : (
+ <div
+ key={def.handle}
+ className="pointer-events-auto absolute flex h-4 w-4 items-center justify-center"
+ style={{
+ ...resizeHandleStyle(def, overlayRect, cropOutlineInsetPx ?? undefined),
+ // Cursor rotates with the object: bucket the corner's base
+ // diagonal + element rotation into the 8 CSS resize cursors.
+ cursor: resolveRotatedResizeCursor(def.handle, overlayRect.angle ?? 0),
+ }}
+ onPointerDown={(e) => {
+ e.stopPropagation();
+ gestures.startGesture("resize", e, { resizeHandle: def.handle });
+ }}
+ >
+ <div className="pointer-events-none h-[12px] w-[12px] rounded-full border-[1.5px] border-studio-accent bg-white shadow-[0_0_3px_rgba(0,0,0,0.45)]" />
+ </div>
+ ),
+ )}
+ </div>
+ {/* Crop owns its element-local oriented frame. Keep it outside the chrome's
+ rotated plane or a rotated selection applies the angle twice. */}
+ {selection.capabilities.canCrop && groupSelectionCount <= 1 && (
+ <DomEditCropHandles
+ selection={selection}
+ overlayRect={overlayRect}
+ onStyleCommit={onStyleCommit}
+ />
+ )}
+ </>
+ );
+}
diff --git a/packages/studio/src/components/editor/LayersPanel.test.ts b/packages/studio/src/components/editor/LayersPanel.test.ts
index f34db36f07..4a3b6a239a 100644
--- a/packages/studio/src/components/editor/LayersPanel.test.ts
+++ b/packages/studio/src/components/editor/LayersPanel.test.ts
@@ -1,10 +1,11 @@
// @vitest-environment happy-dom
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import { Window } from "happy-dom";
import type { DomEditLayerItem } from "./domEditingTypes";
-import { sortLayersByZIndex } from "./LayersPanel";
+import { createRafThrottle, sortLayersByZIndex } from "./LayersPanel";
import { isLayerDraggable } from "./useLayerDrag";
+import { liveTime } from "../../player";
function makeLayer(
overrides: Partial<DomEditLayerItem> & { zIndex?: string; locked?: boolean },
@@ -133,3 +134,66 @@ describe("isLayerDraggable", () => {
expect(isLayerDraggable(layer)).toBe(true);
});
});
+
+// ── liveTime throttle contract (mirrors the useEffect in LayersPanel) ──────
+// The panel subscribes to liveTime with a rAF + 100 ms trailing throttle so
+// it refreshes during scrubbing without a collectLayers call every frame.
+// These tests exercise the subscribe/unsubscribe contract that the effect
+// relies on.
+
+describe("liveTime subscribe / unsubscribe (LayersPanel scrub contract)", () => {
+ let rafCallbacks: FrameRequestCallback[];
+ let originalRaf: typeof requestAnimationFrame;
+ let originalCancelRaf: typeof cancelAnimationFrame;
+
+ beforeEach(() => {
+ rafCallbacks = [];
+ originalRaf = globalThis.requestAnimationFrame;
+ originalCancelRaf = globalThis.cancelAnimationFrame;
+ let nextId = 1;
+ globalThis.requestAnimationFrame = (cb) => {
+ const id = nextId++;
+ rafCallbacks.push(cb);
+ return id;
+ };
+ globalThis.cancelAnimationFrame = vi.fn();
+ });
+
+ afterEach(() => {
+ globalThis.requestAnimationFrame = originalRaf;
+ globalThis.cancelAnimationFrame = originalCancelRaf;
+ });
+
+ it("unsubscribing stops the callback from receiving further notifications", () => {
+ const cb = vi.fn();
+ const unsubscribe = liveTime.subscribe(cb);
+
+ liveTime.notify(1);
+ expect(cb).toHaveBeenCalledTimes(1);
+
+ unsubscribe();
+ liveTime.notify(2);
+ expect(cb).toHaveBeenCalledTimes(1); // no new call after unsubscribe
+ });
+
+ it("queuing a rAF on liveTime notify then flushing calls the refresh exactly once", () => {
+ const refresh = vi.fn();
+ const throttle = createRafThrottle(refresh, 100);
+ const unsubscribe = liveTime.subscribe(throttle.invoke);
+
+ // First notify enqueues one rAF
+ liveTime.notify(0.1);
+ expect(rafCallbacks).toHaveLength(1);
+ expect(refresh).not.toHaveBeenCalled();
+
+ // Second notify before rAF flush is ignored (rafId is set)
+ liveTime.notify(0.2);
+ expect(rafCallbacks).toHaveLength(1);
+
+ // Flush the rAF
+ rafCallbacks[0](performance.now());
+ expect(refresh).toHaveBeenCalledTimes(1);
+
+ unsubscribe();
+ });
+});
diff --git a/packages/studio/src/components/editor/LayersPanel.tsx b/packages/studio/src/components/editor/LayersPanel.tsx
index 915b81c6a6..b84bb47f61 100644
--- a/packages/studio/src/components/editor/LayersPanel.tsx
+++ b/packages/studio/src/components/editor/LayersPanel.tsx
@@ -7,7 +7,7 @@ import {
} from "./domEditing";
import { useStudioPlaybackContext, useStudioShellContext } from "../../contexts/StudioContext";
import { useDomEditContext } from "../../contexts/DomEditContext";
-import { usePlayerStore } from "../../player";
+import { usePlayerStore, liveTime } from "../../player";
import {
findMatchingTimelineElementId,
resolveTimelineSelectionSeekTime,
@@ -49,6 +49,34 @@ function isCompositionHost(el: HTMLElement): boolean {
return el.hasAttribute("data-composition-src") || el.hasAttribute("data-composition-file");
}
+/**
+ * A trailing-rAF + cooldown throttle: `invoke` runs `run` at most once per
+ * animation frame and no more often than `throttleMs`. `cancel` clears any
+ * pending frame (call on cleanup). Extracted so the throttle can be exercised
+ * directly in tests instead of being reconstructed there.
+ */
+export function createRafThrottle(
+ run: () => void,
+ throttleMs = 100,
+): { invoke: () => void; cancel: () => void } {
+ let rafId: number | null = null;
+ let lastFired = 0;
+ return {
+ invoke: () => {
+ const now = performance.now();
+ if (rafId !== null || now - lastFired < throttleMs) return;
+ rafId = requestAnimationFrame(() => {
+ rafId = null;
+ lastFired = performance.now();
+ run();
+ });
+ },
+ cancel: () => {
+ if (rafId !== null) cancelAnimationFrame(rafId);
+ },
+ };
+}
+
interface CollapsedState {
[key: string]: boolean;
}
@@ -122,6 +150,20 @@ export const LayersPanel = memo(function LayersPanel() {
}
}, [compositionLoading, collectLayers]);
+ // Subscribe to liveTime so the panel refreshes during scrubbing.
+ // liveTime bypasses React state (no re-renders per frame), so a plain
+ // usePlayerStore(s => s.currentTime) subscription never fires while the
+ // RAF loop is running. Throttle with a trailing rAF + 100 ms cooldown to
+ // avoid a collectLayers call on every animation frame.
+ useEffect(() => {
+ const throttle = createRafThrottle(collectLayers, 100);
+ const unsubscribe = liveTime.subscribe(throttle.invoke);
+ return () => {
+ unsubscribe();
+ throttle.cancel();
+ };
+ }, [collectLayers]);
+
const resolveSelection = useCallback(
(layer: DomEditLayerItem) => {
// Re-find the element from the live DOM — layer.element may be stale
diff --git a/packages/studio/src/components/editor/OffCanvasIndicators.test.tsx b/packages/studio/src/components/editor/OffCanvasIndicators.test.tsx
new file mode 100644
index 0000000000..159528aff4
--- /dev/null
+++ b/packages/studio/src/components/editor/OffCanvasIndicators.test.tsx
@@ -0,0 +1,34 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it } from "vitest";
+import { OffCanvasIndicators } from "./OffCanvasIndicators";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+it("rotates an off-canvas indicator with its element", () => {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ act(() => {
+ root.render(
+ <OffCanvasIndicators
+ rects={[{ key: "card", left: 80, top: 20, width: 40, height: 20, angle: 30 }]}
+ elements={{ current: new Map() }}
+ compRect={{ left: 0, top: 0, width: 100, height: 100 }}
+ selection={null}
+ groupSelections={[]}
+ activeCompositionPathRef={{ current: null }}
+ onSelectionChangeRef={{ current: () => undefined }}
+ />,
+ );
+ });
+
+ const indicator = host.querySelector<HTMLElement>('[role="button"]');
+ expect(indicator?.parentElement?.style.transform).toBe("rotate(30deg)");
+ expect(indicator?.parentElement?.style.transformOrigin).toBe("center");
+
+ act(() => root.unmount());
+ host.remove();
+});
diff --git a/packages/studio/src/components/editor/OffCanvasIndicators.tsx b/packages/studio/src/components/editor/OffCanvasIndicators.tsx
index c671d59efd..ead1a53a4f 100644
--- a/packages/studio/src/components/editor/OffCanvasIndicators.tsx
+++ b/packages/studio/src/components/editor/OffCanvasIndicators.tsx
@@ -7,6 +7,7 @@ export interface OffCanvasRect {
top: number;
width: number;
height: number;
+ angle?: number;
}
interface OffCanvasIndicatorsProps {
@@ -21,6 +22,44 @@ interface OffCanvasIndicatorsProps {
>;
}
+function clipOutsideCanvas(
+ rect: OffCanvasRect,
+ compRect: { left: number; top: number; width: number; height: number },
+): string | undefined {
+ const angle = rect.angle ?? 0;
+ if (!angle) {
+ const left = Math.max(0, compRect.left - rect.left);
+ const top = Math.max(0, compRect.top - rect.top);
+ const right = Math.min(rect.width, compRect.left + compRect.width - rect.left);
+ const bottom = Math.min(rect.height, compRect.top + compRect.height - rect.top);
+ if (left >= right || top >= bottom) return undefined;
+ return `polygon(evenodd, 0 0, ${rect.width}px 0, ${rect.width}px ${rect.height}px, 0 ${rect.height}px, 0 0, ${left}px ${top}px, ${right}px ${top}px, ${right}px ${bottom}px, ${left}px ${bottom}px, ${left}px ${top}px)`;
+ }
+
+ const radians = (-angle * Math.PI) / 180;
+ const cos = Math.cos(radians);
+ const sin = Math.sin(radians);
+ const centerX = rect.left + rect.width / 2;
+ const centerY = rect.top + rect.height / 2;
+ const toLocal = (x: number, y: number) => {
+ const dx = x - centerX;
+ const dy = y - centerY;
+ return `${rect.width / 2 + dx * cos - dy * sin}px ${rect.height / 2 + dx * sin + dy * cos}px`;
+ };
+ const left = compRect.left;
+ const top = compRect.top;
+ const right = left + compRect.width;
+ const bottom = top + compRect.height;
+ const canvas = [
+ toLocal(left, top),
+ toLocal(right, top),
+ toLocal(right, bottom),
+ toLocal(left, bottom),
+ toLocal(left, top),
+ ].join(", ");
+ return `polygon(evenodd, 0 0, ${rect.width}px 0, ${rect.width}px ${rect.height}px, 0 ${rect.height}px, 0 0, ${canvas})`;
+}
+
/**
* Dashed teal indicators for elements whose bounds extend past the composition
* (the "gray zone"). The in-canvas portion is clipped away so only the
@@ -49,15 +88,15 @@ export function OffCanvasIndicators({
return !groupSelections.some((g) => g.element === el);
})
.map((r) => {
- const pos = { left: r.left, top: r.top, width: r.width, height: r.height };
- const cL = Math.max(0, compRect.left - r.left);
- const cT = Math.max(0, compRect.top - r.top);
- const cR = Math.min(r.width, compRect.left + compRect.width - r.left);
- const cB = Math.min(r.height, compRect.top + compRect.height - r.top);
- const hasInside = cL < cR && cT < cB;
- const clipOutside = hasInside
- ? `polygon(evenodd, 0 0, ${r.width}px 0, ${r.width}px ${r.height}px, 0 ${r.height}px, 0 0, ${cL}px ${cT}px, ${cR}px ${cT}px, ${cR}px ${cB}px, ${cL}px ${cB}px, ${cL}px ${cT}px)`
- : undefined;
+ const pos = {
+ left: r.left,
+ top: r.top,
+ width: r.width,
+ height: r.height,
+ transform: r.angle ? `rotate(${r.angle}deg)` : undefined,
+ transformOrigin: "center",
+ };
+ const clipOutside = clipOutsideCanvas(r, compRect);
const selectOffCanvas = async () => {
const el = elements.current.get(r.key);
if (!el) return;
@@ -86,7 +125,7 @@ export function OffCanvasIndicators({
role="button"
tabIndex={0}
aria-label={`Select off-canvas element ${r.key}`}
- className="pointer-events-auto absolute inset-0 border-2 border-dashed border-studio-accent/60 rounded-md cursor-pointer hover:border-studio-accent hover:bg-studio-accent/10 transition-colors"
+ className="pointer-events-auto absolute inset-0 border-2 border-dashed border-studio-accent/10 rounded-md cursor-pointer hover:border-studio-accent hover:bg-studio-accent/10 transition-colors"
style={clipOutside ? { clipPath: clipOutside } : undefined}
title={`Off-canvas: ${r.key} — click to select`}
onClick={handleClick}
diff --git a/packages/studio/src/components/editor/SnapGuideOverlay.tsx b/packages/studio/src/components/editor/SnapGuideOverlay.tsx
index 01faf85223..850d98adf5 100644
--- a/packages/studio/src/components/editor/SnapGuideOverlay.tsx
+++ b/packages/studio/src/components/editor/SnapGuideOverlay.tsx
@@ -1,7 +1,6 @@
-// fallow-ignore-file unused-file
import { memo, useRef, type RefObject } from "react";
import { useMountEffect } from "../../hooks/useMountEffect";
-import type { SnapGuide, SpacingGuide } from "./snapEngine";
+import { resolveGuideLineRect, type SnapGuide, type SpacingGuide } from "./snapEngine";
export interface SnapGuidesState {
guides: SnapGuide[];
@@ -17,22 +16,35 @@ const SPACING_BG = "rgba(255, 68, 204, 0.15)";
interface SnapGuideOverlayProps {
snapGuidesRef: RefObject<SnapGuidesState | null>;
- overlayWidth: number;
- overlayHeight: number;
+ /** Composition rect in overlay space — guide lines span exactly this rect. */
+ compositionLeft: number;
+ compositionTop: number;
+ compositionWidth: number;
+ compositionHeight: number;
}
export const SnapGuideOverlay = memo(function SnapGuideOverlay({
snapGuidesRef,
- overlayWidth,
- overlayHeight,
+ compositionLeft,
+ compositionTop,
+ compositionWidth,
+ compositionHeight,
}: SnapGuideOverlayProps) {
const guideElsRef = useRef<(HTMLDivElement | null)[]>([]);
const spacingElsRef = useRef<(HTMLDivElement | null)[]>([]);
const spacingLabelElsRef = useRef<(HTMLSpanElement | null)[]>([]);
- const overlayWidthRef = useRef(overlayWidth);
- overlayWidthRef.current = overlayWidth;
- const overlayHeightRef = useRef(overlayHeight);
- overlayHeightRef.current = overlayHeight;
+ const compositionRectRef = useRef({
+ left: compositionLeft,
+ top: compositionTop,
+ width: compositionWidth,
+ height: compositionHeight,
+ });
+ compositionRectRef.current = {
+ left: compositionLeft,
+ top: compositionTop,
+ width: compositionWidth,
+ height: compositionHeight,
+ };
useMountEffect(() => {
let frame = 0;
@@ -44,8 +56,7 @@ export const SnapGuideOverlay = memo(function SnapGuideOverlay({
const state = snapGuidesRef.current;
const guides = state?.guides ?? [];
const spacingGuides = state?.spacingGuides ?? [];
- const w = overlayWidthRef.current;
- const h = overlayHeightRef.current;
+ const composition = compositionRectRef.current;
for (let i = 0; i < MAX_GUIDES; i++) {
const el = guideElsRef.current[i];
@@ -58,17 +69,11 @@ export const SnapGuideOverlay = memo(function SnapGuideOverlay({
}
el.style.display = "";
- if (guide.axis === "x") {
- el.style.left = `${guide.position}px`;
- el.style.top = "0";
- el.style.width = "1px";
- el.style.height = `${h}px`;
- } else {
- el.style.left = "0";
- el.style.top = `${guide.position}px`;
- el.style.width = `${w}px`;
- el.style.height = "1px";
- }
+ const line = resolveGuideLineRect(guide, composition);
+ el.style.left = `${line.left}px`;
+ el.style.top = `${line.top}px`;
+ el.style.width = `${line.width}px`;
+ el.style.height = `${line.height}px`;
}
for (let i = 0; i < MAX_SPACING_GUIDES; i++) {
diff --git a/packages/studio/src/components/editor/SnapToolbar.test.tsx b/packages/studio/src/components/editor/SnapToolbar.test.tsx
index 9cac6538f1..29e73b463d 100644
--- a/packages/studio/src/components/editor/SnapToolbar.test.tsx
+++ b/packages/studio/src/components/editor/SnapToolbar.test.tsx
@@ -34,7 +34,6 @@ function AppHotkeyHarness() {
const leftSidebarRef = useRef<LeftSidebarHandle | null>(null);
useAppHotkeys({
- toggleTimelineVisibility: vi.fn(),
handleTimelineElementDelete: vi.fn(),
handleTimelineElementSplit: vi.fn(),
handleDomEditElementDelete: vi.fn(),
diff --git a/packages/studio/src/components/editor/anchoredResizeCommitFeedsOffset.test.ts b/packages/studio/src/components/editor/anchoredResizeCommitFeedsOffset.test.ts
new file mode 100644
index 0000000000..49065c709c
--- /dev/null
+++ b/packages/studio/src/components/editor/anchoredResizeCommitFeedsOffset.test.ts
@@ -0,0 +1,214 @@
+// @vitest-environment happy-dom
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { DomEditSelection } from "./domEditing";
+import type { GestureState, UseDomEditOverlayGesturesOptions } from "./domEditOverlayGestures";
+
+// Origin box (overlay px). The gesture-start center is its centroid; the
+// center-anchored resize must keep THIS point planted, which means the release
+// must commit a nonzero offset equal to minus half the size growth.
+const ORIGIN = { left: 0, top: 0, width: 200, height: 100 };
+const ORIGIN_CENTER = {
+ x: ORIGIN.left + ORIGIN.width / 2,
+ y: ORIGIN.top + ORIGIN.height / 2,
+};
+
+// Consistent geometry stub: model the physical truth the real DOM would report.
+// A CSS width/height change grows the box from its top-left, so the rendered
+// center drifts by half the size delta; the manual offset the gesture applies
+// (read back from the element's studio vars) pulls it back. `elementCornerOverlayPoints`
+// returns the four corners of that drifted box; `overlayCornersCentroid` (kept
+// real) averages them so the anchor loop can measure the true center each frame.
+vi.mock("./domEditOverlayGeometry", async () => {
+ const actual = await vi.importActual<typeof import("./domEditOverlayGeometry")>(
+ "./domEditOverlayGeometry",
+ );
+ const { readStudioBoxSize, readStudioPathOffset } = await import("./manualEditsDom");
+ const physicalCenter = (element: HTMLElement) => {
+ const size = readStudioBoxSize(element);
+ const width = size.width > 0 ? size.width : ORIGIN.width;
+ const height = size.height > 0 ? size.height : ORIGIN.height;
+ const offset = readStudioPathOffset(element);
+ return {
+ x: ORIGIN_CENTER.x + (width - ORIGIN.width) / 2 + offset.x,
+ y: ORIGIN_CENTER.y + (height - ORIGIN.height) / 2 + offset.y,
+ width,
+ height,
+ };
+ };
+ return {
+ ...actual,
+ elementCornerOverlayPoints: (_o: unknown, _i: unknown, element: HTMLElement) => {
+ const c = physicalCenter(element);
+ const hw = c.width / 2;
+ const hh = c.height / 2;
+ return {
+ nw: { x: c.x - hw, y: c.y - hh },
+ ne: { x: c.x + hw, y: c.y - hh },
+ sw: { x: c.x - hw, y: c.y + hh },
+ se: { x: c.x + hw, y: c.y + hh },
+ };
+ },
+ orientedOverlayRect: (_o: unknown, _i: unknown, element: HTMLElement) => {
+ const c = physicalCenter(element);
+ return {
+ left: c.x - c.width / 2,
+ top: c.y - c.height / 2,
+ width: c.width,
+ height: c.height,
+ editScaleX: 1,
+ editScaleY: 1,
+ angle: 0,
+ };
+ },
+ };
+});
+
+const { createDomEditOverlayGestureHandlers } = await import("./useDomEditOverlayGestures");
+
+function ref<T>(current: T) {
+ return { current };
+}
+
+interface CommitCall {
+ size: { width: number; height: number };
+ offset: { x: number; y: number } | undefined;
+}
+
+function buildHarness() {
+ const element = document.createElement("div");
+ document.body.append(element);
+
+ const selection = {
+ element,
+ id: "box",
+ selector: "#box",
+ selectorIndex: 0,
+ sourceFile: "index.html",
+ tagName: "div",
+ label: "Box",
+ textContent: "",
+ textFields: [],
+ capabilities: {
+ canEditText: false,
+ canEditLayout: true,
+ canMove: true,
+ canApplyManualOffset: true,
+ canApplyManualSize: true,
+ canApplyManualRotation: false,
+ canAdjustOpacity: true,
+ canAdjustFill: true,
+ canAdjustBorderRadius: true,
+ canAdjustStroke: true,
+ canAdjustShadow: true,
+ canAdjustZIndex: true,
+ },
+ computedStyle: { display: "block", position: "absolute" },
+ } as unknown as DomEditSelection;
+
+ const commits: CommitCall[] = [];
+ const overlayEl = document.createElement("div");
+ const iframe = document.createElement("iframe");
+
+ const opts: UseDomEditOverlayGesturesOptions = {
+ overlayRef: ref<HTMLDivElement | null>(overlayEl),
+ iframeRef: ref<HTMLIFrameElement | null>(iframe),
+ boxRef: ref<HTMLDivElement | null>(document.createElement("div")),
+ selectionRef: ref<DomEditSelection | null>(selection),
+ hoverSelectionRef: ref<DomEditSelection | null>(null),
+ overlayRectRef: ref<OverlayRectLike | null>({
+ left: ORIGIN.left,
+ top: ORIGIN.top,
+ width: ORIGIN.width,
+ height: ORIGIN.height,
+ editScaleX: 1,
+ editScaleY: 1,
+ }) as never,
+ groupOverlayItemsRef: ref([]),
+ gestureRef: ref<GestureState | null>(null),
+ groupGestureRef: ref(null),
+ blockedMoveRef: ref(null),
+ rafPausedRef: ref(false),
+ suppressNextBoxClickRef: ref(false),
+ setOverlayRect: () => {},
+ setGroupOverlayItems: () => {},
+ onBlockedMoveRef: ref(() => {}),
+ onManualDragStartRef: ref(() => {}),
+ onPathOffsetCommitRef: ref(() => {}),
+ onGroupPathOffsetCommitRef: ref(() => {}),
+ onBoxSizeCommitRef: ref((_s, size, offset) => {
+ commits.push({ size, offset });
+ }),
+ onRotationCommitRef: ref(() => {}),
+ onCanvasPointerMoveRef: ref(() => Promise.resolve(null)),
+ onCanvasMouseDown: () => {},
+ snapGuidesRef: ref(null),
+ };
+
+ const handlers = createDomEditOverlayGestureHandlers(opts);
+ return { handlers, commits, selection };
+}
+
+type OverlayRectLike = {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ editScaleX: number;
+ editScaleY: number;
+};
+
+function evt(clientX: number, clientY: number) {
+ return {
+ clientX,
+ clientY,
+ pointerId: 1,
+ button: 0,
+ altKey: false,
+ shiftKey: false,
+ preventDefault() {},
+ stopPropagation() {},
+ currentTarget: { setPointerCapture() {} },
+ } as unknown as React.PointerEvent<HTMLDivElement>;
+}
+
+afterEach(() => {
+ document.body.innerHTML = "";
+});
+
+describe("anchored corner resize — the release commit feeds the center-pin offset", () => {
+ it("onPointerUp passes a nonzero offset that keeps the center planted", () => {
+ const { handlers, commits } = buildHarness();
+
+ // Start an SE corner resize. Pointer starts 100px right of the center.
+ handlers.startGesture("resize", evt(ORIGIN_CENTER.x + 100, ORIGIN_CENTER.y), {
+ resizeHandle: "se",
+ });
+
+ // Drag outward to radial scale 1.5 (dist 150 / 100). Several frames so the
+ // per-frame center-pin anchor accumulates and converges into g.lastResizeAnchor.
+ for (let i = 0; i < 5; i++) {
+ handlers.onPointerMove(evt(ORIGIN_CENTER.x + 150, ORIGIN_CENTER.y));
+ }
+
+ handlers.onPointerUp(evt(ORIGIN_CENTER.x + 150, ORIGIN_CENTER.y));
+
+ expect(commits).toHaveLength(1);
+ const { size, offset } = commits[0]!;
+
+ // Proportional 1.5x growth of the 200x100 base.
+ expect(size.width).toBeCloseTo(300, 0);
+ expect(size.height).toBeCloseTo(150, 0);
+
+ // The committed offset must be present and nonzero — the open question.
+ expect(offset).toBeDefined();
+ if (!offset) return;
+ expect(offset.x).not.toBe(0);
+ expect(offset.y).not.toBe(0);
+
+ // And it must equal minus half the size growth, i.e. it re-pins the center to
+ // exactly the gesture-start center (offset = -(finalSize - origin)/2).
+ expect(offset.x).toBeCloseTo(-(size.width - ORIGIN.width) / 2, 0);
+ expect(offset.y).toBeCloseTo(-(size.height - ORIGIN.height) / 2, 0);
+ });
+});
diff --git a/packages/studio/src/components/editor/anchoredResizeReleaseShift.test.ts b/packages/studio/src/components/editor/anchoredResizeReleaseShift.test.ts
index 7e97d65d33..734fd3580d 100644
--- a/packages/studio/src/components/editor/anchoredResizeReleaseShift.test.ts
+++ b/packages/studio/src/components/editor/anchoredResizeReleaseShift.test.ts
@@ -8,6 +8,7 @@ import {
} from "./manualEditsDom";
import { buildBoxSizePatches, buildPathOffsetPatches } from "./manualEditsDomPatches";
import { createManualOffsetDragMember, applyManualOffsetDragCommit } from "./manualOffsetDrag";
+import { computeNextResizeAnchor } from "./domEditResizeLocal";
import type { PatchOperation } from "../../utils/sourcePatcher";
import { splitTopLevelWhitespace } from "./manualEditsStyleHelpers";
@@ -16,15 +17,25 @@ import { splitTopLevelWhitespace } from "./manualEditsStyleHelpers";
* CENTER, which must stay planted across the whole gesture — including after
* release, on every corner and at any rotation.
*
- * This file lands here with ONLY the persist round-trip test, which exercises the
- * real apply → persist → reload symbols that already exist at this point in the
- * stack. The two center-anchor CONVERGENCE tests (the release-shift root cause)
- * drive the exported `computeNextResizeAnchor` accumulator, which is extracted from
- * the resize pointermove branch of `useDomEditOverlayGestures.ts`. That gesture code
- * lands later in the stack (with the canvas glue swap), so those two tests are added
- * to this file at that point — importing the real production helper rather than a
- * test-local copy, so they can never pass against a stand-in that drifts from the
- * shipped math.
+ * Root cause of the original release "shift" (proved with a real-layout Chromium
+ * replay, see the anchor-loop test below): during a resize drag the per-frame
+ * anchor is derived from the element's LIVE measured center — which already carries
+ * the offset applied on the PREVIOUS frame — while `applyManualOffsetDragDraft`
+ * treats that anchor as the ABSOLUTE offset. So `fixedStart - centerNow` is really
+ * only the RESIDUAL correction, and using it as the absolute value makes the anchor
+ * OSCILLATE between the correct value and zero every frame:
+ * frame 0: offset 0 → center shifted by the resize → anchor = full amount → apply
+ * frame 1: offset applied → center back at fixedStart → anchor = 0 → apply 0 (un-pin!)
+ * frame 2: offset 0 again → anchor = full amount → ...
+ * Release commits `g.lastResizeAnchor` from whichever parity the last pointermove
+ * landed on, so the element lands EITHER pinned OR un-pinned — an unpredictable
+ * post-release "shift".
+ *
+ * Fix (useDomEditOverlayGestures pointermove, resize branch, fa4f39168): accumulate
+ * the residual onto the previously-applied anchor instead of using it as the
+ * absolute offset, so the loop converges to a stable value on every frame. The
+ * per-frame accumulation is the exported `computeNextResizeAnchor` helper (the one
+ * call site in the pointermove resize branch); tests 1 & 2 drive it directly.
*/
afterEach(() => {
@@ -66,10 +77,95 @@ function resolvedTranslatePx(el: HTMLElement): { x: number; y: number } {
}
describe("center-anchored corner resize — no shift after release", () => {
+ it("the per-frame center anchor converges (does NOT oscillate) — the release-shift root cause", () => {
+ // Model the pointermove anchor loop that pins the element's CENTER. The physical
+ // truth (confirmed in a real browser): the measured center sits at
+ // `fixedStart - appliedOffset` shifted by the resize — i.e. applying the offset
+ // moves the center back toward its gesture-start position. Here scale=1 so
+ // screen px == offset px. `trueAnchor` is the compensating offset that pins it.
+ const trueAnchor = { dx: -60, dy: -27 };
+ const fixedStart = { x: 500, y: 270 };
+
+ // `appliedOffset` mirrors what applyManualOffsetDragDraft set last frame.
+ let appliedOffset = { x: 0, y: 0 };
+ // `lastResizeAnchor` accumulator, exactly as g.lastResizeAnchor in the fix.
+ let lastResizeAnchor: { dx: number; dy: number } | undefined;
+
+ const anchorsSeen: Array<{ dx: number; dy: number }> = [];
+ for (let frame = 0; frame < 8; frame++) {
+ // Live measured center: the resize would put it at fixedStart + trueAnchor
+ // (un-anchored), and the currently-applied offset pulls it back by that
+ // offset. So centerNow = fixedStart - trueAnchor + appliedOffset.
+ const centerNow = {
+ x: fixedStart.x - trueAnchor.dx + appliedOffset.x,
+ y: fixedStart.y - trueAnchor.dy + appliedOffset.y,
+ };
+ // ── The fixed logic (accumulate residual onto the previous anchor) ──
+ const anchor = computeNextResizeAnchor(lastResizeAnchor, fixedStart, centerNow);
+ lastResizeAnchor = anchor;
+ anchorsSeen.push(anchor);
+ // applyManualOffsetDragDraft sets the absolute offset (scale 1) = anchor.
+ appliedOffset = { x: anchor.dx, y: anchor.dy };
+ }
+
+ // Every frame must report the same, correct anchor — no oscillation, so the
+ // committed value is parity-independent.
+ for (const a of anchorsSeen) {
+ expect(a).toEqual(trueAnchor);
+ }
+ // Guard against the OLD absolute formula regressing: with `anchor =
+ // fixedStart - centerNow` (no accumulation) the sequence would be
+ // [trueAnchor, 0, trueAnchor, 0, ...]; assert the last two frames agree.
+ expect(anchorsSeen.at(-1)).toEqual(anchorsSeen.at(-2));
+ });
+
+ it("the center stays fixed for every corner at any rotation (loop converges)", () => {
+ // The pin loop is handle- and rotation-independent: it always measures the
+ // element CENTER and drives it back to fixedStart. Simulate the loop for all
+ // four corners across unrotated + rotated gestures; the resize's raw center
+ // shift varies with corner/rotation (modelled as `rawShift`), but the loop must
+ // converge the measured center onto fixedStart every time.
+ const fixedStart = { x: 640, y: 360 };
+ const HANDLES = ["nw", "ne", "sw", "se"] as const;
+ const DEGS = [0, 30, 90, 137];
+ for (const handle of HANDLES) {
+ for (const deg of DEGS) {
+ const t = (deg * Math.PI) / 180;
+ // Raw (un-pinned) center shift the size write would cause this frame —
+ // a corner/rotation-dependent vector. Its exact value is irrelevant; the
+ // loop only needs to cancel it.
+ const seed = (HANDLES.indexOf(handle) + 1) * 11;
+ const rawShift = {
+ dx: Math.cos(t) * seed - Math.sin(t) * (seed / 2),
+ dy: Math.sin(t) * seed + Math.cos(t) * (seed / 2),
+ };
+ let appliedOffset = { x: 0, y: 0 };
+ let lastResizeAnchor: { dx: number; dy: number } | undefined;
+ let centerNow = { x: fixedStart.x, y: fixedStart.y };
+ for (let frame = 0; frame < 6; frame++) {
+ centerNow = {
+ x: fixedStart.x + rawShift.dx + appliedOffset.x,
+ y: fixedStart.y + rawShift.dy + appliedOffset.y,
+ };
+ const anchor = computeNextResizeAnchor(lastResizeAnchor, fixedStart, centerNow);
+ lastResizeAnchor = anchor;
+ appliedOffset = { x: anchor.dx, y: anchor.dy };
+ }
+ // After convergence the pinned center equals the gesture-start center.
+ const pinnedCenter = {
+ x: fixedStart.x + rawShift.dx + appliedOffset.x,
+ y: fixedStart.y + rawShift.dy + appliedOffset.y,
+ };
+ expect(pinnedCenter.x).toBeCloseTo(fixedStart.x, 9);
+ expect(pinnedCenter.y).toBeCloseTo(fixedStart.y, 9);
+ }
+ }
+ });
+
it("net translate after persist+reload equals the committed anchor offset (non-GSAP)", () => {
// The committed offset flows through the real apply → persist → reload chain
// unchanged (this hop was proved clean; the shift is upstream in the anchor
- // loop, tested with the gesture code, not in persistence).
+ // loop above, not in persistence).
const el = document.createElement("div");
el.style.setProperty("width", "200px");
el.style.setProperty("height", "100px");
diff --git a/packages/studio/src/components/editor/domEditNudge.test.ts b/packages/studio/src/components/editor/domEditNudge.test.ts
new file mode 100644
index 0000000000..4a90b1c22c
--- /dev/null
+++ b/packages/studio/src/components/editor/domEditNudge.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from "vitest";
+import {
+ CANVAS_NUDGE_SHIFT_STEP_PX,
+ CANVAS_NUDGE_STEP_PX,
+ canCanvasNudgeTargets,
+ resolveCanvasNudgeDelta,
+} from "./domEditNudge";
+
+function mockKeyboardEvent(
+ key: string,
+ overrides: Partial<Pick<KeyboardEvent, "altKey" | "ctrlKey" | "metaKey" | "shiftKey">> = {},
+): Pick<KeyboardEvent, "altKey" | "ctrlKey" | "metaKey" | "shiftKey" | "key"> {
+ return {
+ altKey: false,
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ key,
+ ...overrides,
+ };
+}
+
+describe("resolveCanvasNudgeDelta", () => {
+ it("maps plain arrows to 1px composition deltas", () => {
+ expect(resolveCanvasNudgeDelta(mockKeyboardEvent("ArrowLeft"))).toEqual({
+ dx: -CANVAS_NUDGE_STEP_PX,
+ dy: 0,
+ });
+ expect(resolveCanvasNudgeDelta(mockKeyboardEvent("ArrowRight"))).toEqual({
+ dx: CANVAS_NUDGE_STEP_PX,
+ dy: 0,
+ });
+ expect(resolveCanvasNudgeDelta(mockKeyboardEvent("ArrowUp"))).toEqual({
+ dx: 0,
+ dy: -CANVAS_NUDGE_STEP_PX,
+ });
+ expect(resolveCanvasNudgeDelta(mockKeyboardEvent("ArrowDown"))).toEqual({
+ dx: 0,
+ dy: CANVAS_NUDGE_STEP_PX,
+ });
+ });
+
+ it("maps Shift+arrow to 10px deltas", () => {
+ expect(resolveCanvasNudgeDelta(mockKeyboardEvent("ArrowRight", { shiftKey: true }))).toEqual({
+ dx: CANVAS_NUDGE_SHIFT_STEP_PX,
+ dy: 0,
+ });
+ expect(resolveCanvasNudgeDelta(mockKeyboardEvent("ArrowUp", { shiftKey: true }))).toEqual({
+ dx: 0,
+ dy: -CANVAS_NUDGE_SHIFT_STEP_PX,
+ });
+ });
+
+ it("ignores browser and app shortcut chords", () => {
+ expect(resolveCanvasNudgeDelta(mockKeyboardEvent("ArrowLeft", { altKey: true }))).toBeNull();
+ expect(resolveCanvasNudgeDelta(mockKeyboardEvent("ArrowLeft", { ctrlKey: true }))).toBeNull();
+ expect(resolveCanvasNudgeDelta(mockKeyboardEvent("ArrowLeft", { metaKey: true }))).toBeNull();
+ });
+
+ it("ignores non-arrow keys", () => {
+ expect(resolveCanvasNudgeDelta(mockKeyboardEvent("Escape"))).toBeNull();
+ expect(resolveCanvasNudgeDelta(mockKeyboardEvent("a"))).toBeNull();
+ });
+});
+
+describe("canCanvasNudgeTargets", () => {
+ const movable = { capabilities: { canApplyManualOffset: true } };
+ const locked = { capabilities: { canApplyManualOffset: false } };
+
+ it("requires at least one target", () => {
+ expect(canCanvasNudgeTargets([])).toBe(false);
+ });
+
+ it("allows only when every target accepts a manual offset", () => {
+ expect(canCanvasNudgeTargets([movable])).toBe(true);
+ expect(canCanvasNudgeTargets([movable, movable])).toBe(true);
+ expect(canCanvasNudgeTargets([locked])).toBe(false);
+ expect(canCanvasNudgeTargets([movable, locked])).toBe(false);
+ });
+});
diff --git a/packages/studio/src/components/editor/domEditNudge.ts b/packages/studio/src/components/editor/domEditNudge.ts
new file mode 100644
index 0000000000..b551061425
--- /dev/null
+++ b/packages/studio/src/components/editor/domEditNudge.ts
@@ -0,0 +1,44 @@
+/**
+ * Pure helpers for the canvas arrow-key nudge (DomEditOverlay).
+ *
+ * Mirrors captions/keyboard.ts conventions; the two nudge surfaces can't
+ * double-fire because PreviewOverlays mounts CaptionOverlay and DomEditOverlay
+ * mutually exclusively (caption edit mode returns before the DOM overlay).
+ */
+
+const CANVAS_NUDGE_KEYS = new Set(["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"]);
+
+export const CANVAS_NUDGE_STEP_PX = 1;
+export const CANVAS_NUDGE_SHIFT_STEP_PX = 10;
+/** One undo entry per key burst: the commit fires after this idle gap. */
+export const CANVAS_NUDGE_COMMIT_DEBOUNCE_MS = 400;
+
+type CanvasNudgeKeyEvent = Pick<
+ KeyboardEvent,
+ "altKey" | "ctrlKey" | "metaKey" | "shiftKey" | "key"
+>;
+
+/**
+ * Arrow key → composition-px delta (Shift = 10). Null when the key is not a
+ * plain/Shift arrow, so browser and app shortcut chords pass through.
+ */
+export function resolveCanvasNudgeDelta(
+ event: CanvasNudgeKeyEvent,
+): { dx: number; dy: number } | null {
+ if (event.metaKey || event.ctrlKey || event.altKey) return null;
+ if (!CANVAS_NUDGE_KEYS.has(event.key)) return null;
+ const step = event.shiftKey ? CANVAS_NUDGE_SHIFT_STEP_PX : CANVAS_NUDGE_STEP_PX;
+ return {
+ dx: event.key === "ArrowLeft" ? -step : event.key === "ArrowRight" ? step : 0,
+ dy: event.key === "ArrowUp" ? -step : event.key === "ArrowDown" ? step : 0,
+ };
+}
+
+export interface CanvasNudgeTarget {
+ capabilities: { canApplyManualOffset: boolean };
+}
+
+/** A nudge needs at least one target and every target must accept manual offsets. */
+export function canCanvasNudgeTargets(targets: ReadonlyArray<CanvasNudgeTarget>): boolean {
+ return targets.length > 0 && targets.every((t) => t.capabilities.canApplyManualOffset);
+}
diff --git a/packages/studio/src/components/editor/domEditOverlayGeometry.test.ts b/packages/studio/src/components/editor/domEditOverlayGeometry.test.ts
index 2bd16d839a..217f3d3430 100644
--- a/packages/studio/src/components/editor/domEditOverlayGeometry.test.ts
+++ b/packages/studio/src/components/editor/domEditOverlayGeometry.test.ts
@@ -1,6 +1,37 @@
// @vitest-environment jsdom
import { describe, expect, it } from "vitest";
-import { selectionCacheKey } from "./domEditOverlayGeometry";
+import {
+ orientedOverlayRect,
+ orientedGroupAwareOverlayRect,
+ overlayCornersCentroid,
+ selectionCacheKey,
+} from "./domEditOverlayGeometry";
+
+describe("overlayCornersCentroid", () => {
+ it("averages the four corners (the rendered rotation center)", () => {
+ expect(
+ overlayCornersCentroid({
+ nw: { x: 10, y: 20 },
+ ne: { x: 110, y: 20 },
+ se: { x: 110, y: 80 },
+ sw: { x: 10, y: 80 },
+ }),
+ ).toEqual({ x: 60, y: 50 });
+ });
+
+ it("is unchanged by rotation — a rotated square's corners average to its center", () => {
+ // Unit square centered at (5,5), rotated 45deg about its center: corners land
+ // on the axis midpoints, whose average is still the center.
+ const c = overlayCornersCentroid({
+ nw: { x: 5, y: 5 - Math.SQRT2 / 2 },
+ ne: { x: 5 + Math.SQRT2 / 2, y: 5 },
+ se: { x: 5, y: 5 + Math.SQRT2 / 2 },
+ sw: { x: 5 - Math.SQRT2 / 2, y: 5 },
+ });
+ expect(c.x).toBeCloseTo(5, 9);
+ expect(c.y).toBeCloseTo(5, 9);
+ });
+});
describe("selectionCacheKey — hfId collision (R7)", () => {
it("produces distinct keys for two elements that differ only by hfId", () => {
@@ -11,3 +42,138 @@ describe("selectionCacheKey — hfId collision (R7)", () => {
expect(a).not.toBe(b);
});
});
+
+describe("orientedOverlayRect — rotation gate (perf fix, V15 18a/18b)", () => {
+ // jsdom has no DOMMatrix/DOMPoint; a minimal stand-in is enough to exercise the
+ // real (unmocked) orientedOverlayRect, unlike DomEditOverlay.test.ts and
+ // anchoredResizeCommitFeedsOffset.test.ts, which mock this module entirely.
+ class FakeDOMMatrix {
+ a = 1;
+ b = 0;
+ c = 0;
+ d = 1;
+ e = 0;
+ f = 0;
+ constructor(init?: string) {
+ const m = init ? /matrix\(([^)]+)\)/.exec(init) : null;
+ if (!m) return;
+ const parts = m[1]!.split(",").map((s) => Number.parseFloat(s.trim()));
+ [this.a, this.b, this.c, this.d, this.e, this.f] = parts as [
+ number,
+ number,
+ number,
+ number,
+ number,
+ number,
+ ];
+ }
+ transformPoint(pt: { x: number; y: number }) {
+ return {
+ x: this.a * pt.x + this.c * pt.y + this.e,
+ y: this.b * pt.x + this.d * pt.y + this.f,
+ };
+ }
+ }
+ class FakeDOMPoint {
+ constructor(
+ public x: number,
+ public y: number,
+ ) {}
+ }
+ // matrix() form of rotate(30deg), so the module's `new DOMMatrix(cs.transform)`
+ // parse (which expects "matrix(...)", not "rotate(...)") resolves correctly.
+ const ROTATE_30DEG_MATRIX =
+ "matrix(0.8660254037844387, 0.49999999999999994, -0.49999999999999994, 0.8660254037844387, 0, 0)";
+
+ function stubRect(
+ el: Element,
+ rect: { left: number; top: number; width: number; height: number },
+ ) {
+ (el as unknown as { getBoundingClientRect: () => DOMRect }).getBoundingClientRect = () =>
+ ({
+ left: rect.left,
+ top: rect.top,
+ width: rect.width,
+ height: rect.height,
+ right: rect.left + rect.width,
+ bottom: rect.top + rect.height,
+ x: rect.left,
+ y: rect.top,
+ toJSON() {
+ return this;
+ },
+ }) as DOMRect;
+ }
+
+ function buildHarness() {
+ const overlayEl = document.createElement("div");
+ document.body.appendChild(overlayEl);
+ stubRect(overlayEl, { left: 0, top: 0, width: 1000, height: 1000 });
+
+ const iframe = document.createElement("iframe");
+ document.body.appendChild(iframe);
+ stubRect(iframe, { left: 0, top: 0, width: 1000, height: 1000 });
+
+ const doc = iframe.contentDocument!;
+ const root = doc.createElement("div");
+ root.setAttribute("data-composition-id", "root");
+ root.setAttribute("data-width", "1000");
+ root.setAttribute("data-height", "1000");
+ doc.body.appendChild(root);
+
+ const el = doc.createElement("div");
+ root.appendChild(el);
+ stubRect(el, { left: 400, top: 450, width: 200, height: 100 });
+ Object.defineProperty(el, "offsetWidth", { value: 200, configurable: true });
+ Object.defineProperty(el, "offsetHeight", { value: 100, configurable: true });
+
+ const win = iframe.contentWindow as unknown as Window & {
+ DOMMatrix: unknown;
+ DOMPoint: unknown;
+ };
+ win.DOMMatrix = FakeDOMMatrix;
+ win.DOMPoint = FakeDOMPoint;
+
+ return { overlayEl, iframe, el };
+ }
+
+ it("unrotated element takes the cheap AABB path — matches the raw bounding rect, angle 0", () => {
+ const { overlayEl, iframe, el } = buildHarness();
+ const rect = orientedOverlayRect(overlayEl, iframe, el);
+ expect(rect).not.toBeNull();
+ expect(rect!.left).toBeCloseTo(400, 5);
+ expect(rect!.top).toBeCloseTo(450, 5);
+ expect(rect!.width).toBeCloseTo(200, 5);
+ expect(rect!.height).toBeCloseTo(100, 5);
+ expect(rect!.angle ?? 0).toBe(0);
+ });
+
+ it("rotated element takes the corner-geometry path — reports the live angle", () => {
+ const { overlayEl, iframe, el } = buildHarness();
+ el.style.transform = ROTATE_30DEG_MATRIX;
+ const rect = orientedOverlayRect(overlayEl, iframe, el);
+ expect(rect).not.toBeNull();
+ expect(rect!.angle).toBeCloseTo(30, 3);
+ });
+
+ it("preserves an ordinary element's rotation through the group-aware entry point", () => {
+ const { overlayEl, iframe, el } = buildHarness();
+ el.style.transform = ROTATE_30DEG_MATRIX;
+ const rect = orientedGroupAwareOverlayRect(overlayEl, iframe, el);
+ expect(rect!.angle).toBeCloseTo(30, 3);
+ });
+
+ it("gate re-evaluates every call — editing an element to rotated mid-session flips the path immediately", () => {
+ const { overlayEl, iframe, el } = buildHarness();
+ const before = orientedOverlayRect(overlayEl, iframe, el);
+ expect(before?.angle ?? 0).toBe(0);
+
+ el.style.transform = ROTATE_30DEG_MATRIX;
+ const after = orientedOverlayRect(overlayEl, iframe, el);
+ expect(after!.angle).toBeCloseTo(30, 3);
+
+ el.style.transform = "";
+ const restored = orientedOverlayRect(overlayEl, iframe, el);
+ expect(restored?.angle ?? 0).toBe(0);
+ });
+});
diff --git a/packages/studio/src/components/editor/domEditOverlayGeometry.ts b/packages/studio/src/components/editor/domEditOverlayGeometry.ts
index 31af58f644..70f2500958 100644
--- a/packages/studio/src/components/editor/domEditOverlayGeometry.ts
+++ b/packages/studio/src/components/editor/domEditOverlayGeometry.ts
@@ -9,6 +9,14 @@ export interface OverlayRect {
height: number;
editScaleX: number;
editScaleY: number;
+ /**
+ * The element's live transform rotation in DEGREES (screen/CSS convention, CW
+ * positive), decomposed from its computed transform matrix. Present so the
+ * selection chrome can render as an oriented bounding box (OBB) that co-rotates
+ * with the element. Omitted (treated as 0) for group/union rects and when the
+ * transform is unmeasurable — those render axis-aligned exactly as before.
+ */
+ angle?: number;
}
export interface GroupOverlayItem {
@@ -98,31 +106,115 @@ export function toVisibleOverlayRect(
return rect ? { ...rect, ...hugRectForElement(rect, element) } : null;
}
-export function toOverlayRect(
+/**
+ * getComputedStyle(element).transform decomposed into a DOMMatrix, read ONCE.
+ * Shared by orientedOverlayRect's rotation gate and elementCornerOverlayPoints
+ * so a single measurement pass serves both — constructing this twice per frame
+ * (one read per consumer) was redundant work; see orientedOverlayRect below.
+ */
+interface ElementTransformSnapshot {
+ matrix: DOMMatrix;
+ cs: CSSStyleDeclaration;
+}
+
+function readElementTransformSnapshot(
+ win: Window,
+ element: HTMLElement,
+): ElementTransformSnapshot | null {
+ const DOMMatrixCtor = (win as Window & typeof globalThis).DOMMatrix;
+ if (!DOMMatrixCtor) return null;
+ const cs = win.getComputedStyle(element);
+ try {
+ const matrix = new DOMMatrixCtor(cs.transform === "none" ? "" : cs.transform);
+ return { matrix, cs };
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The element's live transform rotation, in DEGREES (screen/CSS convention, CW
+ * positive), decomposed from its transform matrix (rotation = atan2(b, a)).
+ * GSAP folds rotation and scale into the same matrix; this reads rotation only.
+ * Skew is ignored (does not affect atan2(b, a)).
+ */
+function rotationDegreesFromMatrix(matrix: DOMMatrix): number {
+ const a = Number.isFinite(matrix.a) ? matrix.a : 1;
+ const b = Number.isFinite(matrix.b) ? matrix.b : 0;
+ const deg = (Math.atan2(b, a) * 180) / Math.PI;
+ return Number.isFinite(deg) ? deg : 0;
+}
+
+/** Below this, orientedOverlayRect treats the element as unrotated and returns
+ * the AABB directly (see its doc comment) — tight enough to only swallow
+ * matrix-decomposition floating-point noise, never an actual rotation. */
+const ROTATION_GATE_EPSILON_DEG = 1e-4;
+
+/** iframe→overlay mapping basis shared by every overlay-geometry function. */
+interface OverlayRootScale {
+ iframeRect: DOMRect;
+ overlayRect: DOMRect;
+ rootScaleX: number;
+ rootScaleY: number;
+}
+
+/** The composition root element inside the preview doc (or null when absent). */
+function findOverlayRootElement(doc: Document | null): HTMLElement | null {
+ return doc?.querySelector<HTMLElement>("[data-composition-id]") ?? doc?.documentElement ?? null;
+}
+
+/**
+ * The root's effective width/height for scaling: prefer the composition's
+ * declared dimensions (data-width/data-height), which stay fixed while GSAP
+ * transforms mutate the measured rect; fall back to the measured rect. Null when
+ * unmeasurable.
+ */
+function resolveRootDimensions(root: HTMLElement | null): { width: number; height: number } | null {
+ if (!root) return null;
+ const rootRect = root.getBoundingClientRect();
+ const width = readPositiveDimension(root.getAttribute("data-width")) ?? rootRect.width;
+ const height = readPositiveDimension(root.getAttribute("data-height")) ?? rootRect.height;
+ if (!width || !height) return null;
+ return { width, height };
+}
+
+/**
+ * The iframe/overlay client rects and the iframe→root scale factors. Uses the
+ * composition's declared dimensions (data-width/data-height) for the scale
+ * instead of rootRect.width/height: when GSAP applies transforms (scale,
+ * translate) to the root, rootRect dimensions change but the composition's
+ * canonical size stays fixed, and using rootRect misaligns the overlay during
+ * animated playback. Returns null when the geometry is unmeasurable.
+ */
+function computeOverlayRootScale(
overlayEl: HTMLDivElement,
iframe: HTMLIFrameElement,
- element: HTMLElement,
-): OverlayRect | null {
+ doc: Document | null,
+): OverlayRootScale | null {
const iframeRect = iframe.getBoundingClientRect();
const overlayRect = overlayEl.getBoundingClientRect();
- const doc = iframe.contentDocument;
- const root =
- doc?.querySelector<HTMLElement>("[data-composition-id]") ?? doc?.documentElement ?? null;
- const rootRect = root?.getBoundingClientRect();
- // Use the composition's declared dimensions (data-width/data-height) for scale
- // calculation instead of rootRect.width/height. When GSAP applies transforms
- // (scale, translate) to the root element, rootRect dimensions change but the
- // composition's canonical size stays the same. Using rootRect causes overlay
- // misalignment during animated playback.
- const declaredWidth = readPositiveDimension(root?.getAttribute("data-width") ?? null);
- const declaredHeight = readPositiveDimension(root?.getAttribute("data-height") ?? null);
- const rootWidth = declaredWidth ?? rootRect?.width;
- const rootHeight = declaredHeight ?? rootRect?.height;
- if (!rootWidth || !rootHeight || !rootRect) return null;
+ const dims = resolveRootDimensions(findOverlayRootElement(doc));
+ if (!dims) return null;
+ return {
+ iframeRect,
+ overlayRect,
+ rootScaleX: iframeRect.width / dims.width,
+ rootScaleY: iframeRect.height / dims.height,
+ };
+}
+
+function toOverlayRect(
+ overlayEl: HTMLDivElement,
+ iframe: HTMLIFrameElement,
+ element: HTMLElement,
+ precomputedScale?: OverlayRootScale | null,
+): OverlayRect | null {
+ const scale =
+ precomputedScale ?? computeOverlayRootScale(overlayEl, iframe, iframe.contentDocument);
+ if (!scale) return null;
+ const { iframeRect, overlayRect, rootScaleX, rootScaleY } = scale;
const elementRect = element.getBoundingClientRect();
- const rootScaleX = iframeRect.width / rootWidth;
- const rootScaleY = iframeRect.height / rootHeight;
const sourceBoundary = findSourceBoundary(element);
const sourceBoundaryRect = sourceBoundary?.getBoundingClientRect();
const editScale = resolveDomEditCoordinateScale({
@@ -144,7 +236,163 @@ export function toOverlayRect(
};
}
+/** Which physical corner of the (possibly rotated) element a resize handle keeps
+ * fixed: NW grabs the top-left, so the bottom-right (se) is the anchor, etc. */
+export type FixedCorner = "nw" | "ne" | "sw" | "se";
+
+/** Distance between two overlay-px corner points — the edge-length math
+ * orientedOverlayRect uses to turn corners into a width/height. Exported so a
+ * caller already holding raw corners (e.g. a resize gesture mid-measurement)
+ * can derive the same dimensions without a second orientedOverlayRect call. */
+export function cornerEdgeLength(a: { x: number; y: number }, b: { x: number; y: number }): number {
+ return Math.hypot(b.x - a.x, b.y - a.y);
+}
+
+/**
+ * The centroid (rendered center) of the four transformed corners from
+ * `elementCornerOverlayPoints`, in overlay px. This is the element's true rotation
+ * center — the point a center-anchored resize keeps planted.
+ */
+export function overlayCornersCentroid(corners: Record<FixedCorner, { x: number; y: number }>): {
+ x: number;
+ y: number;
+} {
+ return {
+ x: (corners.nw.x + corners.ne.x + corners.se.x + corners.sw.x) / 4,
+ y: (corners.nw.y + corners.ne.y + corners.se.y + corners.sw.y) / 4,
+ };
+}
+
+/**
+ * The element's border-box corners in OVERLAY coordinates, honoring its live
+ * transform (rotation/skew/scale) — NOT the axis-aligned getBoundingClientRect.
+ * A rotated element's four visual corners are the transformed local box corners.
+ * Uses the same iframe→overlay root scale as toOverlayRect so the returned
+ * points share that function's coordinate space. Returns null when the
+ * geometry is unmeasurable.
+ */
+export function elementCornerOverlayPoints(
+ overlayEl: HTMLDivElement,
+ iframe: HTMLIFrameElement,
+ element: HTMLElement,
+ precomputedScale?: OverlayRootScale | null,
+ precomputedTransform?: ElementTransformSnapshot | null,
+): Record<FixedCorner, { x: number; y: number }> | null {
+ const win = iframe.contentWindow;
+ const doc = iframe.contentDocument;
+ if (!win || !doc) return null;
+ const DOMPointCtor = (win as Window & typeof globalThis).DOMPoint;
+ if (!DOMPointCtor) return null;
+
+ const scale = precomputedScale ?? computeOverlayRootScale(overlayEl, iframe, doc);
+ if (!scale) return null;
+ const { iframeRect, overlayRect, rootScaleX, rootScaleY } = scale;
+
+ // The element's local border box maps to viewport coords by the SAME transform
+ // matrix the browser used for its BCR. We recover the transform's screen-space
+ // action from the BCR: transformPoint(localCorner - origin) gives a corner
+ // RELATIVE to the transformed origin. We anchor those relative corners to the
+ // BCR by matching the AABB of the transformed corners to the real BCR — the
+ // constant offset cancels in the before/after difference the caller takes, but
+ // we resolve it fully here so callers can also read absolute overlay positions.
+ const transform = precomputedTransform ?? readElementTransformSnapshot(win, element);
+ if (!transform) return null;
+ const { matrix, cs } = transform;
+ const w = element.offsetWidth;
+ const h = element.offsetHeight;
+ const originParts = cs.transformOrigin.split(" ").map((p) => Number.parseFloat(p));
+ const ox = Number.isFinite(originParts[0]!) ? originParts[0]! : w / 2;
+ const oy = Number.isFinite(originParts[1]!) ? originParts[1]! : h / 2;
+ const rel = (lx: number, ly: number): { x: number; y: number } => {
+ const p = matrix.transformPoint(new DOMPointCtor(lx - ox, ly - oy));
+ return { x: p.x, y: p.y };
+ };
+ const relCorners = {
+ nw: rel(0, 0),
+ ne: rel(w, 0),
+ se: rel(w, h),
+ sw: rel(0, h),
+ };
+ // Recover the absolute viewport position by matching to the element's BCR:
+ // the relative corners' AABB min corresponds to the BCR's top-left.
+ const xs = [relCorners.nw.x, relCorners.ne.x, relCorners.se.x, relCorners.sw.x];
+ const ys = [relCorners.nw.y, relCorners.ne.y, relCorners.se.y, relCorners.sw.y];
+ const bcr = element.getBoundingClientRect();
+ const dx = bcr.left - Math.min(...xs);
+ const dy = bcr.top - Math.min(...ys);
+ const toOverlay = (pt: { x: number; y: number }): { x: number; y: number } => ({
+ x: iframeRect.left - overlayRect.left + (pt.x + dx) * rootScaleX,
+ y: iframeRect.top - overlayRect.top + (pt.y + dy) * rootScaleY,
+ });
+ return {
+ nw: toOverlay(relCorners.nw),
+ ne: toOverlay(relCorners.ne),
+ se: toOverlay(relCorners.se),
+ sw: toOverlay(relCorners.sw),
+ };
+}
+
+/**
+ * The selection chrome's ORIENTED bounding box: the element's UNROTATED border box
+ * expressed in overlay coordinates (center-anchored left/top/width/height) plus the
+ * live rotation angle. Rendering that rect with `transform: rotate(angle)` about its
+ * center reproduces the element's real transformed corners exactly, so the border,
+ * corner dots, rotate handle, and crop pills all co-rotate with the object.
+ *
+ * Built from `elementCornerOverlayPoints` (the real transformed corners): the OBB
+ * center is the corner centroid, the unrotated width/height are the edge lengths, and
+ * left/top place the unrotated box so that rotating it about its center lands the
+ * corners back on the measured points. At angle 0 this equals `toOverlayRect` (the
+ * AABB and OBB coincide), so unrotated chrome is pixel-identical to today.
+ *
+ * Returns the plain AABB rect (angle 0) when the corner geometry can't be measured.
+ *
+ * Rotation gate: an unrotated element's OBB is numerically identical to its AABB
+ * (the comment above), so a cheap rotation read decides up front whether the
+ * (much pricier) corner-transform pass runs at all — for the overwhelming
+ * majority of selections, which aren't rotated, this call is just `toOverlayRect`
+ * plus one getComputedStyle/DOMMatrix read. The root scale and the transform
+ * snapshot are each computed once per call and threaded into both the rotation
+ * read and the corner math, instead of every helper re-measuring independently.
+ */
+export function orientedOverlayRect(
+ overlayEl: HTMLDivElement,
+ iframe: HTMLIFrameElement,
+ element: HTMLElement,
+): OverlayRect | null {
+ const scale = computeOverlayRootScale(overlayEl, iframe, iframe.contentDocument);
+ if (!scale) return null;
+ const base = toOverlayRect(overlayEl, iframe, element, scale);
+ if (!base) return null;
+
+ const win = iframe.contentWindow;
+ const transform = win ? readElementTransformSnapshot(win, element) : null;
+ const angle = transform ? rotationDegreesFromMatrix(transform.matrix) : 0;
+ if (Math.abs(angle) < ROTATION_GATE_EPSILON_DEG) return base;
+
+ const corners = elementCornerOverlayPoints(overlayEl, iframe, element, scale, transform);
+ if (!corners) return base;
+ // Unrotated edge lengths (in overlay px): nw→ne is the width, nw→sw the height.
+ const width = cornerEdgeLength(corners.nw, corners.ne);
+ const height = cornerEdgeLength(corners.nw, corners.sw);
+ const centerX = (corners.nw.x + corners.se.x) / 2;
+ const centerY = (corners.nw.y + corners.se.y) / 2;
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
+ return base;
+ }
+ return {
+ left: centerX - width / 2,
+ top: centerY - height / 2,
+ width,
+ height,
+ editScaleX: base.editScaleX,
+ editScaleY: base.editScaleY,
+ angle,
+ };
+}
+
const OVERLAY_RECT_EPSILON_PX = 0.5;
+const OVERLAY_RECT_ANGLE_EPSILON_DEG = 0.1;
export function rectsEqual(a: OverlayRect | null, b: OverlayRect | null): boolean {
if (a === b) return true;
@@ -155,7 +403,8 @@ export function rectsEqual(a: OverlayRect | null, b: OverlayRect | null): boolea
Math.abs(a.width - b.width) < OVERLAY_RECT_EPSILON_PX &&
Math.abs(a.height - b.height) < OVERLAY_RECT_EPSILON_PX &&
Math.abs(a.editScaleX - b.editScaleX) < 0.001 &&
- Math.abs(a.editScaleY - b.editScaleY) < 0.001
+ Math.abs(a.editScaleY - b.editScaleY) < 0.001 &&
+ Math.abs((a.angle ?? 0) - (b.angle ?? 0)) < OVERLAY_RECT_ANGLE_EPSILON_DEG
);
}
@@ -228,6 +477,17 @@ export function groupAwareOverlayRect(
return { ...union, editScaleX: rect.editScaleX, editScaleY: rect.editScaleY };
}
+/** Groups stay axis-aligned unions; ordinary elements keep their oriented box. */
+export function orientedGroupAwareOverlayRect(
+ overlayEl: HTMLDivElement,
+ iframe: HTMLIFrameElement,
+ el: HTMLElement,
+): OverlayRect | null {
+ return el.hasAttribute("data-hf-group")
+ ? groupAwareOverlayRect(overlayEl, iframe, el)
+ : orientedOverlayRect(overlayEl, iframe, el);
+}
+
export function filterNestedDomEditGroupItems<T extends { element: HTMLElement }>(items: T[]): T[] {
return items.filter(
(item) => !items.some((other) => other !== item && other.element.contains(item.element)),
diff --git a/packages/studio/src/components/editor/domEditOverlayGestures.ts b/packages/studio/src/components/editor/domEditOverlayGestures.ts
index 2abc793b65..d7fec86a87 100644
--- a/packages/studio/src/components/editor/domEditOverlayGestures.ts
+++ b/packages/studio/src/components/editor/domEditOverlayGestures.ts
@@ -13,10 +13,20 @@ import type { PreviewMouseDownOptions } from "../../hooks/usePreviewInteraction"
export type GestureKind = "drag" | "resize" | "rotate";
+/** Which corner handle initiated a resize gesture. */
+export type ResizeHandle = "nw" | "ne" | "sw" | "se";
+
export const BLOCKED_MOVE_THRESHOLD_PX = 4;
-const MIN_RESIZE_EDGE_PX = 20;
const ROTATION_COMMIT_EPSILON_DEGREES = 0.05;
const ROTATION_SNAP_DEGREES = 15;
+/**
+ * Above this rotation, resize/move edge-snapping is bypassed. Industry editors
+ * (tldraw/Figma) don't edge-snap rotated boxes — the snap targets are axis-aligned
+ * AABBs, so snapping a rotated box's AABB to them shifts the box in a way the user
+ * can't predict; a wrong snap is worse than none. Rotation ~0 keeps snapping exactly
+ * as before.
+ */
+export const ROTATED_SNAP_BYPASS_DEGREES = 0.5;
export interface GestureState {
kind: GestureKind;
@@ -62,6 +72,19 @@ export interface GestureState {
snapContext?: SnapContext;
lastSnappedDx?: number;
lastSnappedDy?: number;
+ /** Corner the resize gesture grabbed (resize gestures only). */
+ resizeHandle?: ResizeHandle;
+ /** Last anchoring translation applied during a corner resize (overlay px). */
+ lastResizeAnchor?: { dx: number; dy: number };
+ /**
+ * The element's rendered CENTER in overlay px at gesture start (the centroid of
+ * its four real — possibly rotated — corners). A center-anchored resize keeps this
+ * point pinned; the per-frame anchor translation is computed as the shift of this
+ * exact center, not an AABB width/height delta (which only holds the center still
+ * when the element grows symmetrically from an unrotated layout box). Undefined
+ * when the corner geometry can't be measured (member creation still succeeded).
+ */
+ resizeFixedCenterStart?: { x: number; y: number };
}
export interface GroupGestureState {
@@ -89,48 +112,23 @@ export function focusDomEditOverlayElement(element: FocusableDomEditOverlay | nu
element?.focus({ preventScroll: true });
}
-export function resolveDomEditResizeGesture(input: {
+/**
+ * Overlay-px translation that keeps the element's CENTER fixed while a corner
+ * resizes: a CSS width/height change grows the layout box from its top-left, so
+ * the center drifts by half the size change on each axis; translating back by that
+ * half-delta re-pins the center. This is the UNROTATED (AABB) fallback used only
+ * when the element's real transformed corners can't be measured — the primary path
+ * pins the measured center (rotation-safe) in useDomEditOverlayGestures.
+ */
+export function resolveResizeCenterAnchorOffset(input: {
originWidth: number;
originHeight: number;
- actualWidth: number;
- actualHeight: number;
- scaleX: number;
- scaleY: number;
- // Rendered-per-CSS-pixel factor of the element itself (its live GSAP scale).
- // The CSS width/height the draft writes get multiplied by this on screen, so
- // the cursor delta must be divided by it — otherwise the box outruns the
- // pointer on a rescaled element and snaps back on release. Defaults to 1.
- contentScaleX?: number;
- contentScaleY?: number;
- dx: number;
- dy: number;
- uniform: boolean;
-}): { overlayWidth: number; overlayHeight: number; width: number; height: number } {
- const scaleX = input.scaleX > 0 ? input.scaleX : 1;
- const scaleY = input.scaleY > 0 ? input.scaleY : 1;
- const contentScaleX =
- input.contentScaleX !== undefined && input.contentScaleX > 0 ? input.contentScaleX : 1;
- const contentScaleY =
- input.contentScaleY !== undefined && input.contentScaleY > 0 ? input.contentScaleY : 1;
-
- if (input.uniform) {
- const deltaX = input.dx / (scaleX * contentScaleX);
- const deltaY = input.dy / (scaleY * contentScaleY);
- const delta = Math.abs(deltaX) >= Math.abs(deltaY) ? deltaX : deltaY;
- const side = Math.max(1, Math.max(input.actualWidth, input.actualHeight) + delta);
- return {
- overlayWidth: Math.max(MIN_RESIZE_EDGE_PX, side * scaleX * contentScaleX),
- overlayHeight: Math.max(MIN_RESIZE_EDGE_PX, side * scaleY * contentScaleY),
- width: side,
- height: side,
- };
- }
-
+ overlayWidth: number;
+ overlayHeight: number;
+}): { dx: number; dy: number } {
return {
- overlayWidth: Math.max(MIN_RESIZE_EDGE_PX, input.originWidth + input.dx),
- overlayHeight: Math.max(MIN_RESIZE_EDGE_PX, input.originHeight + input.dy),
- width: Math.max(1, input.actualWidth + input.dx / (scaleX * contentScaleX)),
- height: Math.max(1, input.actualHeight + input.dy / (scaleY * contentScaleY)),
+ dx: (input.originWidth - input.overlayWidth) / 2,
+ dy: (input.originHeight - input.overlayHeight) / 2,
};
}
@@ -214,7 +212,12 @@ export type UseDomEditOverlayGesturesOptions = {
(updates: DomEditGroupPathOffsetCommit[]) => Promise<void> | void
>;
onBoxSizeCommitRef: RefObject<
- (s: DomEditSelection, n: { width: number; height: number }) => Promise<void> | void
+ (
+ s: DomEditSelection,
+ n: { width: number; height: number },
+ offset?: { x: number; y: number },
+ restore?: () => void,
+ ) => Promise<void> | void
>;
onRotationCommitRef: RefObject<
(s: DomEditSelection, n: { angle: number }) => Promise<void> | void
diff --git a/packages/studio/src/components/editor/domEditOverlayStartGesture.ts b/packages/studio/src/components/editor/domEditOverlayStartGesture.ts
index 636265e206..6576a9b5ba 100644
--- a/packages/studio/src/components/editor/domEditOverlayStartGesture.ts
+++ b/packages/studio/src/components/editor/domEditOverlayStartGesture.ts
@@ -20,15 +20,19 @@ import {
} from "./manualEdits";
import {
type OverlayRect,
+ elementCornerOverlayPoints,
filterNestedDomEditGroupItems,
+ overlayCornersCentroid,
selectionCacheKey,
} from "./domEditOverlayGeometry";
import {
type GestureKind,
type GestureState,
+ type ResizeHandle,
type UseDomEditOverlayGesturesOptions,
} from "./domEditOverlayGestures";
import { collectSnapContext, buildExcludeElements } from "./snapTargetCollection";
+import { logResize, resetResizeMoveLog } from "../../utils/resizeDebug";
export function startGroupDrag(
e: React.PointerEvent<HTMLElement>,
@@ -100,7 +104,11 @@ export function startGesture(
kind: GestureKind,
e: React.PointerEvent<HTMLElement>,
opts: UseDomEditOverlayGesturesOptions,
- options?: { selection?: DomEditSelection; rect?: OverlayRect | null },
+ options?: {
+ selection?: DomEditSelection;
+ rect?: OverlayRect | null;
+ resizeHandle?: ResizeHandle;
+ },
): boolean {
const sel = options?.selection ?? opts.selectionRef.current;
const rect = options?.rect ?? opts.overlayRectRef.current;
@@ -173,7 +181,29 @@ export function startGesture(
initialPathOffset = result.member.initialPathOffset;
manualEditDragToken = result.member.gestureToken;
} else {
- manualEditDragToken = beginStudioManualEditGesture(sel.element);
+ // Center-anchored corner resize (CapCut model): the element scales about its
+ // CENTER, which stays planted. All four corners behave identically, so EVERY
+ // corner needs the manual-offset member that translates the element to re-pin
+ // its center per frame (the memberless else-branch is only a defensive fallback
+ // if member creation fails, e.g. the element can't take a manual offset).
+ const needsAnchorOffset = kind === "resize" && sel.capabilities.canApplyManualOffset;
+ if (needsAnchorOffset) {
+ const result = createManualOffsetDragMember({
+ key: selectionCacheKey(sel),
+ selection: sel,
+ element: sel.element,
+ rect,
+ });
+ if (result.ok) {
+ pathOffsetMember = result.member;
+ initialPathOffset = result.member.initialPathOffset;
+ manualEditDragToken = result.member.gestureToken;
+ } else {
+ manualEditDragToken = beginStudioManualEditGesture(sel.element);
+ }
+ } else {
+ manualEditDragToken = beginStudioManualEditGesture(sel.element);
+ }
}
const overlayBounds = overlayEl?.getBoundingClientRect();
@@ -181,6 +211,17 @@ export function startGesture(
const centerY = (overlayBounds?.top ?? 0) + rect.top + rect.height / 2;
const iframe = opts.iframeRef.current;
+
+ // For a center-anchored corner resize, capture the element's rendered CENTER (the
+ // centroid of its four real, rotation-aware corners) now, so per-frame anchoring
+ // can pin that exact point instead of an axis-aligned width/height delta (which
+ // only holds the center still when the element grows symmetrically from an
+ // unrotated layout box). Present whenever an anchor member exists (all corners).
+ let resizeFixedCenterStart: { x: number; y: number } | undefined;
+ if (kind === "resize" && pathOffsetMember && overlayEl && iframe) {
+ const corners = elementCornerOverlayPoints(overlayEl, iframe, sel.element);
+ if (corners) resizeFixedCenterStart = overlayCornersCentroid(corners);
+ }
const snapContext =
(kind === "drag" || kind === "resize") && overlayEl && iframe
? collectSnapContext({
@@ -219,6 +260,25 @@ export function startGesture(
resizeAnchor,
manualEditDragToken,
snapContext,
+ resizeHandle: kind === "resize" ? (options?.resizeHandle ?? "se") : undefined,
+ resizeFixedCenterStart,
};
+ if (kind === "resize") {
+ resetResizeMoveLog();
+ logResize("start", {
+ handle: options?.resizeHandle ?? "se",
+ pointer: { x: e.clientX, y: e.clientY },
+ center: { x: centerX, y: centerY },
+ origin: { left: rect.left, top: rect.top, w: rect.width, h: rect.height },
+ actual: { w: actualWidth, h: actualHeight },
+ editScale: { x: rect.editScaleX, y: rect.editScaleY },
+ contentScale: { x: contentScaleX, y: contentScaleY },
+ rotation: rotation.angle,
+ hasOffsetMember: !!pathOffsetMember,
+ fixedCenterStart: resizeFixedCenterStart ?? null,
+ initialBoxSize: opts.gestureRef.current?.initialBoxSize ?? null,
+ initialInlineStyle: sel.element.getAttribute("style"),
+ });
+ }
return true;
}
diff --git a/packages/studio/src/components/editor/domEditResizeLocal.test.ts b/packages/studio/src/components/editor/domEditResizeLocal.test.ts
new file mode 100644
index 0000000000..8842b61f17
--- /dev/null
+++ b/packages/studio/src/components/editor/domEditResizeLocal.test.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it } from "vitest";
+import {
+ resolveCenterResizeScale,
+ resolveCenterResizeSize,
+ resolveRotatedResizeCursor,
+} from "./domEditResizeLocal";
+
+const DEG = Math.PI / 180;
+
+describe("resolveCenterResizeScale — radial distance from the center", () => {
+ it("scale is the ratio of pointer-to-center distances", () => {
+ // start 100px from center, now 150px from center → 1.5x.
+ expect(
+ resolveCenterResizeScale({
+ centerStart: { x: 100, y: 100 },
+ pointerStart: { x: 200, y: 100 },
+ pointer: { x: 250, y: 100 },
+ }),
+ ).toBeCloseTo(1.5, 9);
+ });
+
+ it("shrinks as the pointer moves toward the center", () => {
+ expect(
+ resolveCenterResizeScale({
+ centerStart: { x: 0, y: 0 },
+ pointerStart: { x: 0, y: 200 },
+ pointer: { x: 0, y: 50 },
+ }),
+ ).toBeCloseTo(0.25, 9);
+ });
+
+ it("bails to 1 when the gesture starts at (or ~at) the center (degenerate)", () => {
+ expect(
+ resolveCenterResizeScale({
+ centerStart: { x: 100, y: 100 },
+ pointerStart: { x: 101, y: 100 },
+ pointer: { x: 400, y: 400 },
+ }),
+ ).toBe(1);
+ });
+});
+
+describe("resolveCenterResizeSize — rotation is a non-event (radial distance)", () => {
+ // The pure function takes no rotation argument: rotating the WHOLE gesture
+ // (center, pointer-down, pointer-now) about the center by any angle preserves
+ // every radial distance, so the returned size is identical at 0/37/90deg.
+ const base = { baseWidth: 240, baseHeight: 120 };
+ const centerStart = { x: 320, y: 180 };
+ // A pointer-down 100px right of center, dragged to 160px right of center (1.6x).
+ const p0 = { x: 100, y: 0 };
+ const p1 = { x: 160, y: 0 };
+ const rot = (v: { x: number; y: number }, t: number) => ({
+ x: centerStart.x + (Math.cos(t) * v.x - Math.sin(t) * v.y),
+ y: centerStart.y + (Math.sin(t) * v.x + Math.cos(t) * v.y),
+ });
+
+ for (const deg of [0, 37, 90]) {
+ it(`@${deg}deg: proportional 1.6x scale, same result as unrotated`, () => {
+ const t = deg * DEG;
+ const out = resolveCenterResizeSize({
+ ...base,
+ centerStart,
+ pointerStart: rot(p0, t),
+ pointer: rot(p1, t),
+ });
+ expect(out.width).toBeCloseTo(240 * 1.6, 6);
+ expect(out.height).toBeCloseTo(120 * 1.6, 6);
+ expect(out.width / out.height).toBeCloseTo(2, 9);
+ });
+ }
+
+ it("shrink toward center keeps the aspect ratio", () => {
+ const out = resolveCenterResizeSize({
+ baseWidth: 300,
+ baseHeight: 180,
+ centerStart: { x: 0, y: 0 },
+ pointerStart: { x: 0, y: 200 },
+ pointer: { x: 0, y: 120 },
+ });
+ expect(out.width).toBeCloseTo(300 * 0.6, 6);
+ expect(out.height).toBeCloseTo(180 * 0.6, 6);
+ expect(out.width / out.height).toBeCloseTo(300 / 180, 9);
+ });
+
+ it("clamps at the local minimum, never mirroring through zero (drag past center)", () => {
+ // Pointer dragged to the exact center → raw scale 0; the smaller edge is
+ // clamped to MIN_RESIZE_LOCAL_PX and the aspect ratio holds at the clamp.
+ const out = resolveCenterResizeSize({
+ baseWidth: 200,
+ baseHeight: 100,
+ centerStart: { x: 100, y: 100 },
+ pointerStart: { x: 200, y: 100 },
+ pointer: { x: 100, y: 100 },
+ });
+ expect(out.width).toBeGreaterThan(0);
+ expect(out.height).toBeGreaterThan(0);
+ expect(Math.min(out.width, out.height)).toBeCloseTo(1, 9);
+ expect(out.width / out.height).toBeCloseTo(2, 9);
+ });
+
+ it("degenerate start-at-center returns the base size unchanged (scale 1)", () => {
+ const out = resolveCenterResizeSize({
+ baseWidth: 200,
+ baseHeight: 100,
+ centerStart: { x: 100, y: 100 },
+ pointerStart: { x: 100, y: 100 },
+ pointer: { x: 400, y: 400 },
+ });
+ expect(out).toEqual({ width: 200, height: 100 });
+ });
+});
+
+describe("resolveRotatedResizeCursor", () => {
+ it("returns the static diagonal cursors at rotation 0", () => {
+ expect(resolveRotatedResizeCursor("nw", 0)).toBe("nwse-resize");
+ expect(resolveRotatedResizeCursor("se", 0)).toBe("nwse-resize");
+ expect(resolveRotatedResizeCursor("ne", 0)).toBe("nesw-resize");
+ expect(resolveRotatedResizeCursor("sw", 0)).toBe("nesw-resize");
+ });
+
+ it("rotates the cursor with the element (90deg swaps the diagonals)", () => {
+ // NW base 315° + 90° = 45° → nesw-resize
+ expect(resolveRotatedResizeCursor("nw", 90)).toBe("nesw-resize");
+ // NW base 315° + 45° = 360°→0° → ns-resize
+ expect(resolveRotatedResizeCursor("nw", 45)).toBe("ns-resize");
+ });
+
+ it("wraps negative rotations", () => {
+ expect(resolveRotatedResizeCursor("se", -90)).toBe("nesw-resize");
+ });
+});
diff --git a/packages/studio/src/components/editor/domEditResizeLocal.ts b/packages/studio/src/components/editor/domEditResizeLocal.ts
new file mode 100644
index 0000000000..cd791ee0cd
--- /dev/null
+++ b/packages/studio/src/components/editor/domEditResizeLocal.ts
@@ -0,0 +1,125 @@
+/**
+ * Center-anchored corner-resize math (the CapCut model): the element scales
+ * proportionally about its CENTER, the center stays planted, and all four corners
+ * behave identically.
+ *
+ * The scale factor is the RADIAL distance from the element's center: how far the
+ * pointer is from the center now, divided by how far it was at gesture start. This
+ * is inherently proportional, continuous everywhere, and rotation-invariant — a
+ * distance is a distance regardless of the element's angle, so there is no per-axis
+ * projection and no dominant-axis branch to jump across. Which corner was grabbed
+ * is irrelevant to the size (it only picks the resize cursor).
+ *
+ * All math here is pure and unit-tested; the live wiring (measuring the element's
+ * rendered center, feeding the center-pin translate through the manual-offset
+ * channel) lives in useDomEditOverlayGestures.ts.
+ */
+import type { ResizeHandle } from "./domEditOverlayGestures";
+
+/** Minimum element edge in LOCAL px — mirrors the old MIN_RESIZE_EDGE_PX clamp
+ * (no flip-through-zero: clamp, never mirror). */
+const MIN_RESIZE_LOCAL_PX = 1;
+
+/**
+ * Below this pointer-to-center distance (overlay px) the gesture started at (or
+ * effectively at) the center, so the ratio is degenerate (division by ~0). Bail to
+ * scale 1 rather than blow up.
+ */
+const DEGENERATE_START_DIST_PX = 3;
+
+/**
+ * The proportional scale factor for a center-anchored resize: the ratio of the
+ * pointer's radial distance from the element center now to its distance at gesture
+ * start. Rotation-invariant (a radial distance ignores the element's angle) and
+ * continuous. Never negative — dragging through the center just shrinks toward the
+ * clamp; the caller clamps the resulting size, this returns the raw ratio (guarded
+ * against a degenerate start-at-center gesture, which returns 1).
+ */
+export function resolveCenterResizeScale(input: {
+ pointer: { x: number; y: number };
+ pointerStart: { x: number; y: number };
+ centerStart: { x: number; y: number };
+}): number {
+ const startDist = Math.hypot(
+ input.pointerStart.x - input.centerStart.x,
+ input.pointerStart.y - input.centerStart.y,
+ );
+ if (!Number.isFinite(startDist) || startDist < DEGENERATE_START_DIST_PX) return 1;
+ const nowDist = Math.hypot(
+ input.pointer.x - input.centerStart.x,
+ input.pointer.y - input.centerStart.y,
+ );
+ return nowDist / startDist;
+}
+
+/**
+ * The element's new LOCAL size for a center-anchored corner resize: base size
+ * scaled by `resolveCenterResizeScale`, clamped so the smaller edge never drops
+ * below MIN_RESIZE_LOCAL_PX (clamp small, never mirror through zero). The scale is
+ * a dimensionless ratio, so the base local size and the screen-space pointer
+ * distances live in different frames without any display-scale conversion — the
+ * ratio cancels the scale.
+ */
+export function resolveCenterResizeSize(input: {
+ baseWidth: number;
+ baseHeight: number;
+ pointer: { x: number; y: number };
+ pointerStart: { x: number; y: number };
+ centerStart: { x: number; y: number };
+}): { width: number; height: number } {
+ const baseWidth = Math.max(input.baseWidth, MIN_RESIZE_LOCAL_PX);
+ const baseHeight = Math.max(input.baseHeight, MIN_RESIZE_LOCAL_PX);
+ const rawScale = resolveCenterResizeScale({
+ pointer: input.pointer,
+ pointerStart: input.pointerStart,
+ centerStart: input.centerStart,
+ });
+ const minScale = MIN_RESIZE_LOCAL_PX / Math.min(baseWidth, baseHeight);
+ const scale = Math.max(minScale, rawScale);
+ return { width: baseWidth * scale, height: baseHeight * scale };
+}
+
+/**
+ * The eight CSS resize cursors, rotated with the object. A corner's base pointing
+ * direction (the diagonal it lives on) plus the element rotation, bucketed into
+ * 45° slots. So a 90°-rotated NW corner reads as a NE-diagonal cursor, etc.
+ */
+const CURSORS_8 = [
+ "ns-resize", // 0° (up)
+ "nesw-resize", // 45°
+ "ew-resize", // 90° (right)
+ "nwse-resize", // 135°
+ "ns-resize", // 180° (down)
+ "nesw-resize", // 225°
+ "ew-resize", // 270° (left)
+ "nwse-resize", // 315°
+] as const;
+
+/** Base outward diagonal angle of each corner, in degrees, screen convention
+ * (0° = up, clockwise). NW points up-left = 315°, NE up-right = 45°, etc. */
+const CORNER_BASE_ANGLE_DEG: Record<ResizeHandle, number> = {
+ nw: 315,
+ ne: 45,
+ se: 135,
+ sw: 225,
+};
+
+/** Resize cursor for a corner handle on an element rotated by `rotationDeg`. */
+export function resolveRotatedResizeCursor(handle: ResizeHandle, rotationDeg: number): string {
+ const angle = CORNER_BASE_ANGLE_DEG[handle] + rotationDeg;
+ const normalized = ((angle % 360) + 360) % 360;
+ const bucket = Math.round(normalized / 45) % 8;
+ return CURSORS_8[bucket]!;
+}
+
+/** Per-frame anchored-resize center accumulator: ADD the residual center correction
+ * (fixedStart − fixedNow) onto the previous anchor so the pin CONVERGES instead of
+ * oscillating (fa4f39168). Pure; exported for the release-shift characterization tests. */
+export function computeNextResizeAnchor(
+ prev: { dx: number; dy: number } | undefined,
+ fixedStart: { x: number; y: number },
+ fixedNow: { x: number; y: number },
+): { dx: number; dy: number } {
+ const base = prev ?? { dx: 0, dy: 0 };
+ return { dx: base.dx + (fixedStart.x - fixedNow.x), dy: base.dy + (fixedStart.y - fixedNow.y) };
+}
diff --git a/packages/studio/src/components/editor/domEditingDom.ts b/packages/studio/src/components/editor/domEditingDom.ts
index b1f341ca70..e01eb476bf 100644
--- a/packages/studio/src/components/editor/domEditingDom.ts
+++ b/packages/studio/src/components/editor/domEditingDom.ts
@@ -104,7 +104,7 @@ export function findClosestByAttribute(
// mounted root (it keeps `data-composition-id` but drops `data-composition-src`/
// `-file`), so a subcomp element's DOM ancestors no longer say which file it came
// from. This project-global map (composition-id → source file, built once from
-// index.html's clips — see NLELayout) recovers it. The studio loads one project at a
+// index.html's clips — see NLEContext/EditorShell) recovers it. The studio loads one project at a
// time, so module scope is the right lifetime; it's empty until set, in which case
// resolution falls back to the historical attribute-only behavior.
let compositionSourceMap: Map<string, string> = new Map();
diff --git a/packages/studio/src/components/editor/manualEditsDomPatches.test.ts b/packages/studio/src/components/editor/manualEditsDomPatches.test.ts
index 3b5bf56132..5ef3a539fc 100644
--- a/packages/studio/src/components/editor/manualEditsDomPatches.test.ts
+++ b/packages/studio/src/components/editor/manualEditsDomPatches.test.ts
@@ -49,6 +49,7 @@ import {
buildMotionPatches,
buildClearMotionPatches,
} from "./manualEditsDomPatches";
+import { applyStudioBoxSize, applyStudioPathOffset } from "./manualEditsDom";
/* ── helpers ── */
@@ -267,6 +268,52 @@ describe("buildBoxSizePatches / buildClearBoxSizePatches", () => {
});
});
+/* ── Combined box-size + path-offset (anchored-corner resize) ──────────────── */
+
+describe("anchored-corner combined patch: [...buildBoxSizePatches, ...buildPathOffsetPatches]", () => {
+ // NW/NE/SW resize commits size AND anchor offset in ONE persist. The two
+ // builders read the same already-mutated element and are concatenated; this
+ // is only safe if their {type,property} keys are disjoint (no builder
+ // overwrites the other's op when the source patcher applies them in order).
+ it("concatenation of both builders emits disjoint {type,property} keys (no collision)", () => {
+ const e = div();
+ applyStudioBoxSize(e, { width: 300, height: 200 });
+ applyStudioPathOffset(e, { x: 10, y: 20 });
+
+ const combined = [...buildBoxSizePatches(e), ...buildPathOffsetPatches(e)];
+ const keys = combined.map(opKey);
+ expect(new Set(keys).size, `duplicate {type,property} key in combined patch: ${keys}`).toBe(
+ keys.length,
+ );
+ });
+
+ it("combined patch carries BOTH markers so a soft-reload re-hydrates size and offset together", () => {
+ const e = div();
+ applyStudioBoxSize(e, { width: 300, height: 200 });
+ applyStudioPathOffset(e, { x: 10, y: 20 });
+
+ const combined = [...buildBoxSizePatches(e), ...buildPathOffsetPatches(e)];
+ const has = (property: string) =>
+ combined.some((op) => op.type === "attribute" && op.property === property);
+ expect(has(STUDIO_BOX_SIZE_ATTR)).toBe(true);
+ expect(has(STUDIO_PATH_OFFSET_ATTR)).toBe(true);
+ });
+
+ it("order is size-first: every box-size op precedes every path-offset op", () => {
+ const e = div();
+ applyStudioBoxSize(e, { width: 300, height: 200 });
+ applyStudioPathOffset(e, { x: 10, y: 20 });
+
+ const boxKeys = new Set(buildBoxSizePatches(e).map(opKey));
+ const combined = [...buildBoxSizePatches(e), ...buildPathOffsetPatches(e)];
+ const lastBoxIdx = combined.reduce((acc, op, i) => (boxKeys.has(opKey(op)) ? i : acc), -1);
+ const firstOffsetIdx = combined.findIndex(
+ (op) => op.type === "attribute" && op.property === STUDIO_PATH_OFFSET_ATTR,
+ );
+ expect(firstOffsetIdx).toBeGreaterThan(lastBoxIdx);
+ });
+});
+
/* ── Rotation ────────────────────────────────────────────────────────────── */
describe("buildRotationPatches / buildClearRotationPatches", () => {
diff --git a/packages/studio/src/components/editor/manualOffsetDrag.ts b/packages/studio/src/components/editor/manualOffsetDrag.ts
index 6151a09790..a808c792fb 100644
--- a/packages/studio/src/components/editor/manualOffsetDrag.ts
+++ b/packages/studio/src/components/editor/manualOffsetDrag.ts
@@ -441,22 +441,26 @@ export function applyManualOffsetDragDraft(
return offset;
}
-export function applyManualOffsetDragCommit(
- member: ManualOffsetDragMember,
- dx: number,
- dy: number,
-): { x: number; y: number } {
- // Re-stamp the STABLE gesture-start base/offset before the source commit reads
- // them. A mid-drag re-render can wipe these attrs; the commit converts the drop
- // offset → gsap x/y via computeDraggedGsapPosition, which without the base falls
- // back to the live (already-dragged) transform and re-adds the delta — so the
- // element flies off-screen the instant you drop it. The member holds the true
- // gesture-start values in JS, immune to the re-render.
+/**
+ * Re-stamp the STABLE gesture-start base/offset before the source commit reads
+ * them. A mid-gesture re-render can wipe these attrs; the commit converts the
+ * drop offset → gsap x/y via computeDraggedGsapPosition, which without the base
+ * falls back to the live (already-dragged) transform and re-adds the delta — so
+ * the element flies off-screen the instant you drop it. The member holds the
+ * true gesture-start values in JS, immune to the re-render.
+ */
+function restampManualOffsetDragGestureBase(member: ManualOffsetDragMember): void {
member.element.setAttribute("data-hf-drag-gsap-base-x", String(member.baseGsap.x));
member.element.setAttribute("data-hf-drag-gsap-base-y", String(member.baseGsap.y));
member.element.setAttribute("data-hf-drag-initial-offset-x", String(member.initialOffset.x));
member.element.setAttribute("data-hf-drag-initial-offset-y", String(member.initialOffset.y));
- const offset = resolveManualOffsetDragMemberOffset(member, dx, dy);
+}
+
+function applyManualOffsetCommitValue(
+ member: ManualOffsetDragMember,
+ offset: { x: number; y: number },
+): { x: number; y: number } {
+ restampManualOffsetDragGestureBase(member);
// Optimistic visual through the GSAP channel (same as the live draft and the
// committed `tl.set`), so the element holds its dropped position until the
// source mutation soft-reloads — no transient CSS `--hf-studio-offset` write.
@@ -467,6 +471,45 @@ export function applyManualOffsetDragCommit(
return offset;
}
+export function applyManualOffsetDragCommit(
+ member: ManualOffsetDragMember,
+ dx: number,
+ dy: number,
+): { x: number; y: number } {
+ return applyManualOffsetCommitValue(member, resolveManualOffsetDragMemberOffset(member, dx, dy));
+}
+
+/**
+ * Arrow-key nudge, in OFFSET units (composition px), not screen px — "nudge
+ * 1px" means one composition pixel regardless of canvas zoom, so the delta
+ * adds to the gesture-start offset directly instead of going through the
+ * screen→offset matrix. Draft/commit land in the same GSAP channel (with the
+ * same CSS fallback) as the drag equivalents above.
+ */
+export function applyManualOffsetNudgeDraft(
+ member: ManualOffsetDragMember,
+ delta: { x: number; y: number },
+): { x: number; y: number } {
+ const offset = {
+ x: member.initialOffset.x + delta.x,
+ y: member.initialOffset.y + delta.y,
+ };
+ if (!applyOffsetDragDraftViaGsap(member.element, offset, member.baseGsap)) {
+ applyStudioPathOffsetDraft(member.element, offset);
+ }
+ return offset;
+}
+
+export function applyManualOffsetNudgeCommit(
+ member: ManualOffsetDragMember,
+ delta: { x: number; y: number },
+): { x: number; y: number } {
+ return applyManualOffsetCommitValue(member, {
+ x: member.initialOffset.x + delta.x,
+ y: member.initialOffset.y + delta.y,
+ });
+}
+
function restoreManualOffsetDragMember(member: ManualOffsetDragMember): void {
restoreStudioPathOffset(member.element, member.initialPathOffset);
endStudioManualEditGesture(member.element, member.gestureToken);
diff --git a/packages/studio/src/components/editor/offCanvasIndicatorGeometry.ts b/packages/studio/src/components/editor/offCanvasIndicatorGeometry.ts
index 61345e4c74..8b61a3b7f9 100644
--- a/packages/studio/src/components/editor/offCanvasIndicatorGeometry.ts
+++ b/packages/studio/src/components/editor/offCanvasIndicatorGeometry.ts
@@ -1,7 +1,7 @@
import type React from "react";
import type { OffCanvasRect } from "./OffCanvasIndicators";
import { hugRectForElement } from "./domEditOverlayCrop";
-import { groupAwareOverlayRect } from "./domEditOverlayGeometry";
+import { orientedGroupAwareOverlayRect } from "./domEditOverlayGeometry";
import { isElementComputedVisible } from "./domEditingElement";
import { collectDomEditLayerItems } from "./domEditingLayers";
@@ -13,11 +13,30 @@ function offCanvasSignature(rects: OffCanvasRect[]): string {
return rects
.map(
(rect) =>
- `${rect.key}:${rounded(rect.left)},${rounded(rect.top)},${rounded(rect.width)},${rounded(rect.height)}`,
+ `${rect.key}:${rounded(rect.left)},${rounded(rect.top)},${rounded(rect.width)},${rounded(rect.height)},${rounded(rect.angle ?? 0)}`,
)
.join("|");
}
+function extendsOutside(
+ rect: Omit<OffCanvasRect, "key">,
+ comp: { left: number; top: number; width: number; height: number },
+): boolean {
+ const radians = ((rect.angle ?? 0) * Math.PI) / 180;
+ const halfWidth =
+ (Math.abs(Math.cos(radians)) * rect.width + Math.abs(Math.sin(radians)) * rect.height) / 2;
+ const halfHeight =
+ (Math.abs(Math.sin(radians)) * rect.width + Math.abs(Math.cos(radians)) * rect.height) / 2;
+ const centerX = rect.left + rect.width / 2;
+ const centerY = rect.top + rect.height / 2;
+ return (
+ centerX - halfWidth < comp.left ||
+ centerX + halfWidth > comp.left + comp.width ||
+ centerY - halfHeight < comp.top ||
+ centerY + halfHeight > comp.top + comp.height
+ );
+}
+
// fallow-ignore-next-line complexity
export function recomputeOffCanvasIndicators(
iframe: HTMLIFrameElement,
@@ -50,18 +69,20 @@ export function recomputeOffCanvasIndicators(
// whose members sit inside the canvas isn't flagged off-canvas by a stale
// wrapper box. Crop-hug the result so an inset crop that keeps the visible
// part on-canvas doesn't flag the element either.
- const base = groupAwareOverlayRect(overlay, iframe, item.element);
+ const base = orientedGroupAwareOverlayRect(overlay, iframe, item.element);
const r = base ? { ...base, ...hugRectForElement(base, item.element) } : null;
if (!r) continue;
// Any edge crossing the composition border → gray-zone indicator (the
// in-canvas portion is clipped away below, so only the sliver shows).
- const extendsOutsideComp =
- r.left < comp.left ||
- r.left + r.width > comp.left + comp.width ||
- r.top < comp.top ||
- r.top + r.height > comp.top + comp.height;
- if (extendsOutsideComp) {
- rects.push({ key: item.key, left: r.left, top: r.top, width: r.width, height: r.height });
+ if (extendsOutside(r, comp)) {
+ rects.push({
+ key: item.key,
+ left: r.left,
+ top: r.top,
+ width: r.width,
+ height: r.height,
+ angle: r.angle,
+ });
elMap.set(item.key, item.element);
}
}
diff --git a/packages/studio/src/components/editor/offCanvasIndicatorRefresh.test.tsx b/packages/studio/src/components/editor/offCanvasIndicatorRefresh.test.tsx
index 3948989539..3d2321e748 100644
--- a/packages/studio/src/components/editor/offCanvasIndicatorRefresh.test.tsx
+++ b/packages/studio/src/components/editor/offCanvasIndicatorRefresh.test.tsx
@@ -2,11 +2,35 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
-import { describe, expect, it } from "vitest";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { DomEditOverlay } from "./DomEditOverlay";
Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true);
+// happy-dom (20.x) holds each MutationObserver's delivery callback ONLY via a
+// WeakRef (MutationObserverListener: `callback: new WeakRef(...)` — the arrow
+// has no strong referent). If V8 runs a GC between observe() and a mutation,
+// deref() returns undefined and mutation delivery silently stops — the
+// indicator-refresh loop never sees its dirty flag and these tests flake under
+// full-suite memory pressure (passing in isolation). Pin WeakRef to a strong
+// ref for this file so the real observer path stays deterministic.
+const RealWeakRef = globalThis.WeakRef;
+class StrongRef<T extends WeakKey> {
+ #value: T;
+ constructor(value: T) {
+ this.#value = value;
+ }
+ deref(): T {
+ return this.#value;
+ }
+}
+beforeAll(() => {
+ (globalThis as { WeakRef: unknown }).WeakRef = StrongRef;
+});
+afterAll(() => {
+ globalThis.WeakRef = RealWeakRef;
+});
+
const INDICATOR = '[aria-label="Select off-canvas element index.html:headline:0"]';
function domRect(left: number, top: number, width: number, height: number): DOMRect {
diff --git a/packages/studio/src/components/editor/resizeDraft.ts b/packages/studio/src/components/editor/resizeDraft.ts
new file mode 100644
index 0000000000..9bff6e76d5
--- /dev/null
+++ b/packages/studio/src/components/editor/resizeDraft.ts
@@ -0,0 +1,108 @@
+import type { GestureState } from "./domEditOverlayGestures";
+import { resolveResizeCenterAnchorOffset } from "./domEditOverlayGestures";
+import type { OverlayRect } from "./domEditOverlayGeometry";
+import {
+ cornerEdgeLength,
+ elementCornerOverlayPoints,
+ overlayCornersCentroid,
+} from "./domEditOverlayGeometry";
+import { computeNextResizeAnchor } from "./domEditResizeLocal";
+import { applyManualOffsetDragDraft } from "./manualOffsetDrag";
+
+type Corners = ReturnType<typeof elementCornerOverlayPoints>;
+
+/**
+ * The residual center-pin offset for this frame. With measurable corners and a
+ * fixed-center start, accumulate `fixedStart - centerNow` onto the previous
+ * anchor so it CONVERGES rather than oscillating: `applyManualOffsetDragDraft`
+ * treats its argument as the absolute offset, and `centerNow` (measured on the
+ * live element) already carries the previous frame's offset, so the difference
+ * is only the residual correction. Using it absolutely would drop the offset
+ * every other frame and un-pin the center (fa4f39168). Memberless/unmeasurable
+ * geometry falls back to the AABB half-delta.
+ */
+function resolveResizeAnchor(
+ g: GestureState,
+ corners: Corners | null,
+ measureOrientedRect: () => OverlayRect | null,
+): { dx: number; dy: number } {
+ const fixedStart = g.resizeFixedCenterStart;
+ if (corners && fixedStart) {
+ return computeNextResizeAnchor(g.lastResizeAnchor, fixedStart, overlayCornersCentroid(corners));
+ }
+ const fallbackRect = measureOrientedRect();
+ return resolveResizeCenterAnchorOffset({
+ originWidth: g.originWidth,
+ originHeight: g.originHeight,
+ overlayWidth: fallbackRect ? fallbackRect.width : g.originWidth,
+ overlayHeight: fallbackRect ? fallbackRect.height : g.originHeight,
+ });
+}
+
+/**
+ * Center-pinned draft rect: translate the element through the manual-offset
+ * channel to keep its gesture-start center planted (rotation-safe for any
+ * transform-origin), then hug its true rendered bounds. Mutates
+ * `g.lastResizeAnchor` and applies the offset draft as a side effect.
+ */
+function resolveAnchoredResizeDraft(
+ g: GestureState,
+ member: NonNullable<GestureState["pathOffsetMember"]>,
+ element: HTMLElement,
+ overlayEl: HTMLDivElement | null,
+ iframe: HTMLIFrameElement | null,
+ measureOrientedRect: () => OverlayRect | null,
+): OverlayRect {
+ // Measure real corners ONCE — reused for the anchor and the fallback size.
+ const corners =
+ overlayEl && iframe ? elementCornerOverlayPoints(overlayEl, iframe, element) : null;
+ const anchor = resolveResizeAnchor(g, corners, measureOrientedRect);
+ g.lastResizeAnchor = anchor;
+ applyManualOffsetDragDraft(member, anchor.dx, anchor.dy);
+ // Re-measure AFTER the anchor translate so it hugs the element every frame.
+ return (
+ measureOrientedRect() ?? {
+ left: g.originLeft + anchor.dx,
+ top: g.originTop + anchor.dy,
+ width: corners ? cornerEdgeLength(corners.nw, corners.ne) : g.originWidth,
+ height: corners ? cornerEdgeLength(corners.nw, corners.sw) : g.originHeight,
+ editScaleX: g.editScaleX,
+ editScaleY: g.editScaleY,
+ angle: g.actualRotation,
+ }
+ );
+}
+
+/** The overlay rect to paint for the current resize pointer-move frame. */
+export function resolveResizeDraftRect(
+ g: GestureState,
+ element: HTMLElement,
+ overlayEl: HTMLDivElement | null,
+ iframe: HTMLIFrameElement | null,
+ measureOrientedRect: () => OverlayRect | null,
+): OverlayRect {
+ if (g.pathOffsetMember) {
+ return resolveAnchoredResizeDraft(
+ g,
+ g.pathOffsetMember,
+ element,
+ overlayEl,
+ iframe,
+ measureOrientedRect,
+ );
+ }
+ // Re-measure the element's oriented box AFTER the size write. The size draft
+ // rounds/clamps and (with a centered transform-origin + GSAP scale) the real
+ // rendered size diverges from the CSS size, so measure rather than trust math.
+ return (
+ measureOrientedRect() ?? {
+ left: g.originLeft,
+ top: g.originTop,
+ width: g.originWidth,
+ height: g.originHeight,
+ editScaleX: g.editScaleX,
+ editScaleY: g.editScaleY,
+ angle: g.actualRotation,
+ }
+ );
+}
diff --git a/packages/studio/src/components/editor/snapEngine.test.ts b/packages/studio/src/components/editor/snapEngine.test.ts
index 1826aeab33..1d74b09e4b 100644
--- a/packages/studio/src/components/editor/snapEngine.test.ts
+++ b/packages/studio/src/components/editor/snapEngine.test.ts
@@ -5,8 +5,8 @@ import {
buildCompositionSnapTarget,
buildGridSnapEdges,
resolveSnapAdjustment,
- resolveResizeSnapAdjustment,
resolveEquidistanceGuides,
+ resolveGuideLineRect,
SNAP_THRESHOLD_PX,
type SnapTarget,
} from "./snapEngine";
@@ -385,88 +385,22 @@ describe("resolveSnapAdjustment", () => {
});
// ---------------------------------------------------------------------------
-// resolveResizeSnapAdjustment
+// resolveGuideLineRect
// ---------------------------------------------------------------------------
-describe("resolveResizeSnapAdjustment", () => {
- test("only right edge snaps on X", () => {
- // Moving rect at (100, 100) size 50x50, right=150.
- // Target left at 200. Propose dx=47 => proposed right=197. Dist to 200=3.
- const t = target("a", 200, 100, 100, 100);
- const result = resolveResizeSnapAdjustment({
- movingRect: rect(100, 100, 50, 50),
- proposedDx: 47,
- proposedDy: 0,
- targets: [t],
- threshold: SNAP_THRESHOLD_PX,
- disabled: false,
- });
- expect(result.dx).toBe(50); // right edge snaps to 200
- });
+describe("resolveGuideLineRect", () => {
+ const composition = rect(120, 80, 640, 360); // letterboxed inside the overlay
- test("only bottom edge snaps on Y", () => {
- // Moving rect at (100, 100) size 50x50, bottom=150.
- // Target top at 200. Propose dy=47 => proposed bottom=197. Dist to 200=3.
- const t = target("a", 100, 200, 100, 100);
- const result = resolveResizeSnapAdjustment({
- movingRect: rect(100, 100, 50, 50),
- proposedDx: 0,
- proposedDy: 47,
- targets: [t],
- threshold: SNAP_THRESHOLD_PX,
- disabled: false,
- });
- expect(result.dy).toBe(50); // bottom edge snaps to 200
- });
-
- test("left edge does NOT snap during resize", () => {
- // Target right at 150. Moving rect left=100. If drag were active,
- // left would snap. But during resize, only right edge snaps.
- // Moving rect at (100, 100) size 200x200, right=300.
- // Target right=150. Proposed dx=-153 => proposed right=147. Dist to 150=3.
- // This SHOULD snap right to 150 (dx = -150). But left stays at 100.
- const t = target("a", 50, 100, 100, 100); // right=150
- const result = resolveResizeSnapAdjustment({
- movingRect: rect(100, 100, 200, 200),
- proposedDx: -153,
- proposedDy: 0,
- targets: [t],
- threshold: SNAP_THRESHOLD_PX,
- disabled: false,
- });
- // Right edge: 300 + (-153) = 147 => snaps to 150, adjustment = +3, dx = -150
- expect(result.dx).toBe(-150);
- });
-
- test("disabled=true returns passthrough for resize", () => {
- const t = target("a", 200, 200, 100, 100);
- const result = resolveResizeSnapAdjustment({
- movingRect: rect(100, 100, 50, 50),
- proposedDx: 47,
- proposedDy: 47,
- targets: [t],
- threshold: SNAP_THRESHOLD_PX,
- disabled: true,
- });
- expect(result.dx).toBe(47);
- expect(result.dy).toBe(47);
- expect(result.guides).toHaveLength(0);
+ test("vertical guide (axis x) spans the composition's height at the snap x", () => {
+ expect(resolveGuideLineRect({ axis: "x", position: 440, from: 0, to: 0 }, composition)).toEqual(
+ { left: 440, top: 80, width: 1, height: 360 },
+ );
});
- test("resize produces guide lines", () => {
- const t = target("a", 200, 100, 100, 100);
- const result = resolveResizeSnapAdjustment({
- movingRect: rect(100, 100, 50, 50),
- proposedDx: 47,
- proposedDy: 0,
- targets: [t],
- threshold: SNAP_THRESHOLD_PX,
- disabled: false,
- });
- expect(result.guides.length).toBeGreaterThanOrEqual(1);
- const xGuide = result.guides.find((g) => g.axis === "x");
- expect(xGuide).toBeDefined();
- expect(xGuide!.position).toBe(200);
+ test("horizontal guide (axis y) spans the composition's width at the snap y", () => {
+ expect(resolveGuideLineRect({ axis: "y", position: 260, from: 0, to: 0 }, composition)).toEqual(
+ { left: 120, top: 260, width: 640, height: 1 },
+ );
});
});
diff --git a/packages/studio/src/components/editor/snapEngine.ts b/packages/studio/src/components/editor/snapEngine.ts
index 9cb4094975..6a64a22a29 100644
--- a/packages/studio/src/components/editor/snapEngine.ts
+++ b/packages/studio/src/components/editor/snapEngine.ts
@@ -410,62 +410,22 @@ export function resolveSnapAdjustment(input: {
}
// ---------------------------------------------------------------------------
-// resolveResizeSnapAdjustment — resize variant (only right/bottom snap)
+// resolveGuideLineRect — screen rect for rendering a snap guide line
// ---------------------------------------------------------------------------
-// fallow-ignore-next-line complexity
-export function resolveResizeSnapAdjustment(input: {
- movingRect: Rect;
- proposedDx: number;
- proposedDy: number;
- targets: SnapTarget[];
- gridEdges?: { x: SnapEdge[]; y: SnapEdge[] };
- threshold: number;
- disabled: boolean;
-}): SnapResult {
- if (input.disabled || input.threshold <= 0) {
- return DISABLED_RESULT(input.proposedDx, input.proposedDy);
+/**
+ * Full-length guide line spanning the composition: a vertical line (axis "x")
+ * runs the composition's height at the snapped x position; a horizontal line
+ * (axis "y") runs the composition's width. `composition` is the composition
+ * rect in overlay space — guide positions are already overlay-space, so the
+ * line must be offset by the composition's left/top (the canvas is usually
+ * letterboxed inside the overlay).
+ */
+export function resolveGuideLineRect(guide: SnapGuide, composition: Rect): Rect {
+ if (guide.axis === "x") {
+ return { left: guide.position, top: composition.top, width: 1, height: composition.height };
}
-
- const mr = input.movingRect;
- const proposedRight = rectRight(mr) + input.proposedDx;
- const proposedBottom = rectBottom(mr) + input.proposedDy;
-
- const xCandidates = collectCandidates(
- [proposedRight],
- input.targets,
- (t) => [t.left, t.centerX, t.right],
- input.gridEdges?.x,
- input.threshold,
- );
- const yCandidates = collectCandidates(
- [proposedBottom],
- input.targets,
- (t) => [t.top, t.centerY, t.bottom],
- input.gridEdges?.y,
- input.threshold,
- );
-
- const bestX = pickBest(xCandidates);
- const bestY = pickBest(yCandidates);
- const adjustedDx = input.proposedDx + (bestX?.adjustment ?? 0);
- const adjustedDy = input.proposedDy + (bestY?.adjustment ?? 0);
-
- const adjustedRect: Rect = {
- left: mr.left,
- top: mr.top,
- width: mr.width + adjustedDx,
- height: mr.height + adjustedDy,
- };
-
- const targetMap = new Map(input.targets.map((t) => [t.id, t]));
-
- return {
- dx: adjustedDx,
- dy: adjustedDy,
- guides: buildGuidesFromMatches(bestX, bestY, adjustedRect, targetMap),
- spacingGuides: [], // computed separately via resolveEquidistanceGuides
- };
+ return { left: composition.left, top: guide.position, width: composition.width, height: 1 };
}
// ---------------------------------------------------------------------------
diff --git a/packages/studio/src/components/editor/useDomEditNudge.test.tsx b/packages/studio/src/components/editor/useDomEditNudge.test.tsx
new file mode 100644
index 0000000000..9d7265f7a3
--- /dev/null
+++ b/packages/studio/src/components/editor/useDomEditNudge.test.tsx
@@ -0,0 +1,228 @@
+// @vitest-environment happy-dom
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { installReactActEnvironment, makeSelection } from "../../hooks/domSelectionTestHarness";
+import { useDomEditNudge, type UseDomEditNudgeParams } from "./useDomEditNudge";
+import { CANVAS_NUDGE_COMMIT_DEBOUNCE_MS, CANVAS_NUDGE_STEP_PX } from "./domEditNudge";
+import { __resetForTests } from "../../utils/canvasNudgeGate";
+import type { DomEditSelection } from "./domEditing";
+import type { OverlayRect } from "./domEditOverlayGeometry";
+
+installReactActEnvironment();
+
+function makeRef<T>(current: T): { current: T } {
+ return { current };
+}
+
+const REST_RECT: OverlayRect = {
+ left: 0,
+ top: 0,
+ width: 100,
+ height: 50,
+ editScaleX: 1,
+ editScaleY: 1,
+};
+
+// Stable across renders on purpose: the test targets the `selection` identity
+// key specifically, so `groupSelections` must not itself be a source of churn.
+const EMPTY_GROUP_SELECTIONS: DomEditSelection[] = [];
+
+function Harness({
+ selection,
+ onPathOffsetCommit,
+}: {
+ selection: DomEditSelection | null;
+ onPathOffsetCommit: UseDomEditNudgeParams["onPathOffsetCommitRef"]["current"];
+}) {
+ useDomEditNudge({
+ selection,
+ groupSelections: EMPTY_GROUP_SELECTIONS,
+ allowCanvasMovement: true,
+ selectionRef: makeRef(selection),
+ overlayRectRef: makeRef(REST_RECT),
+ groupOverlayItemsRef: makeRef([]),
+ gestureRef: makeRef(null),
+ groupGestureRef: makeRef(null),
+ blockedMoveRef: makeRef(null),
+ onManualDragStartRef: makeRef(() => {}),
+ onPathOffsetCommitRef: makeRef(onPathOffsetCommit),
+ onGroupPathOffsetCommitRef: makeRef(async () => {}),
+ });
+ return null;
+}
+
+function dispatchArrowRight(): void {
+ window.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true }),
+ );
+}
+
+describe("useDomEditNudge — selection cleanup keyed on stable identity", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ __resetForTests();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("keeps a nudge burst alive when the parent hands down a new selection object for the same element", () => {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+
+ const element = document.createElement("div");
+ element.id = "dot-a";
+ document.body.append(element);
+
+ const commit = vi.fn();
+ const firstSelection = makeSelection("Dot", element);
+
+ act(() => {
+ root.render(
+ React.createElement(Harness, { selection: firstSelection, onPathOffsetCommit: commit }),
+ );
+ });
+
+ act(() => {
+ dispatchArrowRight();
+ });
+ expect(commit).not.toHaveBeenCalled();
+
+ // Re-render with a BRAND NEW selection object describing the SAME element
+ // (same id) — exactly what an un-memoized parent does on every render.
+ // Before the fix, the cleanup effect was keyed on this object's identity
+ // and would flush the burst right here, one arrow-press early.
+ const secondSelection = makeSelection("Dot", element);
+ act(() => {
+ root.render(
+ React.createElement(Harness, { selection: secondSelection, onPathOffsetCommit: commit }),
+ );
+ });
+ expect(commit).not.toHaveBeenCalled();
+
+ act(() => {
+ dispatchArrowRight();
+ });
+ expect(commit).not.toHaveBeenCalled();
+
+ act(() => {
+ vi.advanceTimersByTime(CANVAS_NUDGE_COMMIT_DEBOUNCE_MS + 10);
+ });
+
+ // One combined commit for both presses, not two separate (premature) ones.
+ expect(commit).toHaveBeenCalledTimes(1);
+ const [, next] = commit.mock.calls[0] as [DomEditSelection, { x: number; y: number }];
+ expect(next.x).toBeCloseTo(2 * CANVAS_NUDGE_STEP_PX);
+ expect(next.y).toBeCloseTo(0);
+
+ act(() => root.unmount());
+ host.remove();
+ element.remove();
+ });
+
+ it("still flushes the burst when the selection actually changes to a different element", () => {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+
+ const elementA = document.createElement("div");
+ elementA.id = "dot-a";
+ document.body.append(elementA);
+ const elementB = document.createElement("div");
+ elementB.id = "dot-b";
+ document.body.append(elementB);
+
+ const commit = vi.fn();
+ const selectionA = makeSelection("Dot A", elementA);
+ const selectionB = makeSelection("Dot B", elementB);
+
+ act(() => {
+ root.render(
+ React.createElement(Harness, { selection: selectionA, onPathOffsetCommit: commit }),
+ );
+ });
+
+ act(() => {
+ dispatchArrowRight();
+ });
+ expect(commit).not.toHaveBeenCalled();
+
+ // A genuine selection change (different id) must still flush immediately —
+ // only same-identity re-renders should be ignored.
+ act(() => {
+ root.render(
+ React.createElement(Harness, { selection: selectionB, onPathOffsetCommit: commit }),
+ );
+ });
+ expect(commit).toHaveBeenCalledTimes(1);
+ const [committedSelection, next] = commit.mock.calls[0] as [
+ DomEditSelection,
+ { x: number; y: number },
+ ];
+ expect(committedSelection.element).toBe(elementA);
+ expect(next.x).toBeCloseTo(CANVAS_NUDGE_STEP_PX);
+
+ act(() => root.unmount());
+ host.remove();
+ elementA.remove();
+ elementB.remove();
+ });
+
+ it("flushes the burst when switching between two id-less siblings that share a selector", () => {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+
+ // Two id-less siblings with the SAME selector — distinguished only by
+ // selectorIndex. Under the old `id ?? selector ?? label` key they shared
+ // one identity, so selecting B mid-burst didn't flush A and the next arrow
+ // kept moving A. The key now folds in selectorIndex, so they're distinct.
+ const elementA = document.createElement("div");
+ document.body.append(elementA);
+ const elementB = document.createElement("div");
+ document.body.append(elementB);
+
+ const commit = vi.fn();
+ const base = (label: string, element: HTMLElement) => ({
+ ...makeSelection(label, element),
+ id: undefined,
+ selector: "div.row",
+ });
+ const selectionA: DomEditSelection = { ...base("Row", elementA), selectorIndex: 0 };
+ const selectionB: DomEditSelection = { ...base("Row", elementB), selectorIndex: 1 };
+
+ act(() => {
+ root.render(
+ React.createElement(Harness, { selection: selectionA, onPathOffsetCommit: commit }),
+ );
+ });
+
+ act(() => {
+ dispatchArrowRight();
+ });
+ expect(commit).not.toHaveBeenCalled();
+
+ act(() => {
+ root.render(
+ React.createElement(Harness, { selection: selectionB, onPathOffsetCommit: commit }),
+ );
+ });
+
+ // The sibling switch must flush A's pending burst exactly once, for A.
+ expect(commit).toHaveBeenCalledTimes(1);
+ const [committedSelection, next] = commit.mock.calls[0] as [
+ DomEditSelection,
+ { x: number; y: number },
+ ];
+ expect(committedSelection.element).toBe(elementA);
+ expect(next.x).toBeCloseTo(CANVAS_NUDGE_STEP_PX);
+
+ act(() => root.unmount());
+ host.remove();
+ elementA.remove();
+ elementB.remove();
+ });
+});
diff --git a/packages/studio/src/components/editor/useDomEditNudge.ts b/packages/studio/src/components/editor/useDomEditNudge.ts
new file mode 100644
index 0000000000..dc7e5993fc
--- /dev/null
+++ b/packages/studio/src/components/editor/useDomEditNudge.ts
@@ -0,0 +1,254 @@
+/**
+ * Canvas arrow-key nudge for DomEditOverlay: arrows move the selected
+ * element(s) 1 composition px, Shift = 10. Each keypress previews through the
+ * same GSAP/CSS channel as a drag draft, and the burst commits ONCE through
+ * the same onPathOffsetCommit / onGroupPathOffsetCommit path a drag drop uses
+ * — so a nudge burst is exactly a tiny drag: one source patch, one undo entry.
+ */
+import { useCallback, useEffect, useRef, type RefObject } from "react";
+import { useMountEffect } from "../../hooks/useMountEffect";
+import { isEditableTarget } from "../../utils/timelineDiscovery";
+import { acquireCanvasNudgeKeys } from "../../utils/canvasNudgeGate";
+import type { DomEditSelection } from "./domEditing";
+import {
+ type GroupOverlayItem,
+ type OverlayRect,
+ filterNestedDomEditGroupItems,
+} from "./domEditOverlayGeometry";
+import type {
+ BlockedMoveState,
+ DomEditGroupPathOffsetCommit,
+ GestureState,
+ GroupGestureState,
+} from "./domEditOverlayGestures";
+import {
+ applyManualOffsetNudgeCommit,
+ applyManualOffsetNudgeDraft,
+ createManualOffsetDragMember,
+ endManualOffsetDragMembers,
+ restoreManualOffsetDragMembers,
+ type ManualOffsetDragMember,
+} from "./manualOffsetDrag";
+import { isStudioManualEditGestureCurrent, restoreStudioPathOffset } from "./manualEdits";
+import {
+ CANVAS_NUDGE_COMMIT_DEBOUNCE_MS,
+ canCanvasNudgeTargets,
+ resolveCanvasNudgeDelta,
+} from "./domEditNudge";
+
+interface NudgeSession {
+ members: ManualOffsetDragMember[];
+ isGroup: boolean;
+ /** Accumulated delta of the burst, in composition px. */
+ accum: { x: number; y: number };
+ timer: ReturnType<typeof setTimeout> | null;
+}
+
+export interface UseDomEditNudgeParams {
+ selection: DomEditSelection | null;
+ groupSelections: DomEditSelection[];
+ allowCanvasMovement: boolean;
+ selectionRef: RefObject<DomEditSelection | null>;
+ overlayRectRef: RefObject<OverlayRect | null>;
+ groupOverlayItemsRef: RefObject<GroupOverlayItem[]>;
+ gestureRef: RefObject<GestureState | null>;
+ groupGestureRef: RefObject<GroupGestureState | null>;
+ blockedMoveRef: RefObject<BlockedMoveState | null>;
+ onManualDragStartRef: RefObject<(() => void) | undefined>;
+ onPathOffsetCommitRef: RefObject<
+ (
+ s: DomEditSelection,
+ n: { x: number; y: number },
+ m?: { altKey?: boolean },
+ ) => Promise<void> | void
+ >;
+ onGroupPathOffsetCommitRef: RefObject<
+ (updates: DomEditGroupPathOffsetCommit[]) => Promise<void> | void
+ >;
+}
+
+type NudgeTarget = {
+ key: string;
+ selection: DomEditSelection;
+ element: HTMLElement;
+ rect: OverlayRect;
+};
+
+/**
+ * A selection's stable identity, not its object reference. A parent that
+ * doesn't memoize the selection it passes down hands us a new object every
+ * render for the SAME element — keying an effect on the object itself would
+ * then re-fire on every render instead of on an actual selection change.
+ *
+ * All discriminators are folded in (id / hfId / selector / selectorIndex /
+ * label), not just the first present one: two id-less siblings can share a
+ * selector, so `id ?? selector ?? label` collapsed them to the same key —
+ * selecting sibling B mid-burst then didn't flush A's pending nudge, so the
+ * next arrow kept moving A. selectorIndex is the discriminator that separates
+ * them. The parts are only ever compared for equality (never parsed back),
+ * so they're joined on a NUL delimiter — a byte no discriminator can contain,
+ * so distinct selections stay distinct even when a value (e.g. a label) holds
+ * a space. It's written as the escape "\u0000", not a literal 0x00 byte, so
+ * this source file stays text (a raw NUL makes git treat it as binary).
+ */
+function selectionIdentityKey(selection: DomEditSelection | null): string {
+ if (!selection) return "";
+ return [
+ selection.id ?? "",
+ selection.hfId ?? "",
+ selection.selector ?? "",
+ selection.selectorIndex ?? "",
+ selection.label,
+ ].join("\u0000");
+}
+
+function groupSelectionsIdentityKey(selections: DomEditSelection[]): string {
+ return selections.map(selectionIdentityKey).join(" ");
+}
+
+/** Drag members for a multi-selection nudge (same snapshot a group drag uses). */
+function resolveGroupNudgeTargets(groupItems: GroupOverlayItem[]): NudgeTarget[] | null {
+ if (!canCanvasNudgeTargets(groupItems.map((item) => item.selection))) return null;
+ return filterNestedDomEditGroupItems(groupItems);
+}
+
+/** Drag member for a single-selection nudge, or null when it can't be moved. */
+function resolveSingleNudgeTarget(
+ sel: DomEditSelection | null,
+ rect: OverlayRect | null,
+): NudgeTarget[] | null {
+ if (!sel || !rect || !sel.capabilities.canApplyManualOffset || !sel.element.isConnected) {
+ return null;
+ }
+ return [{ key: sel.id ?? sel.selector ?? sel.label, selection: sel, element: sel.element, rect }];
+}
+
+/**
+ * True when a keydown must not start/extend a nudge: canvas movement disabled,
+ * a pointer gesture already owns the element, or the user is typing in a field.
+ */
+function shouldIgnoreNudgeKey(p: UseDomEditNudgeParams, event: KeyboardEvent): boolean {
+ if (!p.allowCanvasMovement || event.defaultPrevented) return true;
+ if (p.gestureRef.current || p.groupGestureRef.current || p.blockedMoveRef.current) return true;
+ return isEditableTarget(event.target);
+}
+
+export function useDomEditNudge(params: UseDomEditNudgeParams): { flushNudge: () => void } {
+ const sessionRef = useRef<NudgeSession | null>(null);
+ const paramsRef = useRef(params);
+ paramsRef.current = params;
+
+ // Commit the pending burst: one source write per burst = one undo entry.
+ // Mirrors the drag's onPointerUp — same commit callbacks, same failure
+ // restore, same member teardown.
+ const commitSession = () => {
+ const session = sessionRef.current;
+ if (!session) return;
+ sessionRef.current = null;
+ if (session.timer) clearTimeout(session.timer);
+ const updates: DomEditGroupPathOffsetCommit[] = session.members.map((member) => ({
+ selection: member.selection,
+ next: applyManualOffsetNudgeCommit(member, session.accum),
+ }));
+ const p = paramsRef.current;
+ const commit = session.isGroup
+ ? p.onGroupPathOffsetCommitRef.current(updates)
+ : p.onPathOffsetCommitRef.current(updates[0].selection, updates[0].next);
+ void Promise.resolve(commit)
+ .catch(() => {
+ for (const member of session.members) {
+ if (isStudioManualEditGestureCurrent(member.element, member.gestureToken)) {
+ restoreStudioPathOffset(member.element, member.initialPathOffset);
+ }
+ }
+ })
+ .finally(() => endManualOffsetDragMembers(session.members));
+ };
+ const commitSessionRef = useRef(commitSession);
+ commitSessionRef.current = commitSession;
+
+ // Build drag members for the current target set — the same member snapshot a
+ // pointer drag starts from (startGesture / startGroupDrag), so the nudge
+ // commit converts offsets → GSAP x/y with identical math.
+ const beginSession = (): NudgeSession | null => {
+ const p = paramsRef.current;
+ const groupItems = p.groupOverlayItemsRef.current;
+ const isGroup = groupItems.length > 1;
+ const targets = isGroup
+ ? resolveGroupNudgeTargets(groupItems)
+ : resolveSingleNudgeTarget(p.selectionRef.current, p.overlayRectRef.current);
+ if (!targets) return null;
+ const members: ManualOffsetDragMember[] = [];
+ for (const target of targets) {
+ const result = createManualOffsetDragMember(target);
+ if (!result.ok) {
+ restoreManualOffsetDragMembers(members);
+ return null;
+ }
+ members.push(result.member);
+ }
+ if (members.length === 0) return null;
+ // Same side effect a drag start has (pauses preview playback).
+ p.onManualDragStartRef.current?.();
+ return { members, isGroup, accum: { x: 0, y: 0 }, timer: null };
+ };
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ const p = paramsRef.current;
+ if (shouldIgnoreNudgeKey(p, event)) return;
+ const delta = resolveCanvasNudgeDelta(event);
+ if (!delta) return;
+ const session = sessionRef.current ?? beginSession();
+ if (!session) return;
+ sessionRef.current = session;
+ event.preventDefault();
+ session.accum = { x: session.accum.x + delta.dx, y: session.accum.y + delta.dy };
+ for (const member of session.members) applyManualOffsetNudgeDraft(member, session.accum);
+ if (session.timer) clearTimeout(session.timer);
+ session.timer = setTimeout(() => commitSessionRef.current(), CANVAS_NUDGE_COMMIT_DEBOUNCE_MS);
+ };
+ const handleKeyDownRef = useRef(handleKeyDown);
+ handleKeyDownRef.current = handleKeyDown;
+
+ useMountEffect(() => {
+ const listener = (event: KeyboardEvent) => handleKeyDownRef.current(event);
+ // Capture, like the other app-level key handlers, so a focused panel
+ // can't swallow the nudge before it reaches us.
+ window.addEventListener("keydown", listener, true);
+ return () => {
+ window.removeEventListener("keydown", listener, true);
+ commitSessionRef.current();
+ };
+ });
+
+ // Selection change ends the burst: commit to the OLD target before the
+ // arrows start moving the new one. Keyed on the selection's stable identity
+ // (id/selector/label), NOT the object reference — a parent that re-creates
+ // the selection object on every render (without memoizing it) must not
+ // flush a burst that's still in progress for the same element.
+ const selectionKey = selectionIdentityKey(params.selection);
+ const groupSelectionsKey = groupSelectionsIdentityKey(params.groupSelections);
+ // eslint-disable-next-line no-restricted-syntax
+ useEffect(() => () => commitSessionRef.current(), [selectionKey, groupSelectionsKey]);
+
+ // Claim the arrow keys from the playback frame-step while the selection is
+ // nudgeable (see canvasNudgeGate — listener order is mount-dependent, so
+ // preventDefault alone can't arbitrate).
+ // eslint-disable-next-line no-restricted-syntax
+ useEffect(() => {
+ const targets =
+ params.groupSelections.length > 1
+ ? params.groupSelections
+ : params.selection
+ ? [params.selection]
+ : [];
+ if (!params.allowCanvasMovement || !canCanvasNudgeTargets(targets)) return;
+ return acquireCanvasNudgeKeys();
+ }, [params.selection, params.groupSelections, params.allowCanvasMovement]);
+
+ // A pointer gesture supersedes a pending burst — DomEditOverlay flushes on
+ // pointerdown-capture so the drag's member snapshot starts from the nudged,
+ // committed position.
+ const flushNudge = useCallback(() => commitSessionRef.current(), []);
+ return { flushNudge };
+}
diff --git a/packages/studio/src/components/editor/useDomEditOverlayGestures.ts b/packages/studio/src/components/editor/useDomEditOverlayGestures.ts
index 83da0418e6..7af8df2e7b 100644
--- a/packages/studio/src/components/editor/useDomEditOverlayGestures.ts
+++ b/packages/studio/src/components/editor/useDomEditOverlayGestures.ts
@@ -4,7 +4,6 @@
* Owns: onPointerMove, onPointerUp, clearPointerState.
* startGesture and startGroupDrag live in domEditOverlayStartGesture.ts.
*/
-import { setElementGsapPosition } from "../../utils/elementGsap";
import type { RefObject } from "react";
import { type DomEditSelection } from "./domEditing";
import {
@@ -30,36 +29,29 @@ import {
import {
type GroupOverlayItem,
type OverlayRect,
+ orientedOverlayRect,
resolveDomEditGroupOverlayRect,
- toOverlayRect,
} from "./domEditOverlayGeometry";
import {
BLOCKED_MOVE_THRESHOLD_PX,
type GestureKind,
type GestureState,
type GroupGestureState,
+ type ResizeHandle,
type UseDomEditOverlayGesturesOptions,
+ ROTATED_SNAP_BYPASS_DEGREES,
hasDomEditRotationChanged,
- resolveDomEditResizeGesture,
resolveDomEditRotationGesture,
} from "./domEditOverlayGestures";
+import { resolveCenterResizeSize } from "./domEditResizeLocal";
+import { resolveResizeDraftRect } from "./resizeDraft";
import {
startGesture as _startGesture,
startGroupDrag as _startGroupDrag,
} from "./domEditOverlayStartGesture";
import { hugRectForElement } from "./domEditOverlayCrop";
-import {
- resolveSnapAdjustment,
- resolveResizeSnapAdjustment,
- resolveEquidistanceGuides,
- SNAP_THRESHOLD_PX,
-} from "./snapEngine";
-/** Undo the resize draft's anchor pin: snap GSAP x/y back to the gesture base. */
-function restoreResizeAnchorPin(element: HTMLElement, g: GestureState): void {
- const anchor = g.resizeAnchor;
- if (!anchor || (anchor.pinX === 0 && anchor.pinY === 0)) return;
- setElementGsapPosition(element, anchor.baseGsapX, anchor.baseGsapY);
-}
+import { resolveSnapAdjustment, resolveEquidistanceGuides, SNAP_THRESHOLD_PX } from "./snapEngine";
+import { logResize, logResizeMove, logResizeSettle } from "../../utils/resizeDebug";
export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGesturesOptions) {
const setDraftOverlayRect = (next: OverlayRect) => {
@@ -73,6 +65,10 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
height: g.originHeight,
editScaleX: g.editScaleX,
editScaleY: g.editScaleY,
+ // Every draft rect must carry the element's rotation: the rotation wrapper
+ // renders rotate(overlayRect.angle), so an omitted angle straightens the
+ // chrome for the duration of the draft (the "straightens while moving" bug).
+ angle: g.actualRotation,
});
};
const setDraftGroupOverlayItems = (next: GroupOverlayItem[]) => {
@@ -88,7 +84,11 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
const startGesture = (
kind: GestureKind,
e: React.PointerEvent<HTMLElement>,
- options?: { selection?: DomEditSelection; rect?: OverlayRect | null },
+ options?: {
+ selection?: DomEditSelection;
+ rect?: OverlayRect | null;
+ resizeHandle?: ResizeHandle;
+ },
) => _startGesture(kind, e, opts, options);
// fallow-ignore-next-line complexity
@@ -183,8 +183,7 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
actualAngle: g.actualRotation,
snap: e.shiftKey,
});
- const draftViaGsap = applyRotationDraftViaGsap(sel.element, rotated.angle);
- if (!draftViaGsap) {
+ if (!applyRotationDraftViaGsap(sel.element, rotated.angle)) {
applyStudioRotationDraft(sel.element, rotated);
}
return;
@@ -192,7 +191,11 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
if (g.kind === "drag") {
const sc = g.snapContext;
- if (sc?.snapEnabled && sc.targets.length > 0) {
+ // Bypass edge-snapping for rotated elements — the snap targets and the
+ // snapped rect are axis-aligned, so snapping a rotated box's AABB shifts it
+ // unpredictably. Rotation ~0 keeps snapping exactly as before.
+ const dragRotated = Math.abs(g.actualRotation) >= ROTATED_SNAP_BYPASS_DEGREES;
+ if (!dragRotated && sc?.snapEnabled && sc.targets.length > 0) {
// Snap the element's VISIBLE (crop-hugged) edges, not the full bounds.
const movingRect = hugRectForElement(
{
@@ -246,6 +249,7 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
height: g.originHeight,
editScaleX: g.editScaleX,
editScaleY: g.editScaleY,
+ angle: g.actualRotation,
});
if (box) {
box.style.left = `${nextBoxLeft}px`;
@@ -255,90 +259,49 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
} else {
if (!box) return;
- const sc = g.snapContext;
- if (sc?.snapEnabled && sc.targets.length > 0) {
- const movingRect = {
- left: g.originLeft,
- top: g.originTop,
- width: g.originWidth,
- height: g.originHeight,
- };
- const allTargets = sc.compositionTarget
- ? [...sc.targets, sc.compositionTarget]
- : sc.targets;
- const snap = resolveResizeSnapAdjustment({
- movingRect,
- proposedDx: dx,
- proposedDy: dy,
- targets: allTargets,
- gridEdges: sc.gridEdges ?? undefined,
- threshold: SNAP_THRESHOLD_PX,
- disabled: e.altKey,
- });
- dx = snap.dx;
- dy = snap.dy;
- opts.snapGuidesRef.current = { guides: snap.guides, spacingGuides: [] };
- }
-
- const nextSize = resolveDomEditResizeGesture({
- originWidth: g.originWidth,
- originHeight: g.originHeight,
- actualWidth: g.actualWidth,
- actualHeight: g.actualHeight,
- scaleX: g.editScaleX,
- scaleY: g.editScaleY,
- contentScaleX: g.contentScaleX,
- contentScaleY: g.contentScaleY,
- dx,
- dy,
- uniform: e.shiftKey,
+ // CENTER-ANCHORED size (CapCut model): the element scales proportionally
+ // about its CENTER — the scale is the pointer's RADIAL distance from the
+ // element center now over its distance at gesture start. Rotation-invariant
+ // (a distance ignores the angle) and continuous, so all four corners behave
+ // identically and there is no per-axis projection or edge-snapping. Base size
+ // is the element-local px size at gesture start (actualWidth/Height,
+ // GSAP-scale-aware). Corner drag is ALWAYS proportional; there is no
+ // free-form stretch gesture. Edge-snapping is intentionally NOT applied:
+ // with center anchoring both edges move symmetrically, so the corner-anchored
+ // snap math no longer holds — CapCut does not edge-snap during scale either.
+ const nextSize = resolveCenterResizeSize({
+ baseWidth: g.actualWidth,
+ baseHeight: g.actualHeight,
+ pointer: { x: e.clientX, y: e.clientY },
+ pointerStart: { x: g.startX, y: g.startY },
+ centerStart: { x: g.centerX, y: g.centerY },
});
applyStudioBoxSizeDraft(sel.element, nextSize);
- // Pin the gesture anchor (top-left): with a live scale transform, the CSS
- // size change shifts the rendered box around the element center. Measure
- // the drift of the gesture-start corner and counter it via GSAP x/y —
- // accumulated onto the previous pin so the correction converges instead
- // of oscillating. The release-time position compensation re-measures the
- // drop, so the pin composes with the commit.
- const anchor = g.resizeAnchor;
- if (anchor) {
- const pinned = sel.element.getBoundingClientRect();
- const nextPinX = anchor.pinX + (anchor.anchorX - pinned.x);
- const nextPinY = anchor.pinY + (anchor.anchorY - pinned.y);
- if (
- setElementGsapPosition(
- sel.element,
- anchor.baseGsapX + nextPinX,
- anchor.baseGsapY + nextPinY,
- )
- ) {
- anchor.pinX = nextPinX;
- anchor.pinY = nextPinY;
- }
- }
- // Re-read BCR after applying dimensions. For elements with a GSAP
- // scale transform and centered transform-origin the visual top-left
- // drifts and the visual size diverges from the raw CSS size, so BCR
- // is the only accurate source for both.
+
const overlayEl = opts.overlayRef.current;
const iframe = opts.iframeRef.current;
- const refreshed = overlayEl && iframe ? toOverlayRect(overlayEl, iframe, sel.element) : null;
- const overlayLeft = refreshed ? refreshed.left : g.originLeft;
- const overlayTop = refreshed ? refreshed.top : g.originTop;
- const overlayWidth = refreshed ? refreshed.width : nextSize.overlayWidth;
- const overlayHeight = refreshed ? refreshed.height : nextSize.overlayHeight;
- box.style.left = `${overlayLeft}px`;
- box.style.top = `${overlayTop}px`;
- box.style.width = `${overlayWidth}px`;
- box.style.height = `${overlayHeight}px`;
- setDraftOverlayRect({
- left: overlayLeft,
- top: overlayTop,
- width: overlayWidth,
- height: overlayHeight,
- editScaleX: g.editScaleX,
- editScaleY: g.editScaleY,
+ const measureOrientedRect = () =>
+ overlayEl && iframe ? orientedOverlayRect(overlayEl, iframe, sel.element) : null;
+
+ const draftRect = resolveResizeDraftRect(
+ g,
+ sel.element,
+ overlayEl,
+ iframe,
+ measureOrientedRect,
+ );
+ logResizeMove({
+ pointer: { x: e.clientX, y: e.clientY },
+ nextSize,
+ anchor: g.lastResizeAnchor ?? null,
+ draftRect,
+ liveInlineStyle: sel.element.getAttribute("style"),
});
+ box.style.left = `${draftRect.left}px`;
+ box.style.top = `${draftRect.top}px`;
+ box.style.width = `${draftRect.width}px`;
+ box.style.height = `${draftRect.height}px`;
+ setDraftOverlayRect(draftRect);
}
};
@@ -414,9 +377,12 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
}
if (g.kind === "resize" && movedDistance < BLOCKED_MOVE_THRESHOLD_PX) {
- restoreResizeAnchorPin(sel.element, g);
restoreStudioBoxSize(sel.element, g.initialBoxSize);
- endStudioManualEditGesture(sel.element, g.manualEditDragToken);
+ if (g.pathOffsetMember) {
+ restoreManualOffsetDragMembers([g.pathOffsetMember]);
+ } else {
+ endStudioManualEditGesture(sel.element, g.manualEditDragToken);
+ }
if (box) {
box.style.width = `${g.originWidth}px`;
box.style.height = `${g.originHeight}px`;
@@ -444,8 +410,7 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
restoreStudioRotation(sel.element, g.initialRotation);
}
};
- const rotationChanged = hasDomEditRotationChanged(g.actualRotation, finalRotation.angle);
- if (!rotationChanged) {
+ if (!hasDomEditRotationChanged(g.actualRotation, finalRotation.angle)) {
restoreRotation();
endStudioManualEditGesture(sel.element, g.manualEditDragToken);
return;
@@ -464,10 +429,13 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
)
restoreRotation();
})
- .finally(() => {
- endStudioManualEditGesture(sel.element, g.manualEditDragToken);
- });
+ .finally(() => endStudioManualEditGesture(sel.element, g.manualEditDragToken));
} else if (g.kind === "drag") {
+ // A moved drag (taps returned earlier) must not let the release click
+ // re-select whatever now sits under the pointer — dropping over a
+ // higher-z element should keep the dragged element selected, not select
+ // the drop target. Mirrors the resize branch below.
+ opts.suppressNextBoxClickRef.current = true;
const dx = g.lastSnappedDx ?? e.clientX - g.startX;
const dy = g.lastSnappedDy ?? e.clientY - g.startY;
if (!g.pathOffsetMember) {
@@ -483,6 +451,7 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
height: g.originHeight,
editScaleX: g.editScaleX,
editScaleY: g.editScaleY,
+ angle: g.actualRotation,
});
if (box) {
box.style.left = `${nextBoxLeft}px`;
@@ -505,18 +474,45 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
opts.suppressNextBoxClickRef.current = true;
const finalSize = readStudioBoxSize(sel.element);
applyStudioBoxSize(sel.element, finalSize);
- void Promise.resolve(opts.onBoxSizeCommitRef.current(sel, finalSize))
+ // Anchored corner resize (NW/NE/SW) also moved the element to keep the
+ // center planted. Land the size AND the anchor offset in a SINGLE
+ // box-size commit (one persist, one undo entry). The prior two-commit
+ // sequence re-stamped the element from source after the size-only persist
+ // but before the offset persist landed — that one frame (new size, old
+ // offset) was the release "jump". SE has no anchor member → size only.
+ const member = g.pathOffsetMember;
+ const anchor = g.lastResizeAnchor;
+ const finalOffset =
+ member && anchor && (anchor.dx !== 0 || anchor.dy !== 0)
+ ? applyManualOffsetDragCommit(member, anchor.dx, anchor.dy)
+ : null;
+ logResize("release", {
+ finalSize,
+ anchor: anchor ?? null,
+ finalOffset: finalOffset ?? null,
+ hasMember: !!member,
+ inlineStyle: sel.element.getAttribute("style"),
+ });
+ const restore = () => {
+ if (
+ !g.manualEditDragToken ||
+ !isStudioManualEditGestureCurrent(sel.element, g.manualEditDragToken)
+ )
+ return;
+ restoreStudioBoxSize(sel.element, g.initialBoxSize);
+ if (finalOffset) restoreStudioPathOffset(sel.element, g.initialPathOffset);
+ };
+ void Promise.resolve(
+ opts.onBoxSizeCommitRef.current(sel, finalSize, finalOffset ?? undefined, restore),
+ )
.catch((error) => {
console.error("resize commit failed", error);
- if (
- g.manualEditDragToken &&
- isStudioManualEditGestureCurrent(sel.element, g.manualEditDragToken)
- ) {
- restoreResizeAnchorPin(sel.element, g);
- restoreStudioBoxSize(sel.element, g.initialBoxSize);
- }
})
- .finally(() => endStudioManualEditGesture(sel.element, g.manualEditDragToken));
+ .finally(() => {
+ if (member) endManualOffsetDragMembers([member]);
+ else endStudioManualEditGesture(sel.element, g.manualEditDragToken);
+ });
+ logResizeSettle(sel.element, "post-release");
}
};
@@ -534,9 +530,12 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
restoreGestureOverlayRect(g);
}
if (g?.mode === "box-size" && sel) {
- restoreResizeAnchorPin(sel.element, g);
restoreStudioBoxSize(sel.element, g.initialBoxSize);
- endStudioManualEditGesture(sel.element, g.manualEditDragToken);
+ if (g.pathOffsetMember) {
+ restoreManualOffsetDragMembers([g.pathOffsetMember]);
+ } else {
+ endStudioManualEditGesture(sel.element, g.manualEditDragToken);
+ }
restoreGestureOverlayRect(g);
}
if (g?.mode === "rotation" && sel) {
diff --git a/packages/studio/src/components/editor/useDomEditOverlayRects.ts b/packages/studio/src/components/editor/useDomEditOverlayRects.ts
index 70d35db452..b45ff6f26c 100644
--- a/packages/studio/src/components/editor/useDomEditOverlayRects.ts
+++ b/packages/studio/src/components/editor/useDomEditOverlayRects.ts
@@ -13,6 +13,7 @@ import {
groupOverlayItemsEqual,
isElementVisibleForOverlay,
groupAwareOverlayRect,
+ orientedGroupAwareOverlayRect,
rectsEqual,
resolveElementForOverlay,
selectionCacheKey,
@@ -157,7 +158,13 @@ export function useDomEditOverlayRects({
// backgroundless full-bleed scene above a subcomposition), which would wrongly
// hide the selection box. Occlusion stays for hover, where a false hide is cheap.
if (el && isElementVisibleForOverlay(el)) {
- const nextRect = groupAwareOverlayRect(overlayEl, iframe, el);
+ // Groups render as an AABB union of their members (a group OBB is out of
+ // scope); a single element renders as an oriented box that co-rotates
+ // with its transform. orientedOverlayRect gates on rotation internally
+ // (a cheap per-call check) and only pays for the full corner-transform
+ // measurement when the element is actually rotated — this RAF loop runs
+ // every frame for any single selection, so that gate matters here most.
+ const nextRect = orientedGroupAwareOverlayRect(overlayEl, iframe, el);
setOverlayRect(nextRect);
const descendants = el.querySelectorAll("*");
if (descendants.length > 0 && descendants.length <= 60) {
@@ -242,7 +249,7 @@ export function useDomEditOverlayRects({
return;
}
- setHoverRect(groupAwareOverlayRect(overlayEl, iframe, hoverEl));
+ setHoverRect(orientedGroupAwareOverlayRect(overlayEl, iframe, hoverEl));
};
frame = requestAnimationFrame(update);
diff --git a/packages/studio/src/components/nle/AssetPreviewOverlay.tsx b/packages/studio/src/components/nle/AssetPreviewOverlay.tsx
new file mode 100644
index 0000000000..6245c4985e
--- /dev/null
+++ b/packages/studio/src/components/nle/AssetPreviewOverlay.tsx
@@ -0,0 +1,147 @@
+/**
+ * CapCut-style asset preview overlay rendered inside PreviewPane.
+ *
+ * Shown when the user clicks an asset card that has NOT yet been added to the
+ * timeline. Displays the media (image / video / audio) without modifying the
+ * composition — no undo entry, no file mutation.
+ *
+ * Dismiss: X button, Escape key, or click on the scrim.
+ * Switching to another not-added asset replaces the current preview.
+ */
+import { useEffect, useCallback } from "react";
+import { VIDEO_EXT, IMAGE_EXT } from "../../utils/mediaTypes";
+import { useAssetPreviewStore } from "../../utils/assetPreviewStore";
+import { resolveMediaPreviewUrl } from "../../player/components/thumbnailUtils";
+
+function basename(path: string): string {
+ return path.split("/").pop() ?? path;
+}
+
+type AssetKind = "image" | "video" | "audio";
+
+function resolveAssetKind(path: string): AssetKind {
+ if (VIDEO_EXT.test(path)) return "video";
+ if (IMAGE_EXT.test(path)) return "image";
+ return "audio";
+}
+
+/** The media element for a previewed asset, chosen by kind. */
+function AssetPreviewMedia({
+ kind,
+ serveUrl,
+ name,
+}: {
+ kind: AssetKind;
+ serveUrl: string;
+ name: string;
+}) {
+ if (kind === "image") {
+ return (
+ <img
+ src={serveUrl}
+ alt={name}
+ className="max-w-full max-h-[70vh] rounded-md object-contain shadow-2xl"
+ />
+ );
+ }
+ if (kind === "video") {
+ return (
+ <video
+ src={serveUrl}
+ controls
+ autoPlay
+ muted
+ playsInline
+ className="max-w-full max-h-[70vh] rounded-md shadow-2xl"
+ />
+ );
+ }
+ return (
+ <div className="flex flex-col items-center gap-4 px-6 py-8 rounded-xl bg-neutral-900 border border-neutral-800">
+ <svg
+ width="40"
+ height="40"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ className="text-neutral-500"
+ >
+ <path d="M9 18V5l12-2v13" strokeLinecap="round" strokeLinejoin="round" />
+ <circle cx="6" cy="18" r="3" />
+ <circle cx="18" cy="16" r="3" />
+ </svg>
+ <audio src={serveUrl} controls className="w-64" />
+ </div>
+ );
+}
+
+export function AssetPreviewOverlay() {
+ const previewAsset = useAssetPreviewStore((s) => s.previewAsset);
+ const previewProjectId = useAssetPreviewStore((s) => s.previewProjectId);
+ const clearPreviewAsset = useAssetPreviewStore((s) => s.clearPreviewAsset);
+
+ const handleKeyDown = useCallback(
+ (e: KeyboardEvent) => {
+ if (e.key === "Escape") clearPreviewAsset();
+ },
+ [clearPreviewAsset],
+ );
+
+ useEffect(() => {
+ if (!previewAsset) return;
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, [previewAsset, handleKeyDown]);
+
+ if (!previewAsset || !previewProjectId) return null;
+
+ const serveUrl = resolveMediaPreviewUrl(previewAsset, previewProjectId);
+ const name = basename(previewAsset);
+
+ return (
+ <div
+ className="absolute inset-0 z-50 flex flex-col items-center justify-center bg-black/80"
+ onClick={clearPreviewAsset}
+ role="dialog"
+ aria-label={`Preview: ${name}`}
+ aria-modal="true"
+ >
+ {/* Close button */}
+ <button
+ className="absolute top-3 right-3 w-7 h-7 rounded-full bg-neutral-800 hover:bg-neutral-700 text-neutral-300 hover:text-white flex items-center justify-center transition-colors z-10"
+ onClick={(e) => {
+ e.stopPropagation();
+ clearPreviewAsset();
+ }}
+ aria-label="Close preview"
+ >
+ <svg
+ width="12"
+ height="12"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ strokeWidth="2.5"
+ fill="none"
+ strokeLinecap="round"
+ >
+ <line x1="18" y1="6" x2="6" y2="18" />
+ <line x1="6" y1="6" x2="18" y2="18" />
+ </svg>
+ </button>
+
+ {/* Media */}
+ <div
+ className="flex flex-col items-center gap-3 max-w-[90%] max-h-[85%]"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <AssetPreviewMedia kind={resolveAssetKind(previewAsset)} serveUrl={serveUrl} name={name} />
+
+ {/* Filename label */}
+ <span className="text-[12px] text-neutral-400 truncate max-w-full px-2 text-center">
+ {name}
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/studio/src/components/nle/NLEContext.test.ts b/packages/studio/src/components/nle/NLEContext.test.ts
new file mode 100644
index 0000000000..cb59fcdb1b
--- /dev/null
+++ b/packages/studio/src/components/nle/NLEContext.test.ts
@@ -0,0 +1,144 @@
+// @vitest-environment happy-dom
+import React, { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { shouldDisableTimelineWhileCompositionLoading, NLEProvider } from "./NLEContext";
+import { useAssetPreviewStore } from "../../utils/assetPreviewStore";
+import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness";
+
+installReactActEnvironment();
+
+// Render NLEProvider into a fresh detached host and settle the mount effect.
+async function mountNleProvider(props: {
+ projectId: string;
+ refreshKey?: number;
+}): Promise<{ host: HTMLDivElement; root: Root }> {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ await renderNleProvider(root, props);
+ return { host, root };
+}
+
+// Re-render NLEProvider into an existing root and settle effects.
+async function renderNleProvider(
+ root: Root,
+ props: {
+ projectId: string;
+ refreshKey?: number;
+ onCompIdToSrcChange?: (map: Map<string, string>) => void;
+ },
+): Promise<void> {
+ await act(async () => {
+ root.render(React.createElement(NLEProvider, props, React.createElement("div")));
+ await Promise.resolve();
+ });
+}
+
+describe("timeline loading disable state", () => {
+ it("disables the timeline while the composition loading overlay is visible", () => {
+ expect(shouldDisableTimelineWhileCompositionLoading(true)).toBe(true);
+ });
+
+ it("reenables the timeline after composition loading finishes", () => {
+ expect(shouldDisableTimelineWhileCompositionLoading(false)).toBe(false);
+ });
+});
+
+describe("NLEProvider — asset preview scoping", () => {
+ beforeEach(() => {
+ // No project API in this unit test — stub fetch so the compIdToSrc mount
+ // effect's request rejects quietly instead of hitting the network.
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(() => Promise.reject(new Error("no network in tests"))),
+ );
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ useAssetPreviewStore.getState().clearPreviewAsset();
+ });
+
+ it("clears a stale cross-project asset preview when the active project changes", async () => {
+ const { host, root } = await mountNleProvider({ projectId: "project-a" });
+
+ useAssetPreviewStore.getState().setPreviewAsset("assets/photo.png", "project-a");
+ expect(useAssetPreviewStore.getState().previewAsset).toBe("assets/photo.png");
+
+ await renderNleProvider(root, { projectId: "project-b" });
+
+ // The overlay stays mounted across the project switch (EditorShell isn't
+ // keyed by projectId) — the store itself must be the thing that clears.
+ expect(useAssetPreviewStore.getState().previewAsset).toBeNull();
+ expect(useAssetPreviewStore.getState().previewProjectId).toBeNull();
+
+ act(() => root.unmount());
+ host.remove();
+ });
+
+ it("does not clear the preview on a re-render that keeps the same projectId", async () => {
+ const { host, root } = await mountNleProvider({ projectId: "project-a" });
+
+ useAssetPreviewStore.getState().setPreviewAsset("assets/photo.png", "project-a");
+
+ await renderNleProvider(root, { projectId: "project-a", refreshKey: 1 });
+
+ expect(useAssetPreviewStore.getState().previewAsset).toBe("assets/photo.png");
+
+ act(() => root.unmount());
+ host.remove();
+ });
+});
+
+describe("NLEProvider — composition source-map scoping", () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("clears the old map and ignores a late project-A response after switching to B", async () => {
+ let resolveA!: (response: Response) => void;
+ const fetchMock = vi.fn((url: string) => {
+ if (url.includes("project-a")) {
+ return new Promise<Response>((resolve) => {
+ resolveA = resolve;
+ });
+ }
+ return Promise.resolve({
+ ok: true,
+ json: async () => ({
+ content: '<div data-composition-id="b-comp" data-composition-src="compositions/b.html">',
+ }),
+ } as Response);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ const observed: Array<Map<string, string>> = [];
+ const onChange = (map: Map<string, string>) => observed.push(new Map(map));
+ const { host, root } = await mountNleProvider({
+ projectId: "project-a",
+ onCompIdToSrcChange: onChange,
+ });
+
+ await renderNleProvider(root, {
+ projectId: "project-b",
+ onCompIdToSrcChange: onChange,
+ });
+ await act(async () => Promise.resolve());
+
+ expect(observed.filter((map) => map.size === 0)).toHaveLength(2);
+ expect(fetchMock).toHaveBeenCalledWith("/api/projects/project-b/files/index.html", {
+ signal: expect.any(AbortSignal),
+ });
+ expect(observed.at(-1)).toEqual(new Map([["b-comp", "compositions/b.html"]]));
+
+ resolveA({
+ ok: true,
+ json: async () => ({
+ content: '<div data-composition-id="a-comp" data-composition-src="compositions/a.html">',
+ }),
+ } as Response);
+ await act(async () => Promise.resolve());
+ expect(observed.at(-1)).toEqual(new Map([["b-comp", "compositions/b.html"]]));
+
+ act(() => root.unmount());
+ host.remove();
+ });
+});
diff --git a/packages/studio/src/components/nle/NLEContext.tsx b/packages/studio/src/components/nle/NLEContext.tsx
new file mode 100644
index 0000000000..968fcafb75
--- /dev/null
+++ b/packages/studio/src/components/nle/NLEContext.tsx
@@ -0,0 +1,328 @@
+import {
+ createContext,
+ useContext,
+ useState,
+ useCallback,
+ useRef,
+ useEffect,
+ type ReactNode,
+} from "react";
+import { useTimelinePlayer, usePlayerStore } from "../../player";
+import type { TimelineElement } from "../../player";
+import type { CompositionLevel } from "./CompositionBreadcrumb";
+import { useCompositionStack } from "./useCompositionStack";
+import { MIN_TIMELINE_H, MIN_PREVIEW_H } from "./TimelineResizeDivider";
+import { setCompositionSourceMap } from "../editor/domEditingDom";
+import { ensureMotionPathPluginLoaded } from "../../utils/gsapSoftReload";
+import { readStudioUiPreferences, writeStudioUiPreferences } from "../../utils/studioUiPreferences";
+import { useAssetPreviewStore } from "../../utils/assetPreviewStore";
+
+// Timeline gets a generous default height so the preview isn't oversized and the
+// tracks have room to breathe (CapCut-style). Users can still drag the divider.
+const DEFAULT_TIMELINE_H = 340;
+
+export function shouldDisableTimelineWhileCompositionLoading(compositionLoading: boolean): boolean {
+ return compositionLoading;
+}
+
+export interface NLEContextValue {
+ projectId: string;
+ // player (from useTimelinePlayer — single instance for the whole shell)
+ iframeRef: React.MutableRefObject<HTMLIFrameElement | null>;
+ togglePlay: () => void;
+ seek: (time: number, options?: { keepPlaying?: boolean }) => boolean;
+ refreshPlayer: () => void;
+ onIframeLoad: () => void;
+ // composition stack (from useCompositionStack)
+ compositionStack: CompositionLevel[];
+ updateCompositionStack: React.Dispatch<React.SetStateAction<CompositionLevel[]>>;
+ handleNavigateComposition: (index: number) => void;
+ handleDrillDown: (element: TimelineElement) => void;
+ compIdToSrc: Map<string, string>;
+ // layout state
+ timelineH: number;
+ setTimelineH: React.Dispatch<React.SetStateAction<number>>;
+ persistTimelineH: (height: number) => void;
+ containerRef: React.RefObject<HTMLDivElement | null>;
+ // composition loading
+ compositionLoading: boolean;
+ setCompositionLoading: (loading: boolean) => void;
+ timelineDisabled: boolean;
+ hasLoadedOnceRef: React.MutableRefObject<boolean>;
+ // preview composition size (for preview block drop)
+ previewCompositionSize: { width: number; height: number } | null;
+ setPreviewCompositionSize: (size: { width: number; height: number } | null) => void;
+}
+
+const NLEContext = createContext<NLEContextValue | null>(null);
+
+export function useNLEContext(): NLEContextValue {
+ const ctx = useContext(NLEContext);
+ if (!ctx) throw new Error("useNLEContext must be used within an NLEProvider");
+ return ctx;
+}
+
+export interface NLEProviderProps {
+ projectId: string;
+ refreshKey?: number;
+ activeCompositionPath?: string | null;
+ onIframeRef?: (iframe: HTMLIFrameElement | null) => void;
+ onCompositionChange?: (compositionPath: string | null) => void;
+ onCompIdToSrcChange?: (map: Map<string, string>) => void;
+ onCompositionLoadingChange?: (loading: boolean) => void;
+ children: ReactNode;
+}
+
+export function NLEProvider({
+ projectId,
+ refreshKey,
+ activeCompositionPath,
+ onIframeRef,
+ onCompositionChange,
+ onCompIdToSrcChange,
+ onCompositionLoadingChange,
+ children,
+}: NLEProviderProps) {
+ const {
+ iframeRef,
+ togglePlay,
+ seek,
+ onIframeLoad: baseOnIframeLoad,
+ refreshPlayer,
+ } = useTimelinePlayer();
+
+ // Reset timeline state when the project changes. Done in an effect, not during
+ // render: reset() updates the player store, and updating another store/component
+ // mid-render triggers React's "Cannot update a component while rendering a
+ // different component" warning. The effect runs right after commit, so the new
+ // project's first frame may briefly show prior timeline state before it clears.
+ //
+ // Also clears the asset preview overlay store: it is project-scoped (see its
+ // doc-comment) but nothing else clears it on project change — EditorShell isn't
+ // keyed by projectId and the overlay stays mounted, so a preview opened in one
+ // project would otherwise keep rendering (and re-fetching from) the old project
+ // after switching.
+ useEffect(() => {
+ usePlayerStore.getState().reset();
+ useAssetPreviewStore.getState().clearPreviewAsset();
+ }, [projectId]);
+
+ // Authored composition size measured from the loaded preview — drives drop
+ // coordinate mapping so blocks land where the user pointed on any comp size.
+ const [previewCompositionSize, setPreviewCompositionSize] = useState<{
+ width: number;
+ height: number;
+ } | null>(null);
+
+ // Lightweight reload: change iframe src instead of destroying the Player.
+ const prevRefreshKeyRef = useRef(refreshKey);
+ useEffect(() => {
+ if (refreshKey === prevRefreshKeyRef.current) return;
+ prevRefreshKeyRef.current = refreshKey;
+ refreshPlayer();
+ }, [refreshKey, refreshPlayer]);
+
+ const onIframeLoad = useCallback(() => {
+ baseOnIframeLoad();
+ // Pre-load + register MotionPathPlugin once so adding a motion path in the
+ // studio doesn't take the async plugin-load flash path on the first soft
+ // reload (the comp may not ship the plugin until it actually uses one).
+ ensureMotionPathPluginLoaded(iframeRef.current);
+ onIframeRef?.(iframeRef.current);
+ }, [baseOnIframeLoad, iframeRef, onIframeRef]);
+
+ const {
+ compositionStack,
+ updateCompositionStack,
+ handleNavigateComposition,
+ handleDrillDown: drillDown,
+ compIdToSrc,
+ setCompIdToSrc,
+ } = useCompositionStack({
+ projectId,
+ activeCompositionPath,
+ onCompositionChange,
+ });
+
+ // Wrap handleDrillDown to also scan the iframe DOM for data-composition-src
+ const iframeRef_ = iframeRef;
+ const handleDrillDown = useCallback(
+ (element: TimelineElement) => {
+ if (!element.compositionSrc) return;
+ usePlayerStore.getState().setSelectedElementId(null);
+ // Check compIdToSrc map first; then scan iframe DOM; then fall through to drillDown
+ const compId = element.id;
+ let resolvedPath = compIdToSrc.get(compId);
+ if (!resolvedPath) {
+ try {
+ const doc = iframeRef_.current?.contentDocument;
+ if (doc) {
+ const host = doc.querySelector(
+ `[data-composition-id="${CSS.escape(compId)}"][data-composition-src]`,
+ );
+ if (host) {
+ resolvedPath = host.getAttribute("data-composition-src") || undefined;
+ }
+ }
+ } catch {
+ /* cross-origin */
+ }
+ }
+ // Delegate with the resolved compositionSrc (may be same as original)
+ drillDown({
+ id: compId,
+ compositionSrc: resolvedPath ?? element.compositionSrc,
+ });
+ },
+ [compIdToSrc, drillDown, iframeRef_],
+ );
+
+ // Composition ID → file path map from raw index.html
+ const compIdToSrcRef = useRef(compIdToSrc);
+ compIdToSrcRef.current = compIdToSrc;
+ const onCompIdToSrcChangeRef = useRef(onCompIdToSrcChange);
+ onCompIdToSrcChangeRef.current = onCompIdToSrcChange;
+
+ useEffect(() => {
+ const controller = new AbortController();
+ let current = true;
+ const emptyMap = new Map<string, string>();
+ setCompIdToSrc(emptyMap);
+ setCompositionSourceMap(emptyMap);
+ onCompIdToSrcChangeRef.current?.(emptyMap);
+
+ fetch(`/api/projects/${projectId}/files/index.html`, {
+ signal: controller.signal,
+ })
+ .then((r) => {
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ return r.json();
+ })
+ .then((data: { content?: string }) => {
+ if (!current) return;
+ const html = data.content || "";
+ const map = new Map<string, string>();
+ const re =
+ /data-composition-id=["']([^"']+)["'][^>]*data-composition-src=["']([^"']+)["']|data-composition-src=["']([^"']+)["'][^>]*data-composition-id=["']([^"']+)["']/g;
+ let match;
+ while ((match = re.exec(html)) !== null) {
+ const id = match[1] || match[4];
+ const src = match[2] || match[3];
+ if (id && src) map.set(id, src);
+ }
+ setCompIdToSrc(map);
+ // Let DOM source-resolution recover a subcomposition element's source file
+ // (the runtime drops the linkage when inlining — see getSourceFileForElement).
+ setCompositionSourceMap(map);
+ onCompIdToSrcChangeRef.current?.(map);
+ })
+ .catch((err: unknown) => {
+ if (!current || controller.signal.aborted) return;
+ // Non-fatal: drill-down still works via the iframe DOM scan; without
+ // the map only source-file resolution for sub-comps degrades.
+ console.warn("[studio] Couldn't load composition source map from index.html:", err);
+ });
+ return () => {
+ current = false;
+ controller.abort();
+ };
+ }, [projectId, setCompIdToSrc]);
+
+ // Patch elements with compositionSrc whenever elements or compIdToSrc change.
+ // eslint-disable-next-line no-restricted-syntax
+ useEffect(() => {
+ if (compIdToSrc.size === 0) return;
+ const patchElements = (elements: TimelineElement[]): TimelineElement[] | null => {
+ const map = compIdToSrcRef.current;
+ if (map.size === 0) return null;
+ let patched = false;
+ const updated = elements.map((el) => {
+ if (el.compositionSrc) return el;
+ const src = map.get(el.id) ?? map.get(el.id.replace(/-(host|comp|layer)$/, ""));
+ if (src) {
+ patched = true;
+ return { ...el, compositionSrc: src };
+ }
+ return el;
+ });
+ return patched ? updated : null;
+ };
+ const patched = patchElements(usePlayerStore.getState().elements);
+ if (patched) usePlayerStore.getState().setElements(patched);
+ let patching = false;
+ return usePlayerStore.subscribe((state, prev) => {
+ if (patching) return;
+ if (state.elements === prev.elements || state.elements.length === 0) return;
+ if (state.elements.every((el) => el.compositionSrc)) return;
+ patching = true;
+ const result = patchElements(state.elements);
+ if (result) state.setElements(result);
+ patching = false;
+ });
+ }, [compIdToSrc]);
+
+ // Resizable timeline height — persisted alongside zoom/pan so the user's
+ // workspace layout survives reloads.
+ const [timelineH, setTimelineH] = useState(() => {
+ const stored = readStudioUiPreferences().timelineHeight;
+ return stored !== undefined && stored >= MIN_TIMELINE_H ? stored : DEFAULT_TIMELINE_H;
+ });
+ const persistTimelineH = useCallback((height: number) => {
+ writeStudioUiPreferences({ timelineHeight: Math.round(height) });
+ }, []);
+ const containerRef = useRef<HTMLDivElement>(null);
+ // A height persisted on a tall window can exceed this window's container and
+ // collapse the flex-1 preview to 0px — clamp once the container is measurable
+ // (the drag/keyboard paths already clamp; the restore path must too).
+ useEffect(() => {
+ const containerH = containerRef.current?.getBoundingClientRect().height;
+ if (!containerH) return;
+ const max = containerH - MIN_PREVIEW_H;
+ setTimelineH((prev) => (prev > max ? Math.max(MIN_TIMELINE_H, max) : prev));
+ }, []);
+
+ const hasLoadedOnceRef = useRef(false);
+ const [compositionLoading, setCompositionLoadingRaw] = useState(true);
+ const setCompositionLoading = useCallback((loading: boolean) => {
+ if (!loading) hasLoadedOnceRef.current = true;
+ if (loading && hasLoadedOnceRef.current) return;
+ setCompositionLoadingRaw(loading);
+ }, []);
+ const timelineDisabled = shouldDisableTimelineWhileCompositionLoading(compositionLoading);
+
+ useEffect(() => {
+ onCompositionLoadingChange?.(compositionLoading);
+ }, [compositionLoading, onCompositionLoadingChange]);
+
+ const onIframeRefStable = useRef(onIframeRef);
+ onIframeRefStable.current = onIframeRef;
+ useEffect(() => {
+ onIframeRefStable.current?.(iframeRef.current);
+ }, [compositionStack.length, refreshKey, iframeRef]);
+
+ const value: NLEContextValue = {
+ projectId,
+ iframeRef,
+ togglePlay,
+ seek,
+ refreshPlayer,
+ onIframeLoad,
+ compositionStack,
+ updateCompositionStack,
+ handleNavigateComposition,
+ handleDrillDown,
+ compIdToSrc,
+ timelineH,
+ setTimelineH,
+ persistTimelineH,
+ containerRef,
+ compositionLoading,
+ setCompositionLoading,
+ timelineDisabled,
+ hasLoadedOnceRef,
+ previewCompositionSize,
+ setPreviewCompositionSize,
+ };
+
+ return <NLEContext.Provider value={value}>{children}</NLEContext.Provider>;
+}
diff --git a/packages/studio/src/components/nle/NLELayout.test.ts b/packages/studio/src/components/nle/NLELayout.test.ts
deleted file mode 100644
index c0aa410bbb..0000000000
--- a/packages/studio/src/components/nle/NLELayout.test.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { shouldDisableTimelineWhileCompositionLoading } from "./NLELayout";
-
-describe("timeline loading disable state", () => {
- it("disables the timeline while the composition loading overlay is visible", () => {
- expect(shouldDisableTimelineWhileCompositionLoading(true)).toBe(true);
- });
-
- it("reenables the timeline after composition loading finishes", () => {
- expect(shouldDisableTimelineWhileCompositionLoading(false)).toBe(false);
- });
-});
diff --git a/packages/studio/src/components/nle/NLELayout.tsx b/packages/studio/src/components/nle/NLELayout.tsx
deleted file mode 100644
index e91d861a43..0000000000
--- a/packages/studio/src/components/nle/NLELayout.tsx
+++ /dev/null
@@ -1,591 +0,0 @@
-import {
- useState,
- useCallback,
- useRef,
- useEffect,
- useSyncExternalStore,
- memo,
- type ReactNode,
-} from "react";
-import { useMountEffect } from "../../hooks/useMountEffect";
-import { useTimelinePlayer, PlayerControls, Timeline, usePlayerStore } from "../../player";
-import type { TimelineElement } from "../../player";
-import type { BlockedTimelineEditIntent } from "../../player/components/timelineEditing";
-import { NLEPreview } from "./NLEPreview";
-import { CompositionBreadcrumb } from "./CompositionBreadcrumb";
-import { TimelineResizeDivider, MIN_TIMELINE_H, MIN_PREVIEW_H } from "./TimelineResizeDivider";
-import { usePreviewBlockDrop } from "./usePreviewBlockDrop";
-import { useCompositionStack } from "./useCompositionStack";
-import { useTimelineEditContext } from "../../contexts/TimelineEditContext";
-import { setCompositionSourceMap } from "../editor/domEditingDom";
-import { trackStudioExpandedClipEdit } from "../../telemetry/events";
-import {
- TIMELINE_TOGGLE_SHORTCUT_LABEL,
- getTimelineToggleTitle,
-} from "../../utils/timelineDiscovery";
-import { ensureMotionPathPluginLoaded } from "../../utils/gsapSoftReload";
-import { readStudioUiPreferences, writeStudioUiPreferences } from "../../utils/studioUiPreferences";
-
-interface NLELayoutProps {
- projectId: string;
- portrait?: boolean;
- /** Slot for overlays rendered on top of the preview (cursors, highlights, etc.) */
- previewOverlay?: ReactNode;
- /** Slot rendered above the timeline tracks (toolbar with split, delete, zoom) */
- timelineToolbar?: ReactNode;
- /** Slot rendered below the timeline tracks */
- timelineFooter?: ReactNode;
- /** Increment to force the preview to reload (e.g., after file writes) */
- refreshKey?: number;
- /** Navigate to a specific composition path (e.g., "compositions/intro.html") */
- activeCompositionPath?: string | null;
- /** Callback to expose the iframe ref (for element picker, etc.) */
- onIframeRef?: (iframe: HTMLIFrameElement | null) => void;
- /** Callback when the viewed composition changes (drill-down/back) */
- onCompositionChange?: (compositionPath: string | null) => void;
- /** Custom clip content renderer for timeline (thumbnails, waveforms, etc.) */
- renderClipContent?: (
- element: TimelineElement,
- style: { clip: string; label: string },
- ) => ReactNode;
- onFileDrop?: (
- files: File[],
- placement?: Pick<TimelineElement, "start" | "track">,
- ) => Promise<void> | void;
- onDeleteElement?: (element: TimelineElement) => Promise<void> | void;
- onAssetDrop?: (
- assetPath: string,
- placement: Pick<TimelineElement, "start" | "track">,
- ) => Promise<void> | void;
- onBlockDrop?: (
- blockName: string,
- placement: Pick<TimelineElement, "start" | "track">,
- ) => Promise<void> | void;
- onPreviewBlockDrop?: (
- blockName: string,
- position: { left: number; top: number },
- ) => Promise<void> | void;
- onBlockedEditAttempt?: (element: TimelineElement, intent: BlockedTimelineEditIntent) => void;
- onSelectTimelineElement?: (element: TimelineElement | null) => void;
- /** Exposes the compIdToSrc map for parent components (e.g., useRenderClipContent) */
- onCompIdToSrcChange?: (map: Map<string, string>) => void;
- /** Whether the timeline panel is visible (default: true) */
- timelineVisible?: boolean;
- /** Callback to toggle timeline visibility */
- onToggleTimeline?: () => void;
- /** Notifies parent when composition loading state changes */
- onCompositionLoadingChange?: (loading: boolean) => void;
-}
-
-const DEFAULT_TIMELINE_H = 220;
-
-function subscribeFullscreen(cb: () => void) {
- document.addEventListener("fullscreenchange", cb);
- return () => document.removeEventListener("fullscreenchange", cb);
-}
-
-function getFullscreenElement() {
- return document.fullscreenElement;
-}
-
-export function shouldDisableTimelineWhileCompositionLoading(compositionLoading: boolean): boolean {
- return compositionLoading;
-}
-
-// fallow-ignore-next-line complexity
-export const NLELayout = memo(function NLELayout({
- projectId,
- portrait,
- previewOverlay,
- timelineToolbar,
- timelineFooter,
- refreshKey,
- activeCompositionPath,
- onIframeRef,
- onCompositionChange,
- renderClipContent,
- onFileDrop,
- onDeleteElement,
- onAssetDrop,
- onBlockDrop,
- onPreviewBlockDrop,
- onBlockedEditAttempt,
- onSelectTimelineElement,
- onCompIdToSrcChange,
- timelineVisible,
- onToggleTimeline,
- onCompositionLoadingChange: onCompositionLoadingChangeParent,
-}: NLELayoutProps) {
- const {
- iframeRef,
- togglePlay,
- seek,
- onIframeLoad: baseOnIframeLoad,
- refreshPlayer,
- } = useTimelinePlayer();
-
- // Reset timeline state when the project changes. Done in an effect, not during
- // render: reset() updates the player store, and updating another store/component
- // mid-render triggers React's "Cannot update a component while rendering a
- // different component" warning. The effect runs right after commit, so the new
- // project's first frame may briefly show prior timeline state before it clears.
- useEffect(() => {
- usePlayerStore.getState().reset();
- }, [projectId]);
-
- const stageRefForDrop = useRef<HTMLDivElement | null>(null);
- const handleStageRef = useCallback((ref: React.RefObject<HTMLDivElement | null>) => {
- stageRefForDrop.current = ref.current;
- }, []);
-
- // Authored composition size measured from the loaded preview — drives drop
- // coordinate mapping so blocks land where the user pointed on any comp size.
- const [previewCompositionSize, setPreviewCompositionSize] = useState<{
- width: number;
- height: number;
- } | null>(null);
-
- const {
- isDragOver: previewDragOver,
- handleDragEnter: handlePreviewDragEnter,
- handleDragOver: handlePreviewDragOver,
- handleDragLeave: handlePreviewDragLeave,
- handleDrop: handlePreviewDrop,
- } = usePreviewBlockDrop({
- portrait,
- compositionSize: previewCompositionSize,
- stageRef: stageRefForDrop as React.RefObject<HTMLDivElement | null>,
- onBlockDrop: onPreviewBlockDrop,
- });
-
- // Lightweight reload: change iframe src instead of destroying the Player.
- // refreshPlayer() saves the seek position and appends a cache-busting _t
- // param — the Player instance stays alive so the adapter is available for
- // saveSeekPosition() to read the current time before the reload.
- const prevRefreshKeyRef = useRef(refreshKey);
- useEffect(() => {
- if (refreshKey === prevRefreshKeyRef.current) return;
- prevRefreshKeyRef.current = refreshKey;
- refreshPlayer();
- }, [refreshKey, refreshPlayer]);
-
- const onIframeLoad = useCallback(() => {
- baseOnIframeLoad();
- // Pre-load + register MotionPathPlugin once so adding a motion path in the
- // studio doesn't take the async plugin-load flash path on the first soft
- // reload (the comp may not ship the plugin until it actually uses one).
- ensureMotionPathPluginLoaded(iframeRef.current);
- onIframeRef?.(iframeRef.current);
- }, [baseOnIframeLoad, iframeRef, onIframeRef]);
-
- const {
- compositionStack,
- updateCompositionStack,
- handleNavigateComposition,
- handleDrillDown: drillDown,
- masterSeekRef,
- compIdToSrc,
- setCompIdToSrc,
- } = useCompositionStack({
- projectId,
- activeCompositionPath,
- onCompositionChange,
- });
-
- // Wrap handleDrillDown to also scan the iframe DOM for data-composition-src
- const iframeRef_ = iframeRef;
- const handleDrillDown = useCallback(
- (element: TimelineElement) => {
- if (!element.compositionSrc) return;
- usePlayerStore.getState().setSelectedElementId(null);
- // Check compIdToSrc map first; then scan iframe DOM; then fall through to drillDown
- const compId = element.id;
- let resolvedPath = compIdToSrc.get(compId);
- if (!resolvedPath) {
- try {
- const doc = iframeRef_.current?.contentDocument;
- if (doc) {
- const host = doc.querySelector(
- `[data-composition-id="${CSS.escape(compId)}"][data-composition-src]`,
- );
- if (host) {
- resolvedPath = host.getAttribute("data-composition-src") || undefined;
- }
- }
- } catch {
- /* cross-origin */
- }
- }
- // Delegate with the resolved compositionSrc (may be same as original)
- drillDown({
- id: compId,
- compositionSrc: resolvedPath ?? element.compositionSrc,
- });
- },
- [compIdToSrc, drillDown, iframeRef_],
- );
-
- // Move/resize/split come from the timeline edit context, not props — the
- // wrappers below intercept expanded clips and must call the *real* handlers.
- // (Delete is a direct prop; it stays that way.)
- const { onMoveElement, onResizeElement, onSplitElement } = useTimelineEditContext();
-
- // An expanded sub-comp child reaches the normal edit handlers in its own
- // local coordinates: addressed by its real DOM id, with timeline time rebased
- // onto the sub-comp it lives in. The handlers then save + reloadPreview exactly
- // as they do for top-level clips — no separate live-DOM path.
- const toLocalElement = useCallback(
- (element: TimelineElement, basis: number): TimelineElement => ({
- ...element,
- id: element.domId ?? element.id,
- start: element.start - basis,
- }),
- [],
- );
-
- const handleMoveElement = useCallback(
- (element: TimelineElement, updates: Pick<TimelineElement, "start" | "track">) => {
- const basis = element.expandedParentStart;
- if (basis === undefined) return onMoveElement?.(element, updates);
- trackStudioExpandedClipEdit({ action: "move" });
- onMoveElement?.(toLocalElement(element, basis), {
- ...updates,
- start: Math.max(0, updates.start - basis),
- });
- },
- [onMoveElement, toLocalElement],
- );
-
- const handleResizeElement = useCallback(
- (
- element: TimelineElement,
- updates: Pick<TimelineElement, "start" | "duration" | "playbackStart">,
- ) => {
- const basis = element.expandedParentStart;
- if (basis === undefined) return onResizeElement?.(element, updates);
- trackStudioExpandedClipEdit({ action: "resize" });
- onResizeElement?.(toLocalElement(element, basis), {
- ...updates,
- start: Math.max(0, updates.start - basis),
- });
- },
- [onResizeElement, toLocalElement],
- );
-
- const handleDeleteElement = useCallback(
- (element: TimelineElement) => {
- const basis = element.expandedParentStart;
- if (basis === undefined) return onDeleteElement?.(element);
- trackStudioExpandedClipEdit({ action: "delete" });
- return onDeleteElement?.(toLocalElement(element, basis));
- },
- [onDeleteElement, toLocalElement],
- );
-
- const handleSplitElement = useCallback(
- (element: TimelineElement, splitTime: number) => {
- const basis = element.expandedParentStart;
- if (basis === undefined) return onSplitElement?.(element, splitTime);
- trackStudioExpandedClipEdit({ action: "split" });
- return onSplitElement?.(toLocalElement(element, basis), Math.max(0, splitTime - basis));
- },
- [onSplitElement, toLocalElement],
- );
-
- // Composition ID → file path map from raw index.html
- const compIdToSrcRef = useRef(compIdToSrc);
- compIdToSrcRef.current = compIdToSrc;
-
- useMountEffect(() => {
- fetch(`/api/projects/${projectId}/files/index.html`)
- .then((r) => {
- if (!r.ok) throw new Error(`HTTP ${r.status}`);
- return r.json();
- })
- .then((data: { content?: string }) => {
- const html = data.content || "";
- const map = new Map<string, string>();
- const re =
- /data-composition-id=["']([^"']+)["'][^>]*data-composition-src=["']([^"']+)["']|data-composition-src=["']([^"']+)["'][^>]*data-composition-id=["']([^"']+)["']/g;
- let match;
- while ((match = re.exec(html)) !== null) {
- const id = match[1] || match[4];
- const src = match[2] || match[3];
- if (id && src) map.set(id, src);
- }
- setCompIdToSrc(map);
- // Let DOM source-resolution recover a subcomposition element's source file
- // (the runtime drops the linkage when inlining — see getSourceFileForElement).
- setCompositionSourceMap(map);
- onCompIdToSrcChange?.(map);
- })
- .catch((err: unknown) => {
- // Non-fatal: drill-down still works via the iframe DOM scan; without
- // the map only source-file resolution for sub-comps degrades.
- console.warn("[studio] Couldn't load composition source map from index.html:", err);
- });
- });
-
- // Patch elements with compositionSrc whenever elements or compIdToSrc change.
- // eslint-disable-next-line no-restricted-syntax
- useEffect(() => {
- if (compIdToSrc.size === 0) return;
- const patchElements = (elements: TimelineElement[]): TimelineElement[] | null => {
- const map = compIdToSrcRef.current;
- if (map.size === 0) return null;
- let patched = false;
- const updated = elements.map((el) => {
- if (el.compositionSrc) return el;
- const src = map.get(el.id) ?? map.get(el.id.replace(/-(host|comp|layer)$/, ""));
- if (src) {
- patched = true;
- return { ...el, compositionSrc: src };
- }
- return el;
- });
- return patched ? updated : null;
- };
- const patched = patchElements(usePlayerStore.getState().elements);
- if (patched) usePlayerStore.getState().setElements(patched);
- let patching = false;
- return usePlayerStore.subscribe((state, prev) => {
- if (patching) return;
- if (state.elements === prev.elements || state.elements.length === 0) return;
- if (state.elements.every((el) => el.compositionSrc)) return;
- patching = true;
- const result = patchElements(state.elements);
- if (result) state.setElements(result);
- patching = false;
- });
- }, [compIdToSrc]);
-
- // Resizable timeline height — persisted alongside zoom/pan so the user's
- // workspace layout survives reloads.
- const [timelineH, setTimelineH] = useState(() => {
- const stored = readStudioUiPreferences().timelineHeight;
- return stored !== undefined && stored >= MIN_TIMELINE_H ? stored : DEFAULT_TIMELINE_H;
- });
- const persistTimelineH = useCallback((height: number) => {
- writeStudioUiPreferences({ timelineHeight: Math.round(height) });
- }, []);
- // A height persisted on a tall window can exceed this window's container and
- // collapse the flex-1 preview to 0px — clamp once the container is measurable
- // (the drag/keyboard paths already clamp; the restore path must too).
- useEffect(() => {
- const containerH = containerRef.current?.getBoundingClientRect().height;
- if (!containerH) return;
- const max = containerH - MIN_PREVIEW_H;
- setTimelineH((prev) => (prev > max ? Math.max(MIN_TIMELINE_H, max) : prev));
- }, []);
- const hasLoadedOnceRef = useRef(false);
- const [compositionLoading, setCompositionLoadingRaw] = useState(true);
- const setCompositionLoading = useCallback((loading: boolean) => {
- if (!loading) hasLoadedOnceRef.current = true;
- if (loading && hasLoadedOnceRef.current) return;
- setCompositionLoadingRaw(loading);
- }, []);
- const timelineDisabled = shouldDisableTimelineWhileCompositionLoading(compositionLoading);
-
- useEffect(() => {
- onCompositionLoadingChangeParent?.(compositionLoading);
- }, [compositionLoading, onCompositionLoadingChangeParent]);
-
- const fullscreenElement = useSyncExternalStore(subscribeFullscreen, getFullscreenElement);
- const isTimelineVisible = timelineVisible ?? true;
- const containerRef = useRef<HTMLDivElement>(null);
- const isFullscreen = fullscreenElement === containerRef.current && fullscreenElement != null;
-
- const toggleFullscreen = useCallback(() => {
- if (!containerRef.current) return;
- if (document.fullscreenElement) {
- void document.exitFullscreen();
- } else {
- void containerRef.current.requestFullscreen();
- }
- }, []);
-
- const currentLevel = compositionStack[compositionStack.length - 1];
- const directUrl = compositionStack.length > 1 ? currentLevel.previewUrl : undefined;
-
- const onIframeRefStable = useRef(onIframeRef);
- onIframeRefStable.current = onIframeRef;
- useEffect(() => {
- onIframeRefStable.current?.(iframeRef.current);
- }, [compositionStack.length, refreshKey, iframeRef]);
-
- // Keyboard: Escape to pop composition level
- const handleKeyDown = useCallback(
- (e: React.KeyboardEvent) => {
- if (e.key === "Escape" && compositionStack.length > 1) {
- updateCompositionStack((prev) => prev.slice(0, -1));
- }
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [compositionStack.length],
- );
-
- // Suppress TS unused-var warning for masterSeekRef (used inside useCompositionStack)
- void masterSeekRef;
-
- return (
- <div
- ref={containerRef}
- className="flex flex-col h-full min-h-0 bg-neutral-950"
- onKeyDown={handleKeyDown}
- tabIndex={-1}
- data-studio-fullscreen-target=""
- >
- {/* Preview + player controls */}
- <div className="flex-1 min-h-0 flex flex-col">
- <div
- className="flex-1 min-h-0 relative overflow-hidden"
- data-preview-pan-surface="true"
- onPointerDown={(e) => {
- const el = iframeRef.current?.parentElement ?? iframeRef.current;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- const inside =
- e.clientX >= rect.left &&
- e.clientX <= rect.right &&
- e.clientY >= rect.top &&
- e.clientY <= rect.bottom;
- if (!inside) onSelectTimelineElement?.(null);
- }}
- onDragEnter={handlePreviewDragEnter}
- onDragOver={handlePreviewDragOver}
- onDragLeave={handlePreviewDragLeave}
- onDrop={handlePreviewDrop}
- >
- <div className="absolute inset-0 overflow-hidden">
- <NLEPreview
- projectId={projectId}
- iframeRef={iframeRef}
- onIframeLoad={onIframeLoad}
- onCompositionLoadingChange={setCompositionLoading}
- portrait={portrait}
- directUrl={directUrl}
- suppressLoadingOverlay={hasLoadedOnceRef.current}
- onStageRef={handleStageRef}
- onCompositionSizeChange={setPreviewCompositionSize}
- />
- {previewDragOver && (
- <div className="absolute inset-2 z-40 rounded-lg border-2 border-dashed border-studio-accent/50 bg-studio-accent/[0.04] pointer-events-none" />
- )}
- </div>
- {!isFullscreen && previewOverlay}
- </div>
- <div className="bg-neutral-950 border-t border-neutral-800/50 flex-shrink-0">
- {!isFullscreen && compositionStack.length > 1 && (
- <CompositionBreadcrumb
- stack={compositionStack}
- onNavigate={handleNavigateComposition}
- />
- )}
- <PlayerControls
- onTogglePlay={togglePlay}
- onSeek={seek}
- disabled={timelineDisabled}
- isFullscreen={isFullscreen}
- onToggleFullscreen={toggleFullscreen}
- />
- </div>
- </div>
-
- {!isFullscreen && isTimelineVisible ? (
- <>
- <TimelineResizeDivider
- timelineH={timelineH}
- setTimelineH={setTimelineH}
- persistTimelineH={persistTimelineH}
- containerRef={containerRef}
- disabled={timelineDisabled}
- />
-
- {/* Timeline section */}
- <div
- className="relative flex flex-col flex-shrink-0"
- style={{ height: timelineH }}
- aria-disabled={timelineDisabled || undefined}
- >
- <div
- className="flex flex-col flex-1 min-h-0 overflow-hidden bg-neutral-950"
- onDoubleClick={(e) => {
- if ((e.target as HTMLElement).closest("[data-clip]")) return;
- if (timelineDisabled) return;
- if (compositionStack.length > 1) {
- updateCompositionStack((prev) => prev.slice(0, -1));
- }
- }}
- >
- <div className="flex-shrink-0">{timelineToolbar}</div>
- <Timeline
- onSeek={seek}
- onDrillDown={handleDrillDown}
- renderClipContent={renderClipContent}
- onFileDrop={onFileDrop}
- onDeleteElement={handleDeleteElement}
- onAssetDrop={onAssetDrop}
- onBlockDrop={onBlockDrop}
- onMoveElement={handleMoveElement}
- onResizeElement={handleResizeElement}
- onBlockedEditAttempt={onBlockedEditAttempt}
- onSplitElement={handleSplitElement}
- onSelectElement={onSelectTimelineElement}
- />
- </div>
- {timelineFooter && <div className="flex-shrink-0">{timelineFooter}</div>}
- {timelineDisabled && (
- <div
- className="absolute inset-0 z-30 cursor-not-allowed bg-black/18 flex items-center justify-center"
- data-testid="timeline-loading-disabled-overlay"
- role="status"
- onPointerDown={(event) => event.preventDefault()}
- onDragOver={(event) => event.preventDefault()}
- onDrop={(event) => event.preventDefault()}
- >
- <span className="rounded-md bg-neutral-900/90 px-2.5 py-1 text-[11px] text-neutral-400">
- Loading composition…
- </span>
- </div>
- )}
- </div>
- </>
- ) : !isFullscreen && onToggleTimeline ? (
- <div className="flex-shrink-0 border-t border-neutral-800/50 bg-neutral-950/96">
- <div className="flex h-10 items-center justify-between px-3">
- <div className="text-[10px] font-medium uppercase tracking-[0.16em] text-neutral-500">
- Timeline
- </div>
- <button
- type="button"
- onClick={onToggleTimeline}
- className="flex h-7 items-center gap-1.5 rounded-md border border-neutral-800 px-2.5 text-[11px] font-medium text-neutral-300 transition-colors hover:border-neutral-700 hover:bg-neutral-900 hover:text-neutral-100"
- title={getTimelineToggleTitle(false)}
- aria-label="Show timeline editor"
- >
- <svg
- width="13"
- height="13"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.7"
- strokeLinecap="round"
- strokeLinejoin="round"
- aria-hidden="true"
- >
- <rect x="3" y="13" width="18" height="8" rx="1" />
- <path d="M7 9h10" />
- <path d="M8 5h8" />
- </svg>
- <span>Show</span>
- <span className="hidden rounded bg-white/5 px-1 py-0.5 font-mono text-[9px] text-neutral-500 sm:inline">
- {TIMELINE_TOGGLE_SHORTCUT_LABEL}
- </span>
- </button>
- </div>
- </div>
- ) : null}
- </div>
- );
-});
diff --git a/packages/studio/src/components/nle/NLEPreview.tsx b/packages/studio/src/components/nle/NLEPreview.tsx
index 6c02dd6e05..8e634f7671 100644
--- a/packages/studio/src/components/nle/NLEPreview.tsx
+++ b/packages/studio/src/components/nle/NLEPreview.tsx
@@ -459,7 +459,7 @@ export const NLEPreview = memo(function NLEPreview({
<div className="flex flex-col h-full min-h-0">
<div
ref={viewportRef}
- className="relative flex-1 flex items-center justify-center p-2 overflow-hidden min-h-0 outline-none focus:ring-1 focus:ring-studio-accent/40 bg-neutral-700"
+ className="relative flex-1 flex items-center justify-center p-2 overflow-hidden min-h-0 outline-none focus:ring-1 focus:ring-studio-accent/40 bg-neutral-950"
tabIndex={0}
aria-label="Composition preview"
>
diff --git a/packages/studio/src/components/nle/PreviewOverlays.tsx b/packages/studio/src/components/nle/PreviewOverlays.tsx
new file mode 100644
index 0000000000..36b67748a3
--- /dev/null
+++ b/packages/studio/src/components/nle/PreviewOverlays.tsx
@@ -0,0 +1,240 @@
+import { useState } from "react";
+import { CaptionOverlay } from "../../captions/components/CaptionOverlay";
+import { DomEditOverlay } from "../editor/DomEditOverlay";
+import { MotionPathOverlay } from "../editor/MotionPathOverlay";
+import { SnapToolbar } from "../editor/SnapToolbar";
+import { useCompositionDimensions } from "../../hooks/useCompositionDimensions";
+import {
+ STUDIO_INSPECTOR_PANELS_ENABLED,
+ STUDIO_KEYFRAMES_ENABLED,
+ STUDIO_PREVIEW_MANUAL_EDITING_ENABLED,
+ STUDIO_PREVIEW_SELECTION_ENABLED,
+} from "../editor/manualEditingAvailability";
+import { useStudioPlaybackContext, useStudioShellContext } from "../../contexts/StudioContext";
+import {
+ useDomEditActionsContext,
+ useDomEditSelectionContext,
+} from "../../contexts/DomEditContext";
+import { readStudioUiPreferences } from "../../utils/studioUiPreferences";
+import { readHfId, type DomEditSelection } from "../editor/domEditing";
+import { buildStableSelector } from "../editor/domEditingDom";
+import type { BlockPreviewInfo } from "../sidebar/BlocksTab";
+import type { GestureRecordingState } from "../editor/GestureRecordControl";
+import type { ReactNode } from "react";
+
+export interface PreviewOverlaysProps {
+ shouldShowSelectedDomBounds: boolean;
+ blockPreview?: BlockPreviewInfo | null;
+ isGestureRecording?: boolean;
+ recordingState?: GestureRecordingState;
+ onToggleRecording?: () => void;
+ gestureOverlay?: ReactNode;
+}
+
+type ZIndexReorderEntry = {
+ element: HTMLElement;
+ zIndex: number;
+ id?: string;
+ selector?: string;
+ selectorIndex?: number;
+ sourceFile: string;
+};
+
+/** Can this element be robustly re-targeted for a persisted z change? */
+function canTargetZIndexElement(
+ element: HTMLElement,
+ id: string | undefined,
+ selector: string | undefined,
+): boolean {
+ return Boolean(id || selector || readHfId(element));
+}
+
+/** The selected element carries its full selection identity. */
+function selectedZIndexEntry(sel: DomEditSelection, zIndex: number): ZIndexReorderEntry {
+ return {
+ element: sel.element,
+ zIndex,
+ id: sel.id ?? undefined,
+ selector: sel.selector,
+ selectorIndex: sel.selectorIndex,
+ sourceFile: sel.sourceFile,
+ };
+}
+
+/**
+ * Sibling elements are raw iframe DOM nodes with no selection object: derive a
+ * PatchTarget from the node itself (siblings live in the same document, so they
+ * share the selection's sourceFile). Null when it cannot be robustly targeted
+ * (no id and no selector) — its z stays live-only.
+ */
+function siblingZIndexEntry(
+ element: HTMLElement,
+ zIndex: number,
+ sourceFile: string,
+): ZIndexReorderEntry | null {
+ const id = element.id || undefined;
+ const selector = buildStableSelector(element);
+ if (!canTargetZIndexElement(element, id, selector)) return null;
+ return { element, zIndex, id, selector, selectorIndex: undefined, sourceFile };
+}
+
+/** Short human-readable label for a dropped sibling, for the console warning below. */
+function describeZIndexElement(element: HTMLElement): string {
+ if (element.id) return `#${element.id}`;
+ const firstClass = element.classList.item(0);
+ return firstClass
+ ? `${element.tagName.toLowerCase()}.${firstClass}`
+ : element.tagName.toLowerCase();
+}
+
+// Resolve z-index patches into commit entries; a sibling with no stable
+// id/selector can't be written to source, so it is collected as a label for the
+// revert-on-reload warning instead.
+function resolveZIndexEntries(
+ sel: DomEditSelection,
+ patches: ReadonlyArray<{ element: HTMLElement; zIndex: number }>,
+): { entries: ZIndexReorderEntry[]; droppedLabels: string[] } {
+ const entries: ZIndexReorderEntry[] = [];
+ const droppedLabels: string[] = [];
+ for (const patch of patches) {
+ if (patch.element === sel.element) {
+ entries.push(selectedZIndexEntry(sel, patch.zIndex));
+ continue;
+ }
+ const entry = siblingZIndexEntry(patch.element, patch.zIndex, sel.sourceFile);
+ if (entry) entries.push(entry);
+ else droppedLabels.push(describeZIndexElement(patch.element));
+ }
+ return { entries, droppedLabels };
+}
+
+// fallow-ignore-next-line complexity
+export function PreviewOverlays({
+ shouldShowSelectedDomBounds,
+ blockPreview,
+ isGestureRecording,
+ recordingState,
+ onToggleRecording,
+ gestureOverlay,
+}: PreviewOverlaysProps) {
+ const { activeCompPath, previewIframeRef } = useStudioShellContext();
+ const { captionEditMode, compositionLoading, isPlaying } = useStudioPlaybackContext();
+ const compositionDimensions = useCompositionDimensions();
+
+ const { domEditHoverSelection, domEditSelection, domEditGroupSelections } =
+ useDomEditSelectionContext();
+ const {
+ handlePreviewCanvasMouseDown,
+ handlePreviewCanvasPointerMove,
+ handlePreviewCanvasPointerLeave,
+ applyDomSelection,
+ handleBlockedDomMove,
+ handleDomManualDragStart,
+ handleDomPathOffsetCommit,
+ handleDomGroupPathOffsetCommit,
+ handleDomBoxSizeCommit,
+ handleDomRotationCommit,
+ handleDomStyleCommit,
+ applyMarqueeSelection,
+ handleDomEditElementDelete,
+ handleDomZIndexReorderCommit,
+ } = useDomEditActionsContext();
+
+ // fallow-ignore-next-line complexity
+ const [snapPrefs, setSnapPrefs] = useState(() => {
+ const p = readStudioUiPreferences();
+ return {
+ snapEnabled: p.snapEnabled ?? true,
+ gridVisible: p.gridVisible ?? false,
+ gridSpacing: p.gridSpacing ?? 50,
+ snapToGrid: p.snapToGrid ?? false,
+ };
+ });
+
+ if (blockPreview) {
+ return (
+ <div className="absolute inset-0 z-30 bg-black pointer-events-none">
+ {blockPreview.videoUrl ? (
+ <video
+ src={blockPreview.videoUrl}
+ autoPlay
+ muted
+ loop
+ playsInline
+ className="w-full h-full object-contain"
+ />
+ ) : blockPreview.posterUrl ? (
+ <img
+ src={blockPreview.posterUrl}
+ alt={blockPreview.title}
+ className="w-full h-full object-contain"
+ />
+ ) : null}
+ </div>
+ );
+ }
+
+ if (captionEditMode) {
+ return <CaptionOverlay iframeRef={previewIframeRef} />;
+ }
+
+ if (!STUDIO_INSPECTOR_PANELS_ENABLED) return null;
+
+ return (
+ <>
+ <DomEditOverlay
+ iframeRef={previewIframeRef}
+ activeCompositionPath={activeCompPath}
+ hoverSelection={
+ STUDIO_PREVIEW_SELECTION_ENABLED && !captionEditMode && !compositionLoading && !isPlaying
+ ? domEditHoverSelection
+ : null
+ }
+ selection={shouldShowSelectedDomBounds ? domEditSelection : null}
+ groupSelections={shouldShowSelectedDomBounds ? domEditGroupSelections : []}
+ allowCanvasMovement={STUDIO_PREVIEW_MANUAL_EDITING_ENABLED && !isGestureRecording}
+ onCanvasMouseDown={handlePreviewCanvasMouseDown}
+ onCanvasPointerMove={handlePreviewCanvasPointerMove}
+ onCanvasPointerLeave={handlePreviewCanvasPointerLeave}
+ onSelectionChange={applyDomSelection}
+ onBlockedMove={handleBlockedDomMove}
+ onManualDragStart={handleDomManualDragStart}
+ onPathOffsetCommit={handleDomPathOffsetCommit}
+ onGroupPathOffsetCommit={handleDomGroupPathOffsetCommit}
+ onBoxSizeCommit={handleDomBoxSizeCommit}
+ onRotationCommit={handleDomRotationCommit}
+ onStyleCommit={handleDomStyleCommit}
+ onDeleteSelection={handleDomEditElementDelete}
+ onApplyZIndex={(sel, patches) => {
+ const { entries, droppedLabels } = resolveZIndexEntries(sel, patches);
+ if (droppedLabels.length > 0) {
+ // The optimistic z-index has already been applied live at this point —
+ // these siblings just won't be written to source, so they'll revert to
+ // their prior stacking order on the next reload with no other signal.
+ console.warn(
+ "[studio] z-index reorder: dropping sibling(s) with no stable id/selector " +
+ "(will revert on reload):",
+ droppedLabels.join(", "),
+ );
+ }
+ if (entries.length > 0) handleDomZIndexReorderCommit(entries);
+ }}
+ gridVisible={snapPrefs.gridVisible}
+ gridSpacing={snapPrefs.gridSpacing}
+ recordingState={recordingState}
+ onToggleRecording={onToggleRecording}
+ onMarqueeSelect={applyMarqueeSelection}
+ />
+ <SnapToolbar onSnapChange={setSnapPrefs} />
+ {STUDIO_KEYFRAMES_ENABLED && (
+ <MotionPathOverlay
+ iframeRef={previewIframeRef}
+ selection={shouldShowSelectedDomBounds ? domEditSelection : null}
+ compositionSize={compositionDimensions}
+ isPlaying={isPlaying}
+ />
+ )}
+ {gestureOverlay}
+ </>
+ );
+}
diff --git a/packages/studio/src/components/nle/PreviewPane.tsx b/packages/studio/src/components/nle/PreviewPane.tsx
new file mode 100644
index 0000000000..530f4ba95f
--- /dev/null
+++ b/packages/studio/src/components/nle/PreviewPane.tsx
@@ -0,0 +1,163 @@
+import { useCallback, useRef, useSyncExternalStore, type ReactNode } from "react";
+import { PlayerControls } from "../../player";
+import type { TimelineElement } from "../../player";
+import { NLEPreview } from "./NLEPreview";
+import { CompositionBreadcrumb } from "./CompositionBreadcrumb";
+import { usePreviewBlockDrop } from "./usePreviewBlockDrop";
+import { useNLEContext } from "./NLEContext";
+import { AssetPreviewOverlay } from "./AssetPreviewOverlay";
+
+function subscribeFullscreen(cb: () => void) {
+ document.addEventListener("fullscreenchange", cb);
+ return () => document.removeEventListener("fullscreenchange", cb);
+}
+
+function getFullscreenElement() {
+ return document.fullscreenElement;
+}
+
+// Clear the timeline selection when a pointer lands outside the composition
+// frame (clicks *inside* the frame are handled by the DOM-edit overlay).
+// fallow-ignore-next-line complexity
+function deselectIfPointerOutsideFrame(
+ e: React.PointerEvent,
+ iframe: HTMLIFrameElement | null,
+ onDeselect?: (element: null) => void,
+): void {
+ const el = iframe?.parentElement ?? iframe;
+ if (!el) return;
+ const rect = el.getBoundingClientRect();
+ const outside =
+ e.clientX < rect.left ||
+ e.clientX > rect.right ||
+ e.clientY < rect.top ||
+ e.clientY > rect.bottom;
+ if (outside) onDeselect?.(null);
+}
+
+export interface PreviewPaneProps {
+ portrait?: boolean;
+ /** Slot for overlays rendered on top of the preview (cursors, highlights, etc.) */
+ previewOverlay?: ReactNode;
+ onSelectTimelineElement?: (element: TimelineElement | null) => void;
+ onPreviewBlockDrop?: (
+ blockName: string,
+ position: { left: number; top: number },
+ ) => Promise<void> | void;
+}
+
+// fallow-ignore-next-line complexity
+export function PreviewPane({
+ portrait,
+ previewOverlay,
+ onSelectTimelineElement,
+ onPreviewBlockDrop,
+}: PreviewPaneProps) {
+ const {
+ projectId,
+ iframeRef,
+ togglePlay,
+ seek,
+ onIframeLoad,
+ compositionStack,
+ handleNavigateComposition,
+ setCompositionLoading,
+ timelineDisabled,
+ hasLoadedOnceRef,
+ previewCompositionSize,
+ setPreviewCompositionSize,
+ } = useNLEContext();
+
+ const stageRefForDrop = useRef<HTMLDivElement | null>(null);
+ const handleStageRef = useCallback((ref: React.RefObject<HTMLDivElement | null>) => {
+ stageRefForDrop.current = ref.current;
+ }, []);
+
+ const {
+ isDragOver: previewDragOver,
+ handleDragEnter: handlePreviewDragEnter,
+ handleDragOver: handlePreviewDragOver,
+ handleDragLeave: handlePreviewDragLeave,
+ handleDrop: handlePreviewDrop,
+ } = usePreviewBlockDrop({
+ portrait,
+ compositionSize: previewCompositionSize,
+ stageRef: stageRefForDrop as React.RefObject<HTMLDivElement | null>,
+ onBlockDrop: onPreviewBlockDrop,
+ });
+
+ // Preview-only fullscreen: fullscreen targets THIS pane's container, so the
+ // browser shows only the preview (sidebars + timeline are excluded naturally).
+ const containerRef = useRef<HTMLDivElement>(null);
+ const fullscreenElement = useSyncExternalStore(subscribeFullscreen, getFullscreenElement);
+ const isFullscreen = fullscreenElement === containerRef.current && fullscreenElement != null;
+
+ const toggleFullscreen = useCallback(() => {
+ if (!containerRef.current) return;
+ if (document.fullscreenElement) {
+ void document.exitFullscreen();
+ } else {
+ void containerRef.current.requestFullscreen();
+ }
+ }, []);
+
+ const currentLevel = compositionStack[compositionStack.length - 1];
+ const directUrl = compositionStack.length > 1 ? currentLevel.previewUrl : undefined;
+
+ return (
+ <div
+ ref={containerRef}
+ // Panel chrome (rounded border) is dropped in fullscreen so the preview
+ // fills the screen edge-to-edge.
+ className={`flex-1 min-h-0 flex flex-col overflow-hidden bg-neutral-950 ${
+ isFullscreen ? "" : "rounded-lg border border-neutral-800/50"
+ }`}
+ data-studio-fullscreen-target=""
+ >
+ <div
+ className="flex-1 min-h-0 relative overflow-hidden"
+ data-preview-pan-surface="true"
+ onPointerDown={(e) =>
+ deselectIfPointerOutsideFrame(e, iframeRef.current, onSelectTimelineElement)
+ }
+ onDragEnter={handlePreviewDragEnter}
+ onDragOver={handlePreviewDragOver}
+ onDragLeave={handlePreviewDragLeave}
+ onDrop={handlePreviewDrop}
+ >
+ <div className="absolute inset-0 overflow-hidden">
+ <NLEPreview
+ projectId={projectId}
+ iframeRef={iframeRef}
+ onIframeLoad={onIframeLoad}
+ onCompositionLoadingChange={setCompositionLoading}
+ portrait={portrait}
+ directUrl={directUrl}
+ suppressLoadingOverlay={hasLoadedOnceRef.current}
+ onStageRef={handleStageRef}
+ onCompositionSizeChange={setPreviewCompositionSize}
+ />
+ {previewDragOver && (
+ <div className="absolute inset-2 z-40 rounded-lg border-2 border-dashed border-studio-accent/50 bg-studio-accent/[0.04] pointer-events-none" />
+ )}
+ <AssetPreviewOverlay />
+ </div>
+ {!isFullscreen && previewOverlay}
+ </div>
+ {/* Transport row: no own background or border — the controls sit flat on
+ the preview panel's surface (CapCut-style). */}
+ <div className="flex-shrink-0">
+ {!isFullscreen && compositionStack.length > 1 && (
+ <CompositionBreadcrumb stack={compositionStack} onNavigate={handleNavigateComposition} />
+ )}
+ <PlayerControls
+ onTogglePlay={togglePlay}
+ onSeek={seek}
+ disabled={timelineDisabled}
+ isFullscreen={isFullscreen}
+ onToggleFullscreen={toggleFullscreen}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/packages/studio/src/components/nle/TimelinePane.test.ts b/packages/studio/src/components/nle/TimelinePane.test.ts
new file mode 100644
index 0000000000..e01813bc43
--- /dev/null
+++ b/packages/studio/src/components/nle/TimelinePane.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it, vi } from "vitest";
+import type { TimelineElement } from "../../player";
+import {
+ forwardRebasedTimelineMoveElements,
+ forwardRebasedTimelineResizeElements,
+} from "./TimelinePane";
+
+describe("TimelinePane move wrapper", () => {
+ it("rebases expanded edits and forwards track-insert as the third argument", async () => {
+ const onMoveElements = vi.fn().mockResolvedValue(undefined);
+ const element: TimelineElement = {
+ id: "expanded-a",
+ domId: "a",
+ tag: "div",
+ start: 12,
+ duration: 2,
+ track: 0,
+ expandedParentStart: 10,
+ };
+ await forwardRebasedTimelineMoveElements(
+ [{ element, updates: { start: 14, track: 2 } }],
+ "clip-lane-move:7",
+ "track-insert",
+ onMoveElements,
+ );
+ expect(onMoveElements).toHaveBeenCalledWith(
+ [
+ {
+ element: expect.objectContaining({ id: "a", start: 2 }),
+ updates: { start: 4, track: 2 },
+ },
+ ],
+ "clip-lane-move:7",
+ "track-insert",
+ );
+ });
+
+ it("forwards one rebased resize batch with the shared gesture key", async () => {
+ const onResizeElements = vi.fn().mockResolvedValue(undefined);
+ const element: TimelineElement = {
+ id: "expanded-a",
+ domId: "a",
+ tag: "div",
+ start: 12,
+ duration: 2,
+ track: 0,
+ expandedParentStart: 10,
+ };
+ await forwardRebasedTimelineResizeElements(
+ [{ element, start: 13, duration: 3 }],
+ { coalesceKey: "clip-group-resize:a:b" },
+ onResizeElements,
+ );
+ expect(onResizeElements).toHaveBeenCalledTimes(1);
+ expect(onResizeElements).toHaveBeenCalledWith(
+ [{ element: expect.objectContaining({ id: "a", start: 2 }), start: 3, duration: 3 }],
+ { coalesceKey: "clip-group-resize:a:b" },
+ );
+ });
+});
diff --git a/packages/studio/src/components/nle/TimelinePane.tsx b/packages/studio/src/components/nle/TimelinePane.tsx
new file mode 100644
index 0000000000..1b0b402eab
--- /dev/null
+++ b/packages/studio/src/components/nle/TimelinePane.tsx
@@ -0,0 +1,293 @@
+import { useCallback, type ReactNode } from "react";
+import { Timeline } from "../../player";
+import type { TimelineElement } from "../../player";
+import type { BlockedTimelineEditIntent } from "../../player/components/timelineEditing";
+import { TimelineResizeDivider } from "./TimelineResizeDivider";
+import { useTimelineEditContext } from "../../contexts/TimelineEditContext";
+import { trackStudioExpandedClipEdit } from "../../telemetry/events";
+import { useNLEContext } from "./NLEContext";
+import type { TimelineMoveOperation } from "../../hooks/timelineMoveAdapter";
+
+type TimelineMoveEdit = {
+ element: TimelineElement;
+ updates: Pick<TimelineElement, "start" | "track">;
+};
+
+export function forwardRebasedTimelineMoveElements(
+ edits: TimelineMoveEdit[],
+ coalesceKey: string | undefined,
+ operation: TimelineMoveOperation | undefined,
+ onMoveElements: (
+ edits: TimelineMoveEdit[],
+ coalesceKey?: string,
+ operation?: TimelineMoveOperation,
+ ) => Promise<void> | void,
+) {
+ return onMoveElements(
+ edits.map(({ element, updates }) => {
+ const basis = element.expandedParentStart;
+ if (basis === undefined) return { element, updates };
+ return {
+ element: { ...element, id: element.domId ?? element.id, start: element.start - basis },
+ updates: { ...updates, start: Math.max(0, updates.start - basis) },
+ };
+ }),
+ coalesceKey,
+ operation,
+ );
+}
+
+type TimelineResizeChange = {
+ element: TimelineElement;
+ start: number;
+ duration: number;
+ playbackStart?: number;
+};
+
+export function forwardRebasedTimelineResizeElements(
+ changes: TimelineResizeChange[],
+ options: { coalesceKey?: string } | undefined,
+ onResizeElements: (
+ changes: TimelineResizeChange[],
+ options?: { coalesceKey?: string },
+ ) => Promise<void> | void,
+) {
+ return onResizeElements(
+ changes.map((change) => {
+ const basis = change.element.expandedParentStart;
+ if (basis === undefined) return change;
+ return {
+ ...change,
+ element: {
+ ...change.element,
+ id: change.element.domId ?? change.element.id,
+ start: change.element.start - basis,
+ },
+ start: Math.max(0, change.start - basis),
+ };
+ }),
+ options,
+ );
+}
+
+export interface TimelinePaneProps {
+ /** Slot rendered above the timeline tracks (toolbar with split, delete, zoom) */
+ timelineToolbar?: ReactNode;
+ /** Slot rendered below the timeline tracks */
+ timelineFooter?: ReactNode;
+ /** Custom clip content renderer for timeline (thumbnails, waveforms, etc.) */
+ renderClipContent?: (
+ element: TimelineElement,
+ style: { clip: string; label: string },
+ ) => ReactNode;
+ onFileDrop?: (
+ files: File[],
+ placement?: Pick<TimelineElement, "start" | "track">,
+ ) => Promise<void> | void;
+ onDeleteElement?: (element: TimelineElement) => Promise<void> | void;
+ onAssetDrop?: (
+ assetPath: string,
+ placement: Pick<TimelineElement, "start" | "track">,
+ ) => Promise<void> | void;
+ onBlockDrop?: (
+ blockName: string,
+ placement: Pick<TimelineElement, "start" | "track">,
+ ) => Promise<void> | void;
+ onBlockedEditAttempt?: (element: TimelineElement, intent: BlockedTimelineEditIntent) => void;
+ onSelectTimelineElement?: (element: TimelineElement | null) => void;
+}
+
+// fallow-ignore-next-line complexity
+export function TimelinePane({
+ timelineToolbar,
+ timelineFooter,
+ renderClipContent,
+ onFileDrop,
+ onDeleteElement,
+ onAssetDrop,
+ onBlockDrop,
+ onBlockedEditAttempt,
+ onSelectTimelineElement,
+}: TimelinePaneProps) {
+ const {
+ seek,
+ handleDrillDown,
+ compositionStack,
+ updateCompositionStack,
+ timelineH,
+ setTimelineH,
+ persistTimelineH,
+ containerRef,
+ timelineDisabled,
+ } = useNLEContext();
+
+ // Move/resize/split come from the timeline edit context, not props — the
+ // wrappers below intercept expanded clips and must call the *real* handlers.
+ // (Delete is a direct prop; it stays that way.)
+ const { onMoveElement, onMoveElements, onResizeElement, onResizeElements, onSplitElement } =
+ useTimelineEditContext();
+
+ // An expanded sub-comp child reaches the normal edit handlers in its own
+ // local coordinates: addressed by its real DOM id, with timeline time rebased
+ // onto the sub-comp it lives in. The handlers then save + reloadPreview exactly
+ // as they do for top-level clips — no separate live-DOM path.
+ const toLocalElement = useCallback(
+ (element: TimelineElement, basis: number): TimelineElement => ({
+ ...element,
+ id: element.domId ?? element.id,
+ start: element.start - basis,
+ }),
+ [],
+ );
+
+ const handleMoveElement = useCallback(
+ (element: TimelineElement, updates: Pick<TimelineElement, "start" | "track">) => {
+ const basis = element.expandedParentStart;
+ if (basis === undefined) return onMoveElement?.(element, updates);
+ trackStudioExpandedClipEdit({ action: "move" });
+ onMoveElement?.(toLocalElement(element, basis), {
+ ...updates,
+ start: Math.max(0, updates.start - basis),
+ });
+ },
+ [onMoveElement, toLocalElement],
+ );
+
+ // Batched move (ripple / insert): rebase each expanded sub-comp child to its
+ // local coords, exactly as handleMoveElement does for a single clip.
+ const handleMoveElements = useCallback(
+ (
+ edits: Array<{ element: TimelineElement; updates: Pick<TimelineElement, "start" | "track"> }>,
+ coalesceKey?: string,
+ operation?: TimelineMoveOperation,
+ ) => {
+ // 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).
+ if (edits.some(({ element }) => element.expandedParentStart !== undefined)) {
+ trackStudioExpandedClipEdit({ action: "move" });
+ }
+ if (!onMoveElements) return;
+ return forwardRebasedTimelineMoveElements(edits, coalesceKey, operation, onMoveElements);
+ },
+ [onMoveElements],
+ );
+
+ const handleResizeElement = useCallback(
+ (
+ element: TimelineElement,
+ updates: Pick<TimelineElement, "start" | "duration" | "playbackStart">,
+ ) => {
+ const basis = element.expandedParentStart;
+ if (basis === undefined) return onResizeElement?.(element, updates);
+ trackStudioExpandedClipEdit({ action: "resize" });
+ onResizeElement?.(toLocalElement(element, basis), {
+ ...updates,
+ start: Math.max(0, updates.start - basis),
+ });
+ },
+ [onResizeElement, toLocalElement],
+ );
+
+ const handleResizeElements = useCallback(
+ (
+ changes: Array<{
+ element: TimelineElement;
+ start: number;
+ duration: number;
+ playbackStart?: number;
+ }>,
+ options?: { coalesceKey?: string },
+ ) => {
+ if (!onResizeElements) return;
+ if (changes.some(({ element }) => element.expandedParentStart !== undefined)) {
+ trackStudioExpandedClipEdit({ action: "resize" });
+ }
+ return forwardRebasedTimelineResizeElements(changes, options, onResizeElements);
+ },
+ [onResizeElements],
+ );
+
+ const handleDeleteElement = useCallback(
+ (element: TimelineElement) => {
+ const basis = element.expandedParentStart;
+ if (basis === undefined) return onDeleteElement?.(element);
+ trackStudioExpandedClipEdit({ action: "delete" });
+ return onDeleteElement?.(toLocalElement(element, basis));
+ },
+ [onDeleteElement, toLocalElement],
+ );
+
+ const handleSplitElement = useCallback(
+ (element: TimelineElement, splitTime: number) => {
+ const basis = element.expandedParentStart;
+ if (basis === undefined) return onSplitElement?.(element, splitTime);
+ trackStudioExpandedClipEdit({ action: "split" });
+ return onSplitElement?.(toLocalElement(element, basis), Math.max(0, splitTime - basis));
+ },
+ [onSplitElement, toLocalElement],
+ );
+
+ return (
+ <>
+ <TimelineResizeDivider
+ timelineH={timelineH}
+ setTimelineH={setTimelineH}
+ persistTimelineH={persistTimelineH}
+ containerRef={containerRef}
+ disabled={timelineDisabled}
+ />
+
+ {/* Timeline section — inner padding (not margin) keeps the divider's
+ height math exact while giving the panel a gap from the shell edges. */}
+ <div
+ className="relative flex flex-col flex-shrink-0 px-px pb-px"
+ style={{ height: timelineH }}
+ aria-disabled={timelineDisabled || undefined}
+ >
+ <div
+ className="flex flex-col flex-1 min-h-0 overflow-hidden rounded-lg border border-neutral-800/50 bg-neutral-950"
+ onDoubleClick={(e) => {
+ if ((e.target as HTMLElement).closest("[data-clip]")) return;
+ if (timelineDisabled) return;
+ if (compositionStack.length > 1) {
+ updateCompositionStack((prev) => prev.slice(0, -1));
+ }
+ }}
+ >
+ <div className="flex-shrink-0">{timelineToolbar}</div>
+ <Timeline
+ onSeek={seek}
+ onDrillDown={handleDrillDown}
+ renderClipContent={renderClipContent}
+ onFileDrop={onFileDrop}
+ onDeleteElement={handleDeleteElement}
+ onAssetDrop={onAssetDrop}
+ onBlockDrop={onBlockDrop}
+ onMoveElement={handleMoveElement}
+ onMoveElements={handleMoveElements}
+ onResizeElement={handleResizeElement}
+ onResizeElements={handleResizeElements}
+ onBlockedEditAttempt={onBlockedEditAttempt}
+ onSplitElement={handleSplitElement}
+ onSelectElement={onSelectTimelineElement}
+ />
+ </div>
+ {timelineFooter && <div className="flex-shrink-0">{timelineFooter}</div>}
+ {timelineDisabled && (
+ <div
+ className="absolute inset-0 z-30 cursor-not-allowed bg-black/18 flex items-center justify-center"
+ data-testid="timeline-loading-disabled-overlay"
+ role="status"
+ onPointerDown={(event) => event.preventDefault()}
+ onDragOver={(event) => event.preventDefault()}
+ onDrop={(event) => event.preventDefault()}
+ >
+ <span className="rounded-md bg-neutral-900/90 px-2.5 py-1 text-[11px] text-neutral-400">
+ Loading composition…
+ </span>
+ </div>
+ )}
+ </div>
+ </>
+ );
+}
diff --git a/packages/studio/src/components/nle/TimelineResizeDivider.tsx b/packages/studio/src/components/nle/TimelineResizeDivider.tsx
index d3bb1c84ee..fc27d76969 100644
--- a/packages/studio/src/components/nle/TimelineResizeDivider.tsx
+++ b/packages/studio/src/components/nle/TimelineResizeDivider.tsx
@@ -73,6 +73,9 @@ export function TimelineResizeDivider({
);
return (
+ // Horizontal resize divider: 3px visible seam (h-[3px]), 8px pointer-capture
+ // zone via the absolutely-positioned inner hit area so the layout gap stays
+ // at 3px while draggability is preserved over the full 8px band.
<div
role="separator"
aria-orientation="horizontal"
@@ -83,7 +86,7 @@ export function TimelineResizeDivider({
(containerRef.current?.getBoundingClientRect().height ?? 600) - MIN_PREVIEW_H,
)}
tabIndex={0}
- className="group h-2 flex-shrink-0 cursor-row-resize flex items-center justify-center z-10 outline-none focus-visible:bg-studio-accent/20"
+ className="group relative h-[3px] flex-shrink-0 cursor-row-resize z-10 outline-none focus-visible:bg-studio-accent/20"
style={{ touchAction: "none" }}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
@@ -91,7 +94,10 @@ export function TimelineResizeDivider({
onPointerCancel={handlePointerUp}
onKeyDown={handleKeyDown}
>
- <div className="h-px w-full bg-white/10 transition-colors group-hover:bg-white/16 group-active:bg-white/22 group-focus-visible:bg-studio-accent/60" />
+ {/* Expanded hit zone: 8px tall, centered on the 3px seam */}
+ <div className="absolute inset-x-0 -top-[2.5px] h-2" />
+ {/* Visible hairline — invisible at rest, subtle wash on hover/drag/focus */}
+ <div className="h-[3px] w-full bg-transparent transition-colors group-hover:bg-white/12 group-active:bg-white/18 group-focus-visible:bg-studio-accent/60" />
</div>
);
}
diff --git a/packages/studio/src/components/nle/useCompositionStack.test.tsx b/packages/studio/src/components/nle/useCompositionStack.test.tsx
new file mode 100644
index 0000000000..a3d300bc79
--- /dev/null
+++ b/packages/studio/src/components/nle/useCompositionStack.test.tsx
@@ -0,0 +1,44 @@
+// @vitest-environment happy-dom
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it } from "vitest";
+import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness";
+import { useCompositionStack } from "./useCompositionStack";
+
+installReactActEnvironment();
+
+describe("useCompositionStack — project scoping", () => {
+ afterEach(() => {
+ document.body.innerHTML = "";
+ });
+
+ for (const activeCompositionPath of [null, "index.html"] as const) {
+ it(`rebuilds the master preview URL on a project switch with ${String(activeCompositionPath)}`, async () => {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ let previewUrl = "";
+
+ function Harness(props: { projectId: string; activeCompositionPath: string | null }) {
+ previewUrl = useCompositionStack(props).compositionStack[0]?.previewUrl ?? "";
+ return null;
+ }
+
+ await act(async () => {
+ root.render(
+ <Harness projectId="project-a" activeCompositionPath={activeCompositionPath} />,
+ );
+ });
+ expect(previewUrl).toBe("/api/projects/project-a/preview");
+
+ await act(async () => {
+ root.render(
+ <Harness projectId="project-b" activeCompositionPath={activeCompositionPath} />,
+ );
+ });
+ expect(previewUrl).toBe("/api/projects/project-b/preview");
+
+ act(() => root.unmount());
+ });
+ }
+});
diff --git a/packages/studio/src/components/nle/useCompositionStack.ts b/packages/studio/src/components/nle/useCompositionStack.ts
index 5f7f7b8dcf..e210184637 100644
--- a/packages/studio/src/components/nle/useCompositionStack.ts
+++ b/packages/studio/src/components/nle/useCompositionStack.ts
@@ -1,7 +1,8 @@
-// Composition drill-down stack management for NLELayout
+// Composition drill-down stack management for NLEContext/EditorShell
import { useState, useCallback, useRef, useEffect } from "react";
import { usePlayerStore } from "../../player";
import type { CompositionLevel } from "./CompositionBreadcrumb";
+import { encodePreviewPath } from "../../player/components/thumbnailUtils";
interface UseCompositionStackOptions {
projectId: string;
@@ -25,7 +26,11 @@ export function useCompositionStack({
onCompositionChange,
}: UseCompositionStackOptions): UseCompositionStackResult {
const [compositionStack, setCompositionStack] = useState<CompositionLevel[]>([
- { id: "master", label: "Master", previewUrl: `/api/projects/${projectId}/preview` },
+ {
+ id: "master",
+ label: "Master",
+ previewUrl: `/api/projects/${projectId}/preview`,
+ },
]);
const onCompositionChangeRef = useRef(onCompositionChange);
@@ -84,7 +89,7 @@ export function useCompositionStack({
.split("/")
.pop()
?.replace(/\.html$/, "") || resolvedPath;
- const previewUrl = `/api/projects/${projectId}/preview/comp/${resolvedPath}`;
+ const previewUrl = `/api/projects/${projectId}/preview/comp/${encodePreviewPath(resolvedPath)}`;
return [...prev, { id: resolvedPath, label, previewUrl }];
});
},
@@ -95,22 +100,25 @@ export function useCompositionStack({
// Navigate to a composition when activeCompositionPath changes.
// eslint-disable-next-line no-restricted-syntax
useEffect(() => {
+ const master: CompositionLevel = {
+ id: "master",
+ label: "Master",
+ previewUrl: `/api/projects/${projectId}/preview`,
+ };
if (activeCompositionPath === "index.html") {
usePlayerStore.getState().setElements([]);
- updateCompositionStack((prev) => (prev.length > 1 ? [prev[0]] : prev));
+ updateCompositionStack([master]);
} else if (activeCompositionPath && activeCompositionPath.startsWith("compositions/")) {
const label = activeCompositionPath.replace(/^compositions\//, "").replace(/\.html$/, "");
- const previewUrl = `/api/projects/${projectId}/preview/comp/${activeCompositionPath}`;
+ const previewUrl = `/api/projects/${projectId}/preview/comp/${encodePreviewPath(activeCompositionPath)}`;
usePlayerStore.getState().setElements([]);
updateCompositionStack((prev) => {
if (prev[prev.length - 1]?.id === activeCompositionPath) return prev;
- return [
- { id: "master", label: "Master", previewUrl: `/api/projects/${projectId}/preview` },
- { id: activeCompositionPath, label, previewUrl },
- ];
+ return [master, { id: activeCompositionPath, label, previewUrl }];
});
} else if (!activeCompositionPath) {
usePlayerStore.getState().setElements([]);
+ updateCompositionStack([master]);
}
}, [activeCompositionPath, projectId, updateCompositionStack]);
diff --git a/packages/studio/src/components/nle/useTimelineEditCallbacks.ts b/packages/studio/src/components/nle/useTimelineEditCallbacks.ts
new file mode 100644
index 0000000000..ec6f9ff725
--- /dev/null
+++ b/packages/studio/src/components/nle/useTimelineEditCallbacks.ts
@@ -0,0 +1,217 @@
+import { useCallback, useMemo } from "react";
+import type { TimelineElement } from "../../player";
+import { usePlayerStore } from "../../player/store/playerStore";
+import type { BlockedTimelineEditIntent } from "../../player/components/timelineEditing";
+import type { TimelineEditCallbacks } from "../../player/components/timelineCallbacks";
+import { useStudioShellContext } from "../../contexts/StudioContext";
+import {
+ useDomEditActionsContext,
+ useDomEditSelectionContext,
+} from "../../contexts/DomEditContext";
+import { resolveTweenStart, resolveTweenDuration } from "../../utils/globalTimeCompiler";
+import { resolveClipTimingBasis } from "../../hooks/useGsapTweenCache";
+import { resolveKeyframeRetime } from "../editor/keyframeRetime";
+import type { TimelineMoveOperation } from "../../hooks/timelineMoveAdapter";
+
+export interface TimelineEditCallbackDeps {
+ handleTimelineElementMove: (
+ element: TimelineElement,
+ updates: Pick<TimelineElement, "start" | "track">,
+ ) => Promise<void> | void;
+ handleTimelineElementsMove: (
+ edits: Array<{ element: TimelineElement; updates: Pick<TimelineElement, "start" | "track"> }>,
+ coalesceKey?: string,
+ operation?: TimelineMoveOperation,
+ ) => Promise<void> | void;
+ handleTimelineElementResize: (
+ element: TimelineElement,
+ updates: Pick<TimelineElement, "start" | "duration" | "playbackStart">,
+ ) => Promise<void> | void;
+ handleTimelineGroupResize: NonNullable<TimelineEditCallbacks["onResizeElements"]>;
+ handleToggleTrackHidden: (track: number, hidden: boolean) => Promise<void> | void;
+ handleBlockedTimelineEdit: (element: TimelineElement, intent: BlockedTimelineEditIntent) => void;
+ handleTimelineElementSplit: (element: TimelineElement, splitTime: number) => Promise<void> | void;
+ handleRazorSplit: (element: TimelineElement, splitTime: number) => Promise<void> | void;
+ handleRazorSplitAll: (splitTime: number) => Promise<void> | void;
+}
+
+/**
+ * Builds the timeline edit callback bag (move/resize/split/razor plus the
+ * keyframe-diamond callbacks) provided to `<Timeline>` via TimelineEditProvider.
+ * The keyframe callbacks resolve the dragged diamond back to its GSAP anim id +
+ * tween-relative percentage, reading DOM-edit selection state from context.
+ */
+// fallow-ignore-next-line complexity
+export function useTimelineEditCallbacks({
+ handleTimelineElementMove,
+ handleTimelineElementsMove,
+ handleTimelineElementResize,
+ handleTimelineGroupResize,
+ handleToggleTrackHidden,
+ handleBlockedTimelineEdit,
+ handleTimelineElementSplit,
+ handleRazorSplit,
+ handleRazorSplitAll,
+}: TimelineEditCallbackDeps): TimelineEditCallbacks {
+ const { projectId, activeCompPath } = useStudioShellContext();
+ const { domEditSelection, selectedGsapAnimations } = useDomEditSelectionContext();
+ const {
+ handleGsapRemoveKeyframe,
+ handleGsapMoveKeyframeToPlayhead,
+ handleGsapMoveKeyframe,
+ handleGsapResizeKeyframedTween,
+ handleGsapUpdateMeta,
+ handleGsapAddKeyframe,
+ handleGsapConvertToKeyframes,
+ handleGsapRemoveAllKeyframes,
+ buildDomSelectionForTimelineElement,
+ } = useDomEditActionsContext();
+
+ // Resolve a timeline-diamond callback's clip-% to the keyframe's anim id + its
+ // tween-relative percentage (shared by the delete/move keyframe callbacks): the
+ // diamond reports a clip-% but the script ops key on the tween-%. Prefers the
+ // anim in the keyframe's property group, falling back to the first keyframed one.
+ const resolveKeyframeTarget = useCallback(
+ // fallow-ignore-next-line complexity
+ (pct: number): { animId: string; tweenPct: number } | null => {
+ const cached = usePlayerStore.getState().keyframeCache.get(domEditSelection?.id ?? "");
+ const kf = cached?.keyframes.find((k) => Math.abs(k.percentage - pct) < 0.2);
+ const group = kf?.propertyGroup;
+ const anim =
+ (group ? selectedGsapAnimations.find((a) => a.propertyGroup === group) : undefined) ??
+ selectedGsapAnimations.find((a) => a.keyframes);
+ return anim ? { animId: anim.id, tweenPct: kf?.tweenPercentage ?? pct } : null;
+ },
+ [domEditSelection?.id, selectedGsapAnimations],
+ );
+
+ return useMemo(
+ () => ({
+ onMoveElement: handleTimelineElementMove,
+ onMoveElements: handleTimelineElementsMove,
+ onResizeElement: handleTimelineElementResize,
+ onResizeElements: handleTimelineGroupResize,
+ onToggleTrackHidden: handleToggleTrackHidden,
+ onBlockedEditAttempt: handleBlockedTimelineEdit,
+ onSplitElement: handleTimelineElementSplit,
+ onRazorSplit: handleRazorSplit,
+ onRazorSplitAll: handleRazorSplitAll,
+ onDeleteAllKeyframes: () => {
+ // Hold the element where it is (collapse keyframes to a static set) rather
+ // than deleting the whole animation — deleting strands a stale GSAP base
+ // that the next drag adds to, flinging the element off-screen.
+ const anim = selectedGsapAnimations.find((a) => a.keyframes);
+ if (!anim) return;
+ handleGsapRemoveAllKeyframes(anim.id);
+ },
+ onDeleteKeyframe: (_elId: string, pct: number) => {
+ const target = resolveKeyframeTarget(pct);
+ if (target) handleGsapRemoveKeyframe(target.animId, target.tweenPct);
+ },
+ // Retime the keyframe to the playhead, preserving its value + ease.
+ onMoveKeyframeToPlayhead: (_elId: string, pct: number) => {
+ const target = resolveKeyframeTarget(pct);
+ if (target) handleGsapMoveKeyframeToPlayhead(target.animId, target.tweenPct);
+ },
+ // Drag-to-retime. The diamond reports clip-%s; resolveKeyframeTarget gives
+ // the dragged keyframe's anim + tween-%. We convert the clip-% drop to an
+ // absolute time (via the clip's timing basis) and let resolveKeyframeRetime
+ // decide: a drop inside the tween window is a plain move (re-key tween-%); a
+ // drop past the boundary (last keyframe past the end, first before the start)
+ // resizes the tween — position/duration grow so the dragged keyframe lands at
+ // the drop while every other keyframe keeps its absolute time (value+ease too).
+ // fallow-ignore-next-line complexity
+ onMoveKeyframe: (_elId: string, fromClipPct: number, toClipPct: number) => {
+ const target = resolveKeyframeTarget(fromClipPct);
+ const sel = domEditSelection;
+ if (!target || !sel) return;
+ const anim = selectedGsapAnimations.find((a) => a.id === target.animId);
+ const tweenStart = anim ? resolveTweenStart(anim) : null;
+ if (!anim || tweenStart === null) return;
+ const tweenDuration = anim.duration ?? resolveTweenDuration(anim);
+ const sourceFile = sel.sourceFile || activeCompPath || "index.html";
+ const { elements, domClipChildren } = usePlayerStore.getState();
+ const { elStart, elDuration } = resolveClipTimingBasis(
+ sel.id ?? "",
+ sourceFile,
+ elements,
+ domClipChildren,
+ );
+ const dropAbsTime = elStart + (toClipPct / 100) * elDuration;
+ const decision = resolveKeyframeRetime({
+ keyframes: anim.keyframes?.keyframes ?? [],
+ draggedTweenPct: target.tweenPct,
+ tweenStart,
+ tweenDuration,
+ dropAbsTime,
+ });
+ if (decision.kind === "move" && decision.toTweenPct != null) {
+ handleGsapMoveKeyframe(target.animId, target.tweenPct, decision.toTweenPct);
+ } else if (
+ decision.kind === "resize" &&
+ decision.pctRemap &&
+ decision.position != null &&
+ decision.duration != null
+ ) {
+ handleGsapResizeKeyframedTween(
+ target.animId,
+ decision.position,
+ decision.duration,
+ decision.pctRemap,
+ );
+ }
+ },
+ onChangeKeyframeEase: (_elId: string, _pct: number, ease: string) => {
+ for (const anim of selectedGsapAnimations) {
+ if (anim.keyframes) handleGsapUpdateMeta(anim.id, { ease });
+ }
+ },
+ // fallow-ignore-next-line complexity
+ onToggleKeyframeAtPlayhead: (el: TimelineElement) => {
+ const currentTime = usePlayerStore.getState().currentTime;
+ const pct =
+ el.duration > 0
+ ? Math.max(0, Math.min(100, Math.round(((currentTime - el.start) / el.duration) * 100)))
+ : 0;
+ const anim = selectedGsapAnimations.find((a) => a.keyframes);
+ if (anim?.keyframes) {
+ const existing = anim.keyframes.keyframes.find((k) => Math.abs(k.percentage - pct) <= 1);
+ if (existing) {
+ handleGsapRemoveKeyframe(anim.id, existing.percentage);
+ } else {
+ handleGsapAddKeyframe(anim.id, pct, "x", 0);
+ }
+ } else {
+ const flatAnim = selectedGsapAnimations.find((a) => !a.keyframes);
+ if (flatAnim) handleGsapConvertToKeyframes(flatAnim.id);
+ }
+ },
+ }),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [
+ handleTimelineElementMove,
+ handleTimelineElementsMove,
+ handleTimelineElementResize,
+ handleTimelineGroupResize,
+ handleToggleTrackHidden,
+ handleBlockedTimelineEdit,
+ handleTimelineElementSplit,
+ handleRazorSplit,
+ handleRazorSplitAll,
+ handleGsapRemoveAllKeyframes,
+ resolveKeyframeTarget,
+ selectedGsapAnimations,
+ handleGsapRemoveKeyframe,
+ handleGsapMoveKeyframeToPlayhead,
+ handleGsapMoveKeyframe,
+ handleGsapResizeKeyframedTween,
+ handleGsapUpdateMeta,
+ handleGsapAddKeyframe,
+ handleGsapConvertToKeyframes,
+ buildDomSelectionForTimelineElement,
+ projectId,
+ activeCompPath,
+ domEditSelection,
+ ],
+ );
+}
diff --git a/packages/studio/src/components/sidebar/AssetCard.tsx b/packages/studio/src/components/sidebar/AssetCard.tsx
new file mode 100644
index 0000000000..a083d34d25
--- /dev/null
+++ b/packages/studio/src/components/sidebar/AssetCard.tsx
@@ -0,0 +1,326 @@
+/**
+ * AssetCard and FontRow — visual asset tile / row components for the Assets panel.
+ * Extracted from AssetsTab.tsx to keep that file under the 600-line CI gate.
+ */
+import { useState, useEffect, useRef, useCallback } from "react";
+import { VideoFrameThumbnail } from "../ui/VideoFrameThumbnail";
+import { VIDEO_EXT, IMAGE_EXT } from "../../utils/mediaTypes";
+import { TIMELINE_ASSET_MIME } from "../../utils/timelineAssetDrop";
+import { ContextMenu } from "./AssetContextMenu";
+import { usePlayerStore } from "../../player/store/playerStore";
+import { useAssetPreviewStore } from "../../utils/assetPreviewStore";
+import { findClipForAsset, isPointerClick } from "../../utils/assetClickBehavior";
+import { basename, ext, truncateMiddle, formatDuration } from "./assetHelpers";
+import { resolveMediaPreviewUrl } from "../../player/components/thumbnailUtils";
+
+/** Drag payload writer shared by the asset tile and the font row: copy effect
+ * plus the timeline-asset MIME and a plain-text path fallback. */
+function writeAssetDragData(e: React.DragEvent, asset: string): void {
+ e.dataTransfer.effectAllowed = "copy";
+ e.dataTransfer.setData(TIMELINE_ASSET_MIME, JSON.stringify({ path: asset }));
+ e.dataTransfer.setData("text/plain", asset);
+}
+
+/** Open the row/tile context menu at the pointer, shared by asset tile + font row. */
+function openAssetContextMenu(
+ e: React.MouseEvent,
+ setContextMenu: (menu: { x: number; y: number }) => void,
+): void {
+ e.preventDefault();
+ setContextMenu({ x: e.clientX, y: e.clientY });
+}
+
+/**
+ * Lazily probe a video/audio URL for its duration via a hidden HTMLVideoElement
+ * (`preload="metadata"`). The manifest only covers ~/.media assets, so project
+ * assets in assets/ have no manifest entry — this fills the gap.
+ * Returns `undefined` until the probe completes; `null` if it failed.
+ */
+function useProbedDuration(src: string, skip: boolean): number | null | undefined {
+ const [duration, setDuration] = useState<number | null | undefined>(undefined);
+ useEffect(() => {
+ if (skip) return;
+ let cancelled = false;
+ let retryTimer: ReturnType<typeof setTimeout> | undefined;
+ // The in-flight probe element, so unmount cleanup can abort its network
+ // fetch (clearing `src`) instead of leaving it to finish in the background.
+ let liveVid: HTMLVideoElement | null = null;
+
+ function teardown(vid: HTMLVideoElement) {
+ vid.onloadedmetadata = null;
+ vid.onerror = null;
+ vid.src = "";
+ }
+
+ function probe(attempt: number) {
+ if (cancelled) return;
+ const vid = document.createElement("video");
+ liveVid = vid;
+ vid.preload = "metadata";
+ vid.muted = true;
+ vid.onloadedmetadata = () => {
+ const d = Number.isFinite(vid.duration) && vid.duration > 0 ? vid.duration : null;
+ teardown(vid);
+ if (!cancelled) setDuration(d);
+ };
+ vid.onerror = () => {
+ teardown(vid);
+ if (!cancelled) {
+ if (attempt < 1) retryTimer = setTimeout(() => probe(attempt + 1), 50);
+ else setDuration(null);
+ }
+ };
+ vid.src = src;
+ }
+
+ probe(0);
+ return () => {
+ cancelled = true;
+ if (retryTimer) clearTimeout(retryTimer);
+ if (liveVid) teardown(liveVid);
+ };
+ }, [src, skip]);
+ return duration;
+}
+
+export interface AssetCardProps {
+ projectId: string;
+ asset: string;
+ used: boolean;
+ duration?: number;
+ onCopy: (path: string) => void;
+ isCopied: boolean;
+ onDelete?: (path: string) => void;
+ onRename?: (oldPath: string, newPath: string) => void;
+ onAddAssetToTimeline?: (path: string) => void;
+}
+
+/**
+ * Thumbnail card for images and video assets. Renders in a 2-col grid.
+ *
+ * Click behaviour (CapCut-style):
+ * - Already added → selects the clip on the timeline (setSelectedElementId).
+ * - Not yet added → opens the asset preview overlay over the canvas.
+ * Drag behaviour is preserved: a pointer movement exceeding DRAG_THRESHOLD_PX
+ * before pointerup is treated as drag-start, not a click.
+ */
+// fallow-ignore-next-line complexity
+export function AssetCard({
+ projectId,
+ asset,
+ used,
+ duration,
+ onCopy,
+ isCopied,
+ onDelete,
+ onRename,
+ onAddAssetToTimeline,
+}: AssetCardProps) {
+ const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
+ const [hovered, setHovered] = useState(false);
+ const fullName = asset.split("/").pop() ?? asset;
+ const name = basename(asset);
+ const extension = ext(asset);
+ const serveUrl = resolveMediaPreviewUrl(asset, projectId);
+ const isVideo = VIDEO_EXT.test(asset);
+ const isImage = IMAGE_EXT.test(asset);
+ const probedDuration = useProbedDuration(serveUrl, !isVideo || duration != null);
+ const resolvedDuration = duration ?? probedDuration ?? undefined;
+ const durationLabel = formatDuration(resolvedDuration ?? 0);
+
+ // Drag-threshold click gate: track pointer-down position so we can ignore
+ // pointer-up events that followed a real drag gesture.
+ const pointerDownRef = useRef<{ x: number; y: number } | null>(null);
+
+ const setSelectedElementId = usePlayerStore((s) => s.setSelectedElementId);
+ const elements = usePlayerStore((s) => s.elements);
+ const setPreviewAsset = useAssetPreviewStore((s) => s.setPreviewAsset);
+
+ const handlePointerDown = useCallback((e: React.PointerEvent) => {
+ pointerDownRef.current = { x: e.clientX, y: e.clientY };
+ }, []);
+
+ const handlePointerUp = useCallback(
+ (e: React.PointerEvent) => {
+ const origin = pointerDownRef.current;
+ pointerDownRef.current = null;
+ if (!origin) return;
+ if (!isPointerClick(e.clientX - origin.x, e.clientY - origin.y)) return;
+ // Treat as click
+ if (used) {
+ const clip = findClipForAsset(elements, asset);
+ if (clip) {
+ setSelectedElementId(clip.key ?? clip.id);
+ return;
+ }
+ }
+ // Not added (or no matching clip found) → preview overlay
+ setPreviewAsset(asset, projectId);
+ },
+ [used, elements, asset, projectId, setSelectedElementId, setPreviewAsset],
+ );
+
+ return (
+ <>
+ <div
+ draggable
+ onPointerDown={handlePointerDown}
+ onPointerUp={handlePointerUp}
+ onDragStart={(e) => writeAssetDragData(e, asset)}
+ onContextMenu={(e) => openAssetContextMenu(e, setContextMenu)}
+ onPointerEnter={() => setHovered(true)}
+ onPointerLeave={() => setHovered(false)}
+ className={`flex flex-col gap-1 cursor-pointer rounded-md p-1 transition-colors ${
+ isCopied ? "bg-studio-accent/10" : "hover:bg-neutral-800/40"
+ }`}
+ >
+ {/* Thumbnail */}
+ <div className="w-full aspect-video rounded overflow-hidden bg-neutral-900 relative">
+ {isImage && (
+ <img
+ src={serveUrl}
+ alt={name}
+ loading="lazy"
+ className="w-full h-full object-cover"
+ onError={(e) => {
+ (e.target as HTMLImageElement).style.display = "none";
+ }}
+ />
+ )}
+ {isVideo && (
+ <>
+ <VideoFrameThumbnail src={serveUrl} />
+ {hovered && (
+ <video
+ src={serveUrl}
+ autoPlay
+ muted
+ loop
+ playsInline
+ className="absolute inset-0 w-full h-full object-cover"
+ />
+ )}
+ </>
+ )}
+ {!isImage && !isVideo && (
+ <div className="w-full h-full flex items-center justify-center">
+ <span className="text-[10px] font-medium text-neutral-600">{extension}</span>
+ </div>
+ )}
+
+ {/* "Added" badge — top-left */}
+ {used && (
+ <span className="absolute top-1 left-1 text-[9px] font-semibold leading-none px-1.5 py-[3px] rounded bg-neutral-950/80 text-panel-text-1">
+ Added
+ </span>
+ )}
+
+ {/* Duration badge — top-right, media only */}
+ {durationLabel && (
+ <span className="absolute top-1 right-1 text-[9px] font-medium leading-none px-1.5 py-[3px] rounded bg-neutral-950/80 text-panel-text-2 tabular-nums">
+ {durationLabel}
+ </span>
+ )}
+ </div>
+
+ {/* Filename caption */}
+ <span
+ className={`text-[10px] leading-tight text-center block w-full ${
+ used ? "text-panel-text-2" : "text-panel-text-4"
+ }`}
+ title={fullName}
+ >
+ {truncateMiddle(fullName, 22)}
+ </span>
+ </div>
+
+ {contextMenu && (
+ <ContextMenu
+ x={contextMenu.x}
+ y={contextMenu.y}
+ asset={asset}
+ onClose={() => setContextMenu(null)}
+ onCopy={onCopy}
+ onDelete={onDelete}
+ onRename={onRename}
+ onAddAtPlayhead={onAddAssetToTimeline}
+ />
+ )}
+ </>
+ );
+}
+
+export interface FontRowProps {
+ asset: string;
+ used: boolean;
+ onCopy: (path: string) => void;
+ isCopied: boolean;
+ onDelete?: (path: string) => void;
+ onRename?: (oldPath: string, newPath: string) => void;
+ onAddAssetToTimeline?: (path: string) => void;
+}
+
+/**
+ * Compact row for font assets (no meaningful thumbnail; show ext badge + name).
+ */
+export function FontRow({
+ asset,
+ used,
+ onCopy,
+ isCopied,
+ onDelete,
+ onRename,
+ onAddAssetToTimeline,
+}: FontRowProps) {
+ const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
+ const name = basename(asset);
+ const extension = ext(asset);
+
+ return (
+ <>
+ <div
+ draggable
+ onClick={() => onCopy(asset)}
+ onDragStart={(e) => writeAssetDragData(e, asset)}
+ onContextMenu={(e) => openAssetContextMenu(e, setContextMenu)}
+ className={`px-2.5 py-1.5 flex items-center gap-2.5 cursor-pointer transition-colors ${
+ isCopied
+ ? "bg-studio-accent/10 border-l-2 border-studio-accent"
+ : "border-l-2 border-transparent hover:bg-neutral-800/50"
+ }`}
+ >
+ <div className="w-[50px] h-[32px] rounded overflow-hidden bg-neutral-900 flex-shrink-0 flex items-center justify-center">
+ <span className="text-[9px] font-medium text-neutral-700">{extension}</span>
+ </div>
+ <div className="min-w-0 flex-1">
+ <span
+ className={`text-xs font-medium truncate block ${used ? "text-panel-text-1" : "text-panel-text-3"}`}
+ >
+ {name}
+ </span>
+ <div className="flex items-center gap-1.5">
+ <span className="text-[10px] text-neutral-600 truncate">{extension}</span>
+ {used && (
+ <span className="text-[9px] font-medium text-panel-accent bg-panel-accent/10 px-1.5 py-px rounded">
+ in use
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {contextMenu && (
+ <ContextMenu
+ x={contextMenu.x}
+ y={contextMenu.y}
+ asset={asset}
+ onClose={() => setContextMenu(null)}
+ onCopy={onCopy}
+ onDelete={onDelete}
+ onRename={onRename}
+ onAddAtPlayhead={onAddAssetToTimeline}
+ />
+ )}
+ </>
+ );
+}
diff --git a/packages/studio/src/components/sidebar/AssetContextMenu.tsx b/packages/studio/src/components/sidebar/AssetContextMenu.tsx
index 07b5417a80..d4e2e187c4 100644
--- a/packages/studio/src/components/sidebar/AssetContextMenu.tsx
+++ b/packages/studio/src/components/sidebar/AssetContextMenu.tsx
@@ -6,6 +6,7 @@ export function ContextMenu({
onCopy,
onDelete,
onRename,
+ onAddAtPlayhead,
}: {
x: number;
y: number;
@@ -14,6 +15,7 @@ export function ContextMenu({
onCopy: (path: string) => void;
onDelete?: (path: string) => void;
onRename?: (oldPath: string, newPath: string) => void;
+ onAddAtPlayhead?: (path: string) => void;
}) {
return (
<div
@@ -28,6 +30,19 @@ export function ContextMenu({
className="absolute bg-neutral-900 border border-neutral-700 rounded-lg shadow-xl py-1 min-w-[140px] text-xs"
style={{ left: x, top: y }}
>
+ {onAddAtPlayhead && (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onAddAtPlayhead(asset);
+ onClose();
+ }}
+ className="w-full text-left px-3 py-1.5 text-neutral-300 hover:bg-neutral-800 transition-colors"
+ >
+ Add at playhead
+ </button>
+ )}
<button
onClick={(e) => {
e.stopPropagation();
@@ -65,33 +80,3 @@ export function ContextMenu({
</div>
);
}
-
-export function DeleteConfirm({
- name,
- onConfirm,
- onCancel,
-}: {
- name: string;
- onConfirm: () => void;
- onCancel: () => void;
-}) {
- return (
- <div className="px-2 py-1.5 bg-red-950/30 border-l-2 border-red-500 flex items-center justify-between gap-2">
- <span className="text-[10px] text-red-400 truncate">Delete {name}?</span>
- <div className="flex items-center gap-1 flex-shrink-0">
- <button
- onClick={onConfirm}
- className="px-2 py-0.5 text-[10px] rounded bg-red-600 text-white hover:bg-red-500 transition-colors"
- >
- Delete
- </button>
- <button
- onClick={onCancel}
- className="px-2 py-0.5 text-[10px] rounded text-neutral-400 hover:text-neutral-200 transition-colors"
- >
- Cancel
- </button>
- </div>
- </div>
- );
-}
diff --git a/packages/studio/src/components/sidebar/AssetsTab.test.ts b/packages/studio/src/components/sidebar/AssetsTab.test.ts
index 74b5c916e5..2ed54db44c 100644
--- a/packages/studio/src/components/sidebar/AssetsTab.test.ts
+++ b/packages/studio/src/components/sidebar/AssetsTab.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { filterByUsage, countUsage, deriveUsedPaths } from "./AssetsTab";
+import { truncateMiddle, formatDuration } from "./assetHelpers";
import { globalAssetRows } from "./GlobalAssetsView";
const assets = ["bgm.mp3", "logo.png", "orphan.wav"];
@@ -47,6 +48,39 @@ describe("deriveUsedPaths", () => {
"assets/logo.png",
]);
});
+
+ it("handles fully-absolute URLs produced by the core runtime (toAbsoluteAssetUrl)", () => {
+ // The runtime calls new URL(raw, document.baseURI).toString() which produces
+ // "http://localhost:3012/api/projects/demo/preview/assets/clip.mp4"
+ const used = deriveUsedPaths([
+ { src: "http://localhost:3012/api/projects/demo/preview/assets/clip.mp4" },
+ { src: "http://localhost:3012/api/projects/abc123/preview/assets/logo.png" },
+ ]);
+ expect(used.has("assets/clip.mp4")).toBe(true);
+ expect(used.has("assets/logo.png")).toBe(true);
+ expect(used.size).toBe(2);
+ });
+
+ it("decodes percent-encoded filenames (spaces, parens) so they match the asset list", () => {
+ // Files with spaces/parens: "assets/my file (1).mp4" authored in HTML
+ // → runtime resolves to "http://…/assets/my%20file%20(1).mp4"
+ const used = deriveUsedPaths([
+ { src: "http://localhost:3012/api/projects/p/preview/assets/my%20file%20(1).mp4" },
+ { src: "/api/projects/p/preview/assets/track%20one.mp3" },
+ ]);
+ expect(used.has("assets/my file (1).mp4")).toBe(true);
+ expect(used.has("assets/track one.mp3")).toBe(true);
+ expect(used.size).toBe(2);
+ });
+
+ it("round-trips: absolute URL with spaces matches filterByUsage against plain asset list", () => {
+ const used = deriveUsedPaths([
+ { src: "http://localhost:3012/api/projects/demo/preview/assets/my%20video.mp4" },
+ ]);
+ expect(filterByUsage(["assets/my video.mp4", "assets/other.png"], used, "used")).toEqual([
+ "assets/my video.mp4",
+ ]);
+ });
});
describe("countUsage", () => {
@@ -59,6 +93,68 @@ describe("countUsage", () => {
});
});
+describe("truncateMiddle", () => {
+ it("returns the original string when it fits within maxLen", () => {
+ expect(truncateMiddle("short.mp4", 20)).toBe("short.mp4");
+ expect(truncateMiddle("exact_length_str.mp4", 20)).toBe("exact_length_str.mp4");
+ });
+
+ it("truncates longer strings with an ellipsis in the middle", () => {
+ const result = truncateMiddle("2a37eabf-long-uuid-887d8.mp4", 20);
+ expect(result.length).toBeLessThanOrEqual(20);
+ expect(result).toContain("…");
+ // Preserves head
+ expect(result.startsWith("2a37eabf-long-uuid-8")).toBe(false); // head is shortened
+ expect(result.startsWith("2a37eabf")).toBe(true);
+ // Preserves tail
+ expect(result.endsWith("887d8.mp4")).toBe(false); // tail portion only
+ expect(result.endsWith(".mp4")).toBe(true);
+ });
+
+ it("preserves the full filename extension in the tail", () => {
+ const result = truncateMiddle("verylongnamehere12345.mp4", 14);
+ expect(result.endsWith(".mp4")).toBe(true);
+ expect(result.length).toBeLessThanOrEqual(14);
+ });
+
+ it("handles maxLen of 1 (degenerate)", () => {
+ const result = truncateMiddle("abcdef", 1);
+ // head = 0, tail = 0 → just the ellipsis
+ expect(result).toBe("…");
+ });
+
+ it("handles a string of exactly maxLen+1 chars", () => {
+ const result = truncateMiddle("abcdefgh", 7);
+ expect(result.length).toBeLessThanOrEqual(7);
+ expect(result).toContain("…");
+ });
+});
+
+describe("formatDuration", () => {
+ it("formats whole seconds as MM:SS", () => {
+ expect(formatDuration(28)).toBe("00:28");
+ expect(formatDuration(60)).toBe("01:00");
+ expect(formatDuration(90)).toBe("01:30");
+ expect(formatDuration(3661)).toBe("61:01");
+ });
+
+ it("rounds fractional seconds to nearest whole", () => {
+ expect(formatDuration(28.4)).toBe("00:28");
+ expect(formatDuration(28.6)).toBe("00:29");
+ });
+
+ it("returns empty string for non-positive values", () => {
+ expect(formatDuration(0)).toBe("");
+ expect(formatDuration(-1)).toBe("");
+ });
+
+ it("returns empty string for non-finite values", () => {
+ expect(formatDuration(NaN)).toBe("");
+ expect(formatDuration(Infinity)).toBe("");
+ expect(formatDuration(-Infinity)).toBe("");
+ });
+});
+
describe("globalAssetRows", () => {
const recs = [
{ id: "bgm_001", type: "bgm", description: "calm ambient" },
diff --git a/packages/studio/src/components/sidebar/AssetsTab.tsx b/packages/studio/src/components/sidebar/AssetsTab.tsx
index fb99cc3765..e1344c88e6 100644
--- a/packages/studio/src/components/sidebar/AssetsTab.tsx
+++ b/packages/studio/src/components/sidebar/AssetsTab.tsx
@@ -1,21 +1,12 @@
// fallow-ignore-file code-duplication
import { memo, useState, useCallback, useRef, useMemo, useEffect } from "react";
-import { VideoFrameThumbnail } from "../ui/VideoFrameThumbnail";
-import { MEDIA_EXT, IMAGE_EXT, VIDEO_EXT, FONT_EXT } from "../../utils/mediaTypes";
-import { TIMELINE_ASSET_MIME } from "../../utils/timelineAssetDrop";
+import { MEDIA_EXT, FONT_EXT } from "../../utils/mediaTypes";
import { copyTextToClipboard } from "../../utils/clipboard";
-import { ContextMenu } from "./AssetContextMenu";
import { usePlayerStore } from "../../player/store/playerStore";
-import {
- type MediaCategory,
- getCategory,
- basename,
- ext,
- CATEGORY_LABELS,
- FILTER_ORDER,
-} from "./assetHelpers";
+import { type MediaCategory, getCategory, CATEGORY_LABELS, FILTER_ORDER } from "./assetHelpers";
import { AudioRow } from "./AudioRow";
import { GlobalAssetsView } from "./GlobalAssetsView";
+import { AssetCard, FontRow } from "./AssetCard";
interface AssetsTabProps {
projectId: string;
@@ -23,155 +14,7 @@ interface AssetsTabProps {
onImport?: (files: FileList) => void;
onDelete?: (path: string) => void;
onRename?: (oldPath: string, newPath: string) => void;
-}
-
-// fallow-ignore-next-line complexity
-function ImageCard({
- projectId,
- asset,
- used,
- onCopy,
- isCopied,
- onDelete,
- onRename,
- size,
-}: {
- projectId: string;
- asset: string;
- used: boolean;
- onCopy: (path: string) => void;
- isCopied: boolean;
- onDelete?: (path: string) => void;
- onRename?: (oldPath: string, newPath: string) => void;
- size: "large" | "small";
-}) {
- const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
- const [hovered, setHovered] = useState(false);
- const name = basename(asset);
- const extension = ext(asset);
- const serveUrl = `/api/projects/${projectId}/preview/${asset}`;
- const isVideo = VIDEO_EXT.test(asset);
- const isImage = IMAGE_EXT.test(asset);
-
- const thumbW = size === "large" ? "w-full" : "w-[50px]";
- const thumbH = size === "large" ? "h-[100px]" : "h-[32px]";
-
- return (
- <>
- <div
- draggable
- onClick={() => onCopy(asset)}
- onDragStart={(e) => {
- e.dataTransfer.effectAllowed = "copy";
- e.dataTransfer.setData(TIMELINE_ASSET_MIME, JSON.stringify({ path: asset }));
- e.dataTransfer.setData("text/plain", asset);
- }}
- onContextMenu={(e) => {
- e.preventDefault();
- setContextMenu({ x: e.clientX, y: e.clientY });
- }}
- onPointerEnter={() => setHovered(true)}
- onPointerLeave={() => setHovered(false)}
- className={`transition-colors cursor-pointer ${
- size === "large"
- ? `px-2.5 py-1 ${isCopied ? "bg-studio-accent/10" : "hover:bg-neutral-800/30"}`
- : `px-2.5 py-1.5 flex items-center gap-2.5 ${
- isCopied
- ? "bg-studio-accent/10 border-l-2 border-studio-accent"
- : "border-l-2 border-transparent hover:bg-neutral-800/50"
- }`
- }`}
- >
- {size === "large" ? (
- <div className="flex flex-col gap-1">
- <div className={`${thumbW} ${thumbH} rounded overflow-hidden bg-neutral-900 relative`}>
- {isImage && (
- <img
- src={serveUrl}
- alt={name}
- loading="lazy"
- className="w-full h-full object-cover"
- onError={(e) => {
- (e.target as HTMLImageElement).style.display = "none";
- }}
- />
- )}
- {isVideo && <VideoFrameThumbnail src={serveUrl} />}
- {isVideo && hovered && (
- <video
- src={serveUrl}
- autoPlay
- muted
- loop
- playsInline
- className="absolute inset-0 w-full h-full object-cover"
- />
- )}
- </div>
- <div className="flex items-center gap-1.5">
- <span
- className={`text-xs font-medium truncate ${used ? "text-panel-text-1" : "text-panel-text-3"}`}
- >
- {name}
- </span>
- <span className="text-[10px] text-neutral-600">{extension}</span>
- {used && (
- <span className="text-[9px] font-medium text-panel-accent bg-panel-accent/10 px-1.5 py-px rounded">
- in use
- </span>
- )}
- </div>
- </div>
- ) : (
- <>
- <div className="w-[50px] h-[32px] rounded overflow-hidden bg-neutral-900 flex-shrink-0 flex items-center justify-center">
- {isImage && (
- <img
- src={serveUrl}
- alt={name}
- loading="lazy"
- className="w-full h-full object-cover"
- onError={(e) => {
- (e.target as HTMLImageElement).style.display = "none";
- }}
- />
- )}
- {!isImage && (
- <span className="text-[9px] font-medium text-neutral-700">{extension}</span>
- )}
- </div>
- <div className="min-w-0 flex-1">
- <span
- className={`text-xs font-medium truncate block ${used ? "text-panel-text-1" : "text-panel-text-3"}`}
- >
- {name}
- </span>
- <div className="flex items-center gap-1.5">
- <span className="text-[10px] text-neutral-600 truncate">{extension}</span>
- {used && (
- <span className="text-[9px] font-medium text-panel-accent bg-panel-accent/10 px-1.5 py-px rounded">
- in use
- </span>
- )}
- </div>
- </div>
- </>
- )}
- </div>
-
- {contextMenu && (
- <ContextMenu
- x={contextMenu.x}
- y={contextMenu.y}
- asset={asset}
- onClose={() => setContextMenu(null)}
- onCopy={onCopy}
- onDelete={onDelete}
- onRename={onRename}
- />
- )}
- </>
- );
+ onAddAssetToTimeline?: (path: string) => void;
}
export type UsageFilter = "all" | "used" | "unused";
@@ -200,20 +43,48 @@ export function countUsage(
/**
* Project-relative asset paths referenced by composition elements — the set the
* "in use" badge, used-first sort, and usage filter all key on. Element src is
- * the raw authored value (timelineElementHelpers sets entry.src =
- * getAttribute("src")), so it can be a relative path ("assets/x.png"), a
- * "./"-prefixed path, the served "/api/projects/<id>/preview/assets/x.png" form,
- * or carry a ?query — normalize all of them to the bare project path so they
- * match the asset-list entries. Pure — unit-tested.
+ * populated from the core runtime's `resolveNodeAssetUrl` which calls
+ * `new URL(raw, document.baseURI).toString()`, turning authored relative paths
+ * into fully-absolute URLs with percent-encoded characters, e.g.
+ * "assets/my file (1).mp4"
+ * → "http://localhost:3012/api/projects/demo/preview/assets/my%20file%20(1).mp4"
+ *
+ * This function normalizes every src shape to the bare project-relative path so
+ * it matches the asset-list entries:
+ * - Absolute URL → strip origin + /api/projects/<id>/preview/ prefix, decode %XX
+ * - Server-relative /api/…preview/… → same strip + decode
+ * - Relative "./"-prefixed or bare → strip leading ./ or /
+ * - ?query / #hash → dropped
+ *
+ * Pure — unit-tested.
*/
export function deriveUsedPaths(elements: Array<{ src?: string }>): Set<string> {
const paths = new Set<string>();
for (const el of elements) {
if (!el.src) continue;
- const s = el.src
+ let s = el.src;
+
+ // Strip absolute origin if present (http://host/path → /path)
+ try {
+ const u = new URL(s);
+ s = u.pathname + (u.search ? u.search : "") + (u.hash ? u.hash : "");
+ } catch {
+ // Not a valid absolute URL — leave as-is (relative path)
+ }
+
+ s = s
.replace(/^\/api\/projects\/[^/]+\/preview\//, "") // strip the dev serve prefix
.replace(/^\.?\//, "") // strip leading ./ or /
.split(/[?#]/)[0]; // drop query / hash
+
+ // Decode percent-encoded characters (spaces, parens, etc.) so the path
+ // matches the plain-text asset-list entries the server returns.
+ try {
+ s = decodeURIComponent(s);
+ } catch {
+ // Malformed encoding — use as-is
+ }
+
if (s) paths.add(s);
}
return paths;
@@ -225,6 +96,7 @@ export const AssetsTab = memo(function AssetsTab({
onImport,
onDelete,
onRename,
+ onAddAssetToTimeline,
}: AssetsTabProps) {
const fileInputRef = useRef<HTMLInputElement>(null);
const [dragOver, setDragOver] = useState(false);
@@ -232,17 +104,11 @@ export const AssetsTab = memo(function AssetsTab({
const [activeFilter, setActiveFilter] = useState<MediaCategory | "all">("all");
const [usageFilter, setUsageFilter] = useState<"all" | "used" | "unused">("all");
const [searchQuery, setSearchQuery] = useState("");
- // Cross-project view: the global media-use cache (~/.media). The view itself
- // (GlobalAssetsView) owns its fetch — AssetsTab only tracks which scope is active.
const [viewMode, setViewMode] = useState<"local" | "global">("local");
const [manifest, setManifest] = useState<
Map<string, { description?: string; duration?: number; width?: number; height?: number }>
>(new Map());
- // Projects whose media manifest 404'd — most don't have one. Cache the miss so
- // we don't re-fetch (and spam the console) on every re-render; the effect was
- // also keyed on the `assets` array reference, which changes each render, so it
- // re-fired constantly. Key on a stable join + skip known-missing manifests.
const manifest404Ref = useRef<Set<string>>(new Set());
const assetsKey = assets.join("|");
useEffect(() => {
@@ -278,7 +144,6 @@ export const AssetsTab = memo(function AssetsTab({
cancelled = true;
};
}, [projectId, assetsKey]);
-
const handleDrop = useCallback(
(e: React.DragEvent) => {
e.preventDefault();
@@ -287,7 +152,6 @@ export const AssetsTab = memo(function AssetsTab({
},
[onImport],
);
-
const handleCopyPath = useCallback(async (path: string) => {
const copied = await copyTextToClipboard(path);
if (copied) {
@@ -295,22 +159,27 @@ export const AssetsTab = memo(function AssetsTab({
setTimeout(() => setCopiedPath(null), 1500);
}
}, []);
-
const elements = usePlayerStore((s) => s.elements);
const usedPaths = useMemo(() => deriveUsedPaths(elements), [elements]);
-
const mediaAssets = useMemo(() => {
const media = assets.filter((a) => MEDIA_EXT.test(a) || FONT_EXT.test(a));
const all = filterByUsage(media, usedPaths, usageFilter);
if (!searchQuery) return all;
const q = searchQuery.toLowerCase();
return all.filter((a) => {
- if (basename(a).toLowerCase().includes(q)) return true;
+ if (
+ a
+ .split("/")
+ .pop()
+ ?.replace(/\.[^.]*$/, "")
+ .toLowerCase()
+ .includes(q)
+ )
+ return true;
const rec = manifest.get(a);
return rec?.description?.toLowerCase().includes(q);
});
}, [assets, searchQuery, manifest, usageFilter, usedPaths]);
-
const categorized = useMemo(() => {
const groups: Record<MediaCategory, string[]> = { audio: [], images: [], video: [], fonts: [] };
for (const a of mediaAssets) {
@@ -327,15 +196,11 @@ export const AssetsTab = memo(function AssetsTab({
}
return groups;
}, [mediaAssets, usedPaths]);
-
const counts = useMemo(() => {
const c: Record<string, number> = { all: mediaAssets.length };
for (const cat of FILTER_ORDER) c[cat] = categorized[cat].length;
return c;
}, [mediaAssets, categorized]);
-
- // Usage counts over the full media set (independent of the active usage filter,
- // so the chips don't show their own filtered totals).
const usageCounts = useMemo(
() =>
countUsage(
@@ -344,12 +209,10 @@ export const AssetsTab = memo(function AssetsTab({
),
[assets, usedPaths],
);
-
const visibleCategories =
activeFilter === "all"
? FILTER_ORDER.filter((c) => categorized[c].length > 0)
: [activeFilter as MediaCategory].filter((c) => categorized[c].length > 0);
-
return (
<div
className={`flex-1 flex flex-col min-h-0 transition-colors ${dragOver ? "bg-studio-accent/[0.05]" : ""}`}
@@ -362,7 +225,7 @@ export const AssetsTab = memo(function AssetsTab({
>
{/* Header — matches design panel Section pattern */}
<div className="px-4 pt-2.5 pb-1.5 flex-shrink-0">
- {/* Scope toggle — this project's assets vs the global media-use cache */}
+ {/* Scope toggle */}
<div className="flex gap-1 mb-2.5 p-0.5 rounded-md bg-panel-input">
{(["local", "global"] as const).map((m) => (
<button
@@ -447,7 +310,7 @@ export const AssetsTab = memo(function AssetsTab({
</div>
)}
- {/* Filter chips — panel-input style (local view only) */}
+ {/* Filter chips */}
{viewMode === "local" && mediaAssets.length > 0 && (
<div className="flex gap-1.5 flex-wrap">
<button
@@ -475,7 +338,6 @@ export const AssetsTab = memo(function AssetsTab({
</button>
) : null,
)}
- {/* Usage filter — show only assets the composition references, or only the unused ones */}
{usageCounts.used > 0 && usageCounts.unused > 0 && (
<>
<span className="w-px self-stretch bg-panel-input mx-0.5" aria-hidden="true" />
@@ -505,7 +367,6 @@ export const AssetsTab = memo(function AssetsTab({
)}
</div>
- {/* Asset list */}
<div className="flex-1 overflow-y-auto mt-1">
{viewMode === "global" ? (
<GlobalAssetsView searchQuery={searchQuery} />
@@ -553,34 +414,38 @@ export const AssetsTab = memo(function AssetsTab({
isCopied={copiedPath === a}
onDelete={onDelete}
onRename={onRename}
+ onAddAssetToTimeline={onAddAssetToTimeline}
/>
))}
- {(cat === "images" || cat === "video") &&
- categorized[cat].map((a) => (
- <ImageCard
- key={a}
- projectId={projectId}
- asset={a}
- used={usedPaths.has(a)}
- onCopy={handleCopyPath}
- isCopied={copiedPath === a}
- onDelete={onDelete}
- onRename={onRename}
- size={categorized[cat].length <= 4 ? "large" : "small"}
- />
- ))}
+ {(cat === "images" || cat === "video") && (
+ <div className="grid grid-cols-2 gap-1 px-2 pb-1">
+ {categorized[cat].map((a) => (
+ <AssetCard
+ key={a}
+ projectId={projectId}
+ asset={a}
+ used={usedPaths.has(a)}
+ duration={manifest.get(a)?.duration}
+ onCopy={handleCopyPath}
+ isCopied={copiedPath === a}
+ onDelete={onDelete}
+ onRename={onRename}
+ onAddAssetToTimeline={onAddAssetToTimeline}
+ />
+ ))}
+ </div>
+ )}
{cat === "fonts" &&
categorized[cat].map((a) => (
- <ImageCard
+ <FontRow
key={a}
- projectId={projectId}
asset={a}
used={usedPaths.has(a)}
onCopy={handleCopyPath}
isCopied={copiedPath === a}
onDelete={onDelete}
onRename={onRename}
- size="small"
+ onAddAssetToTimeline={onAddAssetToTimeline}
/>
))}
</div>
diff --git a/packages/studio/src/components/sidebar/AudioRow.tsx b/packages/studio/src/components/sidebar/AudioRow.tsx
index 4c9b442d31..445ea6732d 100644
--- a/packages/studio/src/components/sidebar/AudioRow.tsx
+++ b/packages/studio/src/components/sidebar/AudioRow.tsx
@@ -2,6 +2,10 @@ import { useState, useRef, useEffect, useCallback } from "react";
import { ContextMenu } from "./AssetContextMenu";
import { basename, getAudioSubtype } from "./assetHelpers";
import { TIMELINE_ASSET_MIME } from "../../utils/timelineAssetDrop";
+import { usePlayerStore } from "../../player/store/playerStore";
+import { useAssetPreviewStore } from "../../utils/assetPreviewStore";
+import { findClipForAsset, isPointerClick } from "../../utils/assetClickBehavior";
+import { resolveMediaPreviewUrl } from "../../player/components/thumbnailUtils";
export function AudioRow({
projectId,
@@ -12,6 +16,7 @@ export function AudioRow({
isCopied,
onDelete,
onRename,
+ onAddAssetToTimeline,
}: {
projectId: string;
asset: string;
@@ -21,6 +26,7 @@ export function AudioRow({
isCopied: boolean;
onDelete?: (path: string) => void;
onRename?: (oldPath: string, newPath: string) => void;
+ onAddAssetToTimeline?: (path: string) => void;
}) {
const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
const [playing, setPlaying] = useState(false);
@@ -32,7 +38,36 @@ export function AudioRow({
const animRef = useRef<number>(0);
const name = basename(asset);
const subtype = getAudioSubtype(asset);
- const serveUrl = `/api/projects/${projectId}/preview/${asset}`;
+ const serveUrl = resolveMediaPreviewUrl(asset, projectId);
+
+ // CapCut-style click behavior: drag-threshold gate.
+ const pointerDownRef = useRef<{ x: number; y: number } | null>(null);
+ const setSelectedElementId = usePlayerStore((s) => s.setSelectedElementId);
+ const elements = usePlayerStore((s) => s.elements);
+ const setPreviewAsset = useAssetPreviewStore((s) => s.setPreviewAsset);
+
+ const handlePointerDown = useCallback((e: React.PointerEvent) => {
+ pointerDownRef.current = { x: e.clientX, y: e.clientY };
+ }, []);
+
+ const handlePointerUp = useCallback(
+ (e: React.PointerEvent) => {
+ const origin = pointerDownRef.current;
+ pointerDownRef.current = null;
+ if (!origin) return;
+ if (!isPointerClick(e.clientX - origin.x, e.clientY - origin.y)) return;
+ if (used) {
+ const clip = findClipForAsset(elements, asset);
+ if (clip) {
+ setSelectedElementId(clip.key ?? clip.id);
+ return;
+ }
+ }
+ // Not added → preview overlay (audio player)
+ setPreviewAsset(asset, projectId);
+ },
+ [used, elements, asset, projectId, setSelectedElementId, setPreviewAsset],
+ );
useEffect(() => {
return () => {
@@ -109,7 +144,8 @@ export function AudioRow({
<>
<div
draggable
- onClick={() => onCopy(asset)}
+ onPointerDown={handlePointerDown}
+ onPointerUp={handlePointerUp}
onDragStart={(e) => {
e.dataTransfer.effectAllowed = "copy";
e.dataTransfer.setData(TIMELINE_ASSET_MIME, JSON.stringify({ path: asset }));
@@ -195,6 +231,7 @@ export function AudioRow({
onCopy={onCopy}
onDelete={onDelete}
onRename={onRename}
+ onAddAtPlayhead={onAddAssetToTimeline}
/>
)}
</>
diff --git a/packages/studio/src/components/sidebar/BlocksTab.tsx b/packages/studio/src/components/sidebar/BlocksTab.tsx
index c94807f1a6..6b4c27eec8 100644
--- a/packages/studio/src/components/sidebar/BlocksTab.tsx
+++ b/packages/studio/src/components/sidebar/BlocksTab.tsx
@@ -10,6 +10,7 @@ import {
import { usePlayerStore } from "../../player";
import { formatTime } from "../../player/lib/time";
import { useStudioShellContext } from "../../contexts/StudioContext";
+import { TIMELINE_BLOCK_MIME } from "../../utils/timelineAssetDrop";
export interface BlockPreviewInfo {
videoUrl?: string;
posterUrl?: string;
@@ -383,10 +384,16 @@ function BlockCard({
return (
<div
className="group/card rounded-md overflow-hidden cursor-pointer transition-colors bg-neutral-900 hover:bg-neutral-800"
+ draggable
+ onDragStart={(e) => {
+ e.dataTransfer.effectAllowed = "copy";
+ e.dataTransfer.setData(TIMELINE_BLOCK_MIME, JSON.stringify({ name }));
+ e.dataTransfer.setData("text/plain", name);
+ handleLeave(); // cancel the hover-preview timer so it doesn't fire mid-drag
+ }}
onPointerEnter={handleEnter}
onPointerLeave={handleLeave}
>
- {/* Thumbnail */}
<div className="aspect-video w-full overflow-hidden relative">
{hovered && videoUrl ? (
<video
diff --git a/packages/studio/src/components/sidebar/LeftSidebar.tsx b/packages/studio/src/components/sidebar/LeftSidebar.tsx
index 2ca8b4120f..acaed6cda6 100644
--- a/packages/studio/src/components/sidebar/LeftSidebar.tsx
+++ b/packages/studio/src/components/sidebar/LeftSidebar.tsx
@@ -60,6 +60,7 @@ interface LeftSidebarProps {
onAddBlock?: (blockName: string) => void;
onPreviewBlock?: (preview: BlockPreviewInfo | null) => void;
takeoverContent?: ReactNode;
+ onAddAssetToTimeline?: (path: string) => void;
}
export const LeftSidebar = memo(
@@ -92,6 +93,7 @@ export const LeftSidebar = memo(
onAddBlock,
onPreviewBlock,
takeoverContent,
+ onAddAssetToTimeline,
},
ref,
) {
@@ -111,7 +113,7 @@ export const LeftSidebar = memo(
return (
<div
- className="flex flex-col h-full bg-neutral-950 border-r border-neutral-800/50"
+ className="flex flex-col h-full overflow-hidden rounded-lg border border-neutral-800/50 bg-neutral-950"
style={{ width }}
>
{takeoverContent ? (
@@ -230,6 +232,7 @@ export const LeftSidebar = memo(
onImport={onImportFiles}
onDelete={onDeleteFile}
onRename={onRenameFile}
+ onAddAssetToTimeline={onAddAssetToTimeline}
/>
)}
{tab === "code" && (
diff --git a/packages/studio/src/components/sidebar/assetHelpers.ts b/packages/studio/src/components/sidebar/assetHelpers.ts
index 069c47491c..b60bd4cac5 100644
--- a/packages/studio/src/components/sidebar/assetHelpers.ts
+++ b/packages/studio/src/components/sidebar/assetHelpers.ts
@@ -30,6 +30,35 @@ export function ext(path: string): string {
return dot > 0 ? name.slice(dot + 1).toUpperCase() : "";
}
+/**
+ * Truncate a string to at most `maxLen` chars, preserving the start and end.
+ * Middle characters are replaced with an ellipsis. If the string is short
+ * enough it is returned unchanged.
+ *
+ * @example truncateMiddle("2a37eabf-long-uuid-887d8.mp4", 20) → "2a37eabf-…887d8.mp4"
+ *
+ * Pure — unit-tested.
+ */
+export function truncateMiddle(str: string, maxLen: number): string {
+ if (str.length <= maxLen) return str;
+ const keep = maxLen - 1; // 1 char for ellipsis
+ const tail = Math.floor(keep / 3);
+ const head = keep - tail;
+ return str.slice(0, head) + "…" + str.slice(str.length - tail);
+}
+
+/**
+ * Format a duration in seconds as MM:SS. Returns an empty string for
+ * non-positive, NaN, or Infinity values. Pure — unit-tested.
+ */
+export function formatDuration(seconds: number): string {
+ if (!Number.isFinite(seconds) || seconds <= 0) return "";
+ const total = Math.round(seconds);
+ const m = Math.floor(total / 60);
+ const s = total % 60;
+ return `${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
+}
+
export const CATEGORY_LABELS: Record<MediaCategory, string> = {
audio: "Audio",
images: "Images",
diff --git a/packages/studio/src/contexts/DomEditContext.tsx b/packages/studio/src/contexts/DomEditContext.tsx
index 927df7ef82..bd1593efef 100644
--- a/packages/studio/src/contexts/DomEditContext.tsx
+++ b/packages/studio/src/contexts/DomEditContext.tsx
@@ -98,6 +98,15 @@ export function useDomEditActionsContext(): DomEditActionsValue {
return ctx;
}
+/**
+ * Optional access — returns null outside a provider. Lets the player-package
+ * <Timeline> (a public standalone export) reach the z-order persist path when
+ * embedded in the NLE without hard-requiring the provider in standalone/test mounts.
+ */
+export function useDomEditActionsContextOptional(): DomEditActionsValue | null {
+ return useContext(DomEditActionsContext);
+}
+
export function useDomEditSelectionContext(): DomEditSelectionValue {
const ctx = useContext(DomEditSelectionContext);
if (!ctx) throw new Error("useDomEditSelectionContext must be used within DomEditProvider");
diff --git a/packages/studio/src/contexts/StudioContext.tsx b/packages/studio/src/contexts/StudioContext.tsx
index a2d0ffa942..7c7e35b617 100644
--- a/packages/studio/src/contexts/StudioContext.tsx
+++ b/packages/studio/src/contexts/StudioContext.tsx
@@ -31,8 +31,6 @@ export interface StudioShellValue {
compositionDimensions: CompositionDimensions | null;
waitForPendingDomEditSaves: () => Promise<void>;
handlePreviewIframeRef: (iframe: HTMLIFrameElement | null) => void;
- timelineVisible: boolean;
- toggleTimelineVisibility: () => void;
}
export interface StudioPlaybackValue {
@@ -56,6 +54,15 @@ export function useStudioShellContext(): StudioShellValue {
return ctx;
}
+/**
+ * Optional access — returns null outside a provider. Lets the player-package
+ * <Timeline> (a public standalone export) read shell state when embedded in the
+ * NLE without hard-requiring the provider in standalone/test mounts.
+ */
+export function useStudioShellContextOptional(): StudioShellValue | null {
+ return useContext(StudioShellContext);
+}
+
export function useStudioPlaybackContext(): StudioPlaybackValue {
const ctx = useContext(StudioPlaybackContext);
if (!ctx) throw new Error("useStudioPlaybackContext must be used within StudioPlaybackProvider");
@@ -90,8 +97,6 @@ export function StudioShellProvider({
compositionDimensions,
waitForPendingDomEditSaves,
handlePreviewIframeRef,
- timelineVisible,
- toggleTimelineVisibility,
} = value;
const stable = useMemo<StudioShellValue>(
@@ -108,14 +113,11 @@ export function StudioShellProvider({
compositionDimensions,
waitForPendingDomEditSaves,
handlePreviewIframeRef,
- timelineVisible,
- toggleTimelineVisibility,
}),
[
projectId,
activeCompPath,
compositionDimensions,
- timelineVisible,
editHistory,
renderQueue,
setActiveCompPath,
@@ -125,7 +127,6 @@ export function StudioShellProvider({
handleRedo,
waitForPendingDomEditSaves,
handlePreviewIframeRef,
- toggleTimelineVisibility,
],
);
return <StudioShellContext value={stable}>{children}</StudioShellContext>;
diff --git a/packages/studio/src/contexts/TimelineEditContext.tsx b/packages/studio/src/contexts/TimelineEditContext.tsx
index bfc47c6bd7..c2b6edc6ce 100644
--- a/packages/studio/src/contexts/TimelineEditContext.tsx
+++ b/packages/studio/src/contexts/TimelineEditContext.tsx
@@ -10,7 +10,7 @@ export function useTimelineEditContext(): TimelineEditCallbacks {
}
/**
- * Optional access, returns an empty object when outside a provider.
+ * Optional access — returns an empty object when outside a provider.
* Useful in components that can render both inside and outside the NLE.
*/
export function useTimelineEditContextOptional(): TimelineEditCallbacks {
@@ -26,18 +26,14 @@ export function TimelineEditProvider({
}) {
const memoized = useMemo(
() => value,
- // Each callback is a stable reference from the parent, memoize the bag
+ // Each callback is a stable reference from the parent — memoize the bag
// so consumers don't re-render when unrelated parent state changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
[
value.onMoveElement,
- value.onResizeElement,
value.onMoveElements,
- value.onResizeElements,
- value.onPreviewMoveElements,
- value.onPreviewResizeElements,
+ value.onResizeElement,
value.onToggleTrackHidden,
- value.onToggleElementHidden,
value.onBlockedEditAttempt,
value.onSplitElement,
value.onRazorSplit,
diff --git a/packages/studio/src/hooks/deleteSelectedKeyframes.ts b/packages/studio/src/hooks/deleteSelectedKeyframes.ts
new file mode 100644
index 0000000000..20d5c9ff0d
--- /dev/null
+++ b/packages/studio/src/hooks/deleteSelectedKeyframes.ts
@@ -0,0 +1,35 @@
+import { usePlayerStore } from "../player/store/playerStore";
+import { selectedKeyframePercentagesForElement } from "../utils/keyframeSelection";
+import type { CommitMutationOptions } from "./gsapScriptCommitTypes";
+
+let deleteKeyframesCommitCounter = 0;
+
+/**
+ * Remove the keyframes currently selected in the player store from the active
+ * element's GSAP animation. Reads selection lazily so it stays correct when
+ * invoked from a ref callback.
+ */
+export function deleteSelectedKeyframes(session: {
+ selectedGsapAnimations: readonly { id: string; keyframes?: unknown }[];
+ handleGsapRemoveKeyframe: (
+ animId: string,
+ pct: number,
+ options?: Partial<CommitMutationOptions>,
+ ) => void;
+}): void {
+ const { selectedKeyframes, selectedElementId } = usePlayerStore.getState();
+ const animation = session.selectedGsapAnimations.find((anim) => anim.keyframes);
+ if (!animation) return;
+ // Only the active element's keyframes; a stale cross-element selection must not delete here.
+ const percentages = selectedKeyframePercentagesForElement(selectedKeyframes, selectedElementId);
+ const coalesceOptions = {
+ coalesceKey: `delete-keyframes:${++deleteKeyframesCommitCounter}`,
+ coalesceMs: Number.POSITIVE_INFINITY,
+ };
+ for (const [index, pct] of percentages.entries()) {
+ session.handleGsapRemoveKeyframe(animation.id, pct, {
+ ...coalesceOptions,
+ ...(index === percentages.length - 1 ? { softReload: true } : { skipReload: true }),
+ });
+ }
+}
diff --git a/packages/studio/src/hooks/domEditCommitTypes.ts b/packages/studio/src/hooks/domEditCommitTypes.ts
index b55a18e32d..cfc73aefde 100644
--- a/packages/studio/src/hooks/domEditCommitTypes.ts
+++ b/packages/studio/src/hooks/domEditCommitTypes.ts
@@ -1,5 +1,15 @@
import type { DomEditSelection } from "../components/editor/domEditing";
-import type { PatchOperation } from "../utils/sourcePatcher";
+import type { PatchOperation, PatchTarget } from "../utils/sourcePatcher";
+
+export interface DomEditPatchBatch {
+ sourceFile: string;
+ patches: Array<{ target: PatchTarget; operations: PatchOperation[] }>;
+}
+
+export type CommitDomEditPatchBatches = (
+ batches: DomEditPatchBatch[],
+ options: { label: string; coalesceKey: string },
+) => Promise<void>;
export type PersistDomEditOperations = (
selection: DomEditSelection,
@@ -7,6 +17,7 @@ export type PersistDomEditOperations = (
options?: {
label?: string;
coalesceKey?: string;
+ coalesceMs?: number;
skipRefresh?: boolean;
prepareContent?: (html: string, sourceFile: string) => string;
shouldSave?: () => boolean;
diff --git a/packages/studio/src/hooks/domSelectionTestHarness.ts b/packages/studio/src/hooks/domSelectionTestHarness.ts
index 78810ca5c8..affd703311 100644
--- a/packages/studio/src/hooks/domSelectionTestHarness.ts
+++ b/packages/studio/src/hooks/domSelectionTestHarness.ts
@@ -1,5 +1,8 @@
// Shared harness helpers for selection hook tests (useDomSelection,
// usePreviewInteraction). Test-only module.
+import type React from "react";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
import type { DomEditSelection } from "../components/editor/domEditing";
export function installReactActEnvironment(): void {
@@ -9,6 +12,17 @@ export function installReactActEnvironment(): void {
});
}
+/** Mount a React element into a fresh detached host and return its root. */
+export function mountReactHarness(node: React.ReactElement): Root {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ act(() => {
+ root.render(node);
+ });
+ return root;
+}
+
export function makeSelection(label: string, element: HTMLElement): DomEditSelection {
return {
element,
diff --git a/packages/studio/src/hooks/gestureTransaction.test.ts b/packages/studio/src/hooks/gestureTransaction.test.ts
new file mode 100644
index 0000000000..3cc8e45530
--- /dev/null
+++ b/packages/studio/src/hooks/gestureTransaction.test.ts
@@ -0,0 +1,311 @@
+// @vitest-environment happy-dom
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { DomEditSelection } from "../components/editor/domEditingTypes";
+import { trackStudioEvent } from "../utils/studioTelemetry";
+import type { CommitMutation } from "./gsapScriptCommitTypes";
+import { isGestureTransactionCommit, runGestureTransaction } from "./gestureTransaction";
+
+vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() }));
+
+const trackStudioEventMock = vi.mocked(trackStudioEvent);
+
+function rect(x: number, y: number, width: number, height: number): DOMRect {
+ return { x, y, width, height } as DOMRect;
+}
+
+function runTwoMutationTransaction(
+ underlying: CommitMutation,
+ firstSelection: DomEditSelection,
+ secondSelection = firstSelection,
+): Promise<void> {
+ return runGestureTransaction({
+ element: firstSelection.element,
+ label: "Resize layer",
+ settle: vi.fn(),
+ persist: async (commit) => {
+ const commitMutation = commit(underlying);
+ await commitMutation(firstSelection, { type: "first" }, { label: "First" });
+ await commitMutation(secondSelection, { type: "last" }, { label: "Last", softReload: true });
+ },
+ restore: vi.fn(),
+ skipPixelAssert: true,
+ });
+}
+
+describe("runGestureTransaction", () => {
+ beforeEach(() => {
+ trackStudioEventMock.mockReset();
+ });
+
+ it("settles synchronously before persist reaches its first await", async () => {
+ const order: string[] = [];
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+
+ const transaction = runGestureTransaction({
+ element: document.createElement("div"),
+ label: "Resize layer",
+ settle: () => order.push("settle"),
+ persist: async () => {
+ order.push("persist");
+ await gate;
+ order.push("persisted");
+ },
+ restore: vi.fn(),
+ skipPixelAssert: true,
+ });
+
+ expect(order).toEqual(["settle", "persist"]);
+ release();
+ await transaction;
+ expect(order).toEqual(["settle", "persist", "persisted"]);
+ });
+
+ it("injects one coalesce key and reloads only the final mutation", async () => {
+ const element = document.createElement("div");
+ const selection = { element, id: "clip" } as DomEditSelection;
+ const underlying = vi.fn<CommitMutation>().mockResolvedValue(undefined);
+ const batch = vi.fn<NonNullable<CommitMutation["batch"]>>().mockResolvedValue(undefined);
+ underlying.batch = batch;
+ const now = vi.spyOn(performance, "now").mockReturnValueOnce(100).mockReturnValueOnce(112.6);
+
+ await runTwoMutationTransaction(underlying, selection);
+
+ expect(underlying).not.toHaveBeenCalled();
+ expect(batch).toHaveBeenCalledTimes(1);
+ const [calls, mergedOptions] = batch.mock.calls[0]!;
+ const firstOptions = calls[0]!.options;
+ const lastOptions = calls[1]!.options;
+ expect(calls.map(({ mutation }) => mutation)).toEqual([{ type: "first" }, { type: "last" }]);
+ expect(firstOptions.coalesceKey).toBe(lastOptions.coalesceKey);
+ expect(firstOptions.coalesceKey).toMatch(/^tx:Resize layer:\d+$/);
+ expect(firstOptions.coalesceMs).toBe(Number.POSITIVE_INFINITY);
+ expect(lastOptions.coalesceMs).toBe(Number.POSITIVE_INFINITY);
+ expect(firstOptions).toMatchObject({ skipReload: true });
+ expect(firstOptions.softReload).toBeUndefined();
+ expect(lastOptions).toMatchObject({ softReload: true });
+ expect(lastOptions.skipReload).toBeUndefined();
+ // The transaction owns the undo label — the per-mutation "First"/"Last"
+ // labels are overridden so the coalesced entry reads "Resize layer".
+ expect(firstOptions.label).toBe("Resize layer");
+ expect(lastOptions.label).toBe("Resize layer");
+ expect(mergedOptions).toMatchObject({
+ label: "Resize layer",
+ coalesceKey: firstOptions.coalesceKey,
+ coalesceMs: Number.POSITIVE_INFINITY,
+ softReload: true,
+ });
+ expect(mergedOptions.skipReload).toBeUndefined();
+ expect(trackStudioEventMock).toHaveBeenCalledWith("commit_transaction", {
+ label: "Resize layer",
+ mutation_count: 2,
+ reload_count: 1,
+ duration_ms: 13,
+ pixel_asserted: false,
+ });
+ now.mockRestore();
+ });
+
+ it("reports one reload when a batch collapses two softReload commits", async () => {
+ const element = document.createElement("div");
+ const selection = { element, id: "clip", sourceFile: "index.html" } as DomEditSelection;
+ const underlying = vi.fn<CommitMutation>().mockResolvedValue(undefined);
+ underlying.batch = vi.fn<NonNullable<CommitMutation["batch"]>>().mockResolvedValue(undefined);
+
+ // Both a resize's size and offset persists request softReload; the batch is
+ // one write and one reload, so telemetry must report reload_count 1, not 2.
+ await runGestureTransaction({
+ element,
+ label: "Resize layer",
+ settle: vi.fn(),
+ persist: async (commit) => {
+ const commitMutation = commit(underlying);
+ await commitMutation(selection, { type: "size" }, { label: "Resize", softReload: true });
+ await commitMutation(selection, { type: "offset" }, { label: "Move", softReload: true });
+ },
+ restore: vi.fn(),
+ skipPixelAssert: true,
+ });
+
+ expect(underlying.batch).toHaveBeenCalledTimes(1);
+ expect(trackStudioEventMock).toHaveBeenCalledWith(
+ "commit_transaction",
+ expect.objectContaining({ mutation_count: 2, reload_count: 1 }),
+ );
+ });
+
+ it("falls back to sequential dispatch when the commit has no batch capability", async () => {
+ const element = document.createElement("div");
+ const selection = { element, id: "clip" } as DomEditSelection;
+ const underlying = vi.fn<CommitMutation>().mockResolvedValue(undefined);
+
+ await runTwoMutationTransaction(underlying, selection);
+
+ expect(underlying).toHaveBeenCalledTimes(2);
+ expect(underlying.mock.calls[0]![2]).toMatchObject({ skipReload: true });
+ expect(underlying.mock.calls[1]![2]).toMatchObject({ softReload: true });
+ });
+
+ it("keeps a single mutation on the original commit path", async () => {
+ const element = document.createElement("div");
+ const selection = { element, id: "clip" } as DomEditSelection;
+ const underlying = vi.fn<CommitMutation>().mockResolvedValue(undefined);
+ const batch = vi.fn<NonNullable<CommitMutation["batch"]>>().mockResolvedValue(undefined);
+ underlying.batch = batch;
+
+ await runGestureTransaction({
+ element,
+ label: "Move layer",
+ settle: vi.fn(),
+ persist: async (commit) => {
+ await commit(underlying)(
+ selection,
+ { type: "update-property" },
+ { label: "Move", softReload: true },
+ );
+ },
+ restore: vi.fn(),
+ skipPixelAssert: true,
+ });
+
+ expect(underlying).toHaveBeenCalledTimes(1);
+ expect(batch).not.toHaveBeenCalled();
+ });
+
+ it("does not batch mutations for different source files", async () => {
+ const element = document.createElement("div");
+ const firstSelection = { element, id: "a", sourceFile: "a.html" } as DomEditSelection;
+ const secondSelection = { element, id: "b", sourceFile: "b.html" } as DomEditSelection;
+ const underlying = vi.fn<CommitMutation>().mockResolvedValue(undefined);
+ const batch = vi.fn<NonNullable<CommitMutation["batch"]>>().mockResolvedValue(undefined);
+ underlying.batch = batch;
+
+ await runTwoMutationTransaction(underlying, firstSelection, secondSelection);
+
+ expect(batch).not.toHaveBeenCalled();
+ expect(underlying).toHaveBeenCalledTimes(2);
+ });
+
+ it("identifies transaction-owned commit wrappers without marking their underlying commit", async () => {
+ const underlying = vi.fn<CommitMutation>().mockResolvedValue(undefined);
+ let wrapped: CommitMutation | null = null;
+
+ await runGestureTransaction({
+ element: document.createElement("div"),
+ label: "Move layer",
+ settle: vi.fn(),
+ persist: async (commit) => {
+ wrapped = commit(underlying);
+ },
+ restore: vi.fn(),
+ skipPixelAssert: true,
+ });
+
+ expect(isGestureTransactionCommit(underlying)).toBe(false);
+ expect(isGestureTransactionCommit(wrapped!)).toBe(true);
+ });
+
+ it("restores exactly once and rethrows a persist failure", async () => {
+ const error = new Error("persist failed with secret selector #private-layer");
+ error.name = "PersistenceError";
+ const restore = vi.fn();
+ const element = document.createElement("div");
+ const selection = { element, id: "clip" } as DomEditSelection;
+ const underlying = vi.fn<CommitMutation>().mockResolvedValue(undefined);
+
+ await expect(
+ runGestureTransaction({
+ element,
+ label: "Resize layer",
+ settle: vi.fn(),
+ persist: async (commit) => {
+ await commit(underlying)(selection, { type: "position" }, { label: "Position" });
+ throw error;
+ },
+ restore,
+ skipPixelAssert: true,
+ }),
+ ).rejects.toBe(error);
+ expect(restore).toHaveBeenCalledTimes(1);
+ expect(trackStudioEventMock).toHaveBeenCalledWith("commit_transaction_failed", {
+ label: "Resize layer",
+ mutation_count: 1,
+ error_name: "PersistenceError",
+ restore_ran: true,
+ });
+ const failureProperties = trackStudioEventMock.mock.calls.find(
+ ([event]) => event === "commit_transaction_failed",
+ )?.[1];
+ expect(JSON.stringify(failureProperties)).not.toContain(error.message);
+ expect(JSON.stringify(failureProperties)).not.toContain("#private-layer");
+ });
+
+ it("reports when persistence changes pixels", async () => {
+ const element = document.createElement("div");
+ const getRect = vi
+ .spyOn(element, "getBoundingClientRect")
+ .mockReturnValueOnce(rect(10.04, 20.05, 100.05, 80.05))
+ .mockReturnValueOnce(rect(11.19, 17.89, 100.29, 78.99));
+ const error = vi.spyOn(console, "error").mockImplementation(() => undefined);
+ const now = vi.spyOn(performance, "now").mockReturnValueOnce(50).mockReturnValueOnce(58.44);
+
+ await runGestureTransaction({
+ element,
+ label: "Resize layer",
+ settle: vi.fn(),
+ persist: async () => undefined,
+ restore: vi.fn(),
+ });
+
+ expect(getRect).toHaveBeenCalledTimes(2);
+ expect(error).toHaveBeenCalledWith(
+ "[hf-commit] persist changed pixels",
+ expect.objectContaining({
+ label: "Resize layer",
+ delta: expect.objectContaining({ x: expect.any(Number) }),
+ }),
+ );
+ expect(trackStudioEventMock).toHaveBeenCalledWith("commit_invariant_violation", {
+ label: "Resize layer",
+ delta_x: 1.2,
+ delta_y: -2.2,
+ delta_w: 0.2,
+ delta_h: -1.1,
+ mutation_count: 0,
+ reload_count: 0,
+ duration_ms: 8,
+ });
+ expect(trackStudioEventMock).toHaveBeenCalledWith(
+ "commit_transaction",
+ expect.objectContaining({ pixel_asserted: true }),
+ );
+ now.mockRestore();
+ error.mockRestore();
+ });
+
+ it("skips the pixel assertion for live position tweens", async () => {
+ const element = document.createElement("div");
+ const getRect = vi.spyOn(element, "getBoundingClientRect");
+ const error = vi.spyOn(console, "error").mockImplementation(() => undefined);
+
+ await runGestureTransaction({
+ element,
+ label: "Resize layer",
+ settle: vi.fn(),
+ persist: async () => undefined,
+ restore: vi.fn(),
+ skipPixelAssert: true,
+ });
+
+ expect(getRect).not.toHaveBeenCalled();
+ expect(error).not.toHaveBeenCalledWith("[hf-commit] persist changed pixels", expect.anything());
+ expect(trackStudioEventMock).not.toHaveBeenCalledWith(
+ "commit_invariant_violation",
+ expect.anything(),
+ );
+ error.mockRestore();
+ });
+});
diff --git a/packages/studio/src/hooks/gestureTransaction.ts b/packages/studio/src/hooks/gestureTransaction.ts
new file mode 100644
index 0000000000..4b398d6636
--- /dev/null
+++ b/packages/studio/src/hooks/gestureTransaction.ts
@@ -0,0 +1,199 @@
+import type {
+ CommitMutation,
+ CommitMutationCall,
+ CommitMutationOptions,
+} from "./gsapScriptCommitTypes";
+import { trackStudioEvent } from "../utils/studioTelemetry";
+
+type PixelRect = Pick<DOMRect, "x" | "y" | "width" | "height">;
+
+export type TxCommit = (commitMutation: CommitMutation) => CommitMutation;
+
+export interface GestureTransaction {
+ element: HTMLElement;
+ label: string;
+ settle(): void;
+ persist(commit: TxCommit): Promise<void>;
+ restore(): void;
+ skipPixelAssert?: boolean;
+}
+
+let transactionCounter = 0;
+const transactionCommits = new WeakSet<CommitMutation>();
+
+/** Whether a commit function already belongs to an active gesture transaction. */
+export function isGestureTransactionCommit(commitMutation: CommitMutation): boolean {
+ return transactionCommits.has(commitMutation);
+}
+
+function readPixelRect(element: HTMLElement): PixelRect {
+ const { x, y, width, height } = element.getBoundingClientRect();
+ return { x, y, width, height };
+}
+
+function transactionOptions(
+ options: CommitMutationOptions,
+ coalesceKey: string,
+ label: string,
+): CommitMutationOptions {
+ // The transaction owns the undo label: every wrapped mutation records under
+ // `label`, so the coalesced entry reads as the gesture (e.g. "Resize layer")
+ // rather than whichever sub-mutation happened to land last (the offset
+ // persist's "Move layer").
+ const { coalesceKey: _coalesceKey, skipReload: _skipReload, softReload, ...rest } = options;
+ return softReload
+ ? { ...rest, label, softReload: true, coalesceKey, coalesceMs: Number.POSITIVE_INFINITY }
+ : { ...rest, label, skipReload: true, coalesceKey, coalesceMs: Number.POSITIVE_INFINITY };
+}
+
+function pixelDelta(before: PixelRect, after: PixelRect): PixelRect {
+ return {
+ x: after.x - before.x,
+ y: after.y - before.y,
+ width: after.width - before.width,
+ height: after.height - before.height,
+ };
+}
+
+function exceedsPixelTolerance(delta: PixelRect): boolean {
+ return Object.values(delta).some((value) => Math.abs(value) > 1);
+}
+
+function roundToOneDecimal(value: number): number {
+ return Math.round(value * 10) / 10;
+}
+
+type BufferedCommit = CommitMutationCall & { dispatch: CommitMutation };
+
+function mergeTransactionOptions(calls: BufferedCommit[]): CommitMutationOptions {
+ const reloadCall = calls.find(({ options }) => options.softReload);
+ const source = reloadCall?.options ?? calls.at(-1)?.options;
+ if (!source) throw new Error("Cannot merge an empty gesture transaction");
+ const { skipReload: _skipReload, instantPatch: _instantPatch, ...options } = source;
+ return reloadCall ? { ...options, softReload: true } : { ...options, skipReload: true };
+}
+
+/**
+ * Dispatch a transaction's buffered commits and return the number of preview
+ * reloads that ACTUALLY happened — a batch collapses every buffered softReload
+ * into one reload, so reload telemetry reflects the real cost, not the count of
+ * softReload requests.
+ */
+function reloadsRequested(calls: BufferedCommit[]): number {
+ return calls.filter(({ options }) => options.softReload).length;
+}
+
+async function dispatchBufferedCommits(calls: BufferedCommit[]): Promise<number> {
+ const first = calls[0];
+ if (!first) return 0;
+ if (calls.length === 1) {
+ await first.dispatch(first.selection, first.mutation, first.options);
+ return reloadsRequested(calls);
+ }
+ const canBatch = calls.every(
+ ({ dispatch, selection }) =>
+ dispatch === first.dispatch && selection.sourceFile === first.selection.sourceFile,
+ );
+ if (canBatch && first.dispatch.batch) {
+ await first.dispatch.batch(
+ calls.map(({ selection, mutation, options }) => ({ selection, mutation, options })),
+ mergeTransactionOptions(calls),
+ );
+ // One server write, one reload — the reload count collapses with the batch.
+ return reloadsRequested(calls) > 0 ? 1 : 0;
+ }
+ for (const { dispatch, selection, mutation, options } of calls) {
+ await dispatch(selection, mutation, options);
+ }
+ return reloadsRequested(calls);
+}
+
+/**
+ * Dev-only [hf-commit] lifecycle trace. The production observability lives in
+ * the trackStudioEvent commit_* events (always on); these console lines are a
+ * developer aid and stay out of end users' consoles.
+ */
+function traceCommit(stage: string, data: Record<string, unknown>): void {
+ if (import.meta.env.DEV) console.info(`[hf-commit] ${stage}`, data);
+}
+
+/**
+ * Owns the visual + persistence + history lifecycle for one gesture release.
+ * `settle` deliberately runs before the first promise is created or awaited.
+ */
+export function runGestureTransaction(tx: GestureTransaction): Promise<void> {
+ const startedAt = performance.now();
+ const coalesceKey = `tx:${tx.label}:${++transactionCounter}`;
+ let mutationCount = 0;
+ let reloadCount = 0;
+ const bufferedCommits: BufferedCommit[] = [];
+ traceCommit("start", { label: tx.label, coalesceKey });
+ tx.settle();
+ traceCommit("settled", { label: tx.label, coalesceKey });
+
+ const before = !tx.skipPixelAssert ? readPixelRect(tx.element) : null;
+ const commit: TxCommit = (commitMutation) => {
+ const wrapped: CommitMutation = (selection, mutation, options) => {
+ mutationCount += 1;
+ bufferedCommits.push({
+ dispatch: commitMutation,
+ selection,
+ mutation,
+ options: transactionOptions(options, coalesceKey, tx.label),
+ });
+ return Promise.resolve();
+ };
+ transactionCommits.add(wrapped);
+ return wrapped;
+ };
+
+ return tx
+ .persist(commit)
+ .then(async () => {
+ reloadCount = await dispatchBufferedCommits(bufferedCommits);
+ const durationMs = Math.round(performance.now() - startedAt);
+ traceCommit("persisted", { label: tx.label, coalesceKey });
+ if (before) {
+ const after = readPixelRect(tx.element);
+ const delta = pixelDelta(before, after);
+ if (exceedsPixelTolerance(delta)) {
+ if (import.meta.env.DEV) {
+ console.error("[hf-commit] persist changed pixels", {
+ label: tx.label,
+ before,
+ after,
+ delta,
+ });
+ }
+ trackStudioEvent("commit_invariant_violation", {
+ label: tx.label,
+ delta_x: roundToOneDecimal(delta.x),
+ delta_y: roundToOneDecimal(delta.y),
+ delta_w: roundToOneDecimal(delta.width),
+ delta_h: roundToOneDecimal(delta.height),
+ mutation_count: mutationCount,
+ reload_count: reloadCount,
+ duration_ms: durationMs,
+ });
+ }
+ }
+ trackStudioEvent("commit_transaction", {
+ label: tx.label,
+ mutation_count: mutationCount,
+ reload_count: reloadCount,
+ duration_ms: durationMs,
+ pixel_asserted: before !== null,
+ });
+ })
+ .catch((error: unknown) => {
+ tx.restore();
+ trackStudioEvent("commit_transaction_failed", {
+ label: tx.label,
+ mutation_count: mutationCount,
+ error_name: error instanceof Error ? error.name : "unknown",
+ restore_ran: true,
+ });
+ traceCommit("restore", { label: tx.label, coalesceKey });
+ throw error;
+ });
+}
diff --git a/packages/studio/src/hooks/gsapDragCommit.test.ts b/packages/studio/src/hooks/gsapDragCommit.test.ts
index 6fe00cd8f4..74822de145 100644
--- a/packages/studio/src/hooks/gsapDragCommit.test.ts
+++ b/packages/studio/src/hooks/gsapDragCommit.test.ts
@@ -1,3 +1,5 @@
+// @vitest-environment happy-dom
+
import { describe, expect, it, beforeEach } from "vitest";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
@@ -5,6 +7,7 @@ import { commitGsapPositionFromDrag } from "./gsapDragPositionCommit";
import {
commitStaticGsapPosition,
commitStaticGsapRotation,
+ commitStaticGsapSize,
findExistingPositionWrite,
parkPlayheadOnKeyframe,
type GsapDragCommitCallbacks,
@@ -280,7 +283,7 @@ const existingRotationSet = (): GsapAnimation =>
describe("commitStaticGsapPosition — instantPatch (value-only set)", () => {
beforeEach(() => usePlayerStore.setState({ currentTime: 0, activeKeyframePct: null }));
- it("attaches an instantPatch to BOTH coalesced commits, each derived from its own mutation", async () => {
+ it("updates an existing set atomically and derives its instantPatch from that mutation", async () => {
const { commits, callbacks } = optionRecordingCallbacks();
await commitStaticGsapPosition(
@@ -292,69 +295,122 @@ describe("commitStaticGsapPosition — instantPatch (value-only set)", () => {
callbacks,
);
- expect(commits).toHaveLength(2);
- // First (x) commit is the intermediate skipReload one — it now carries an
- // instantPatch for just {x}, so if the SECOND POST fails the preview still
- // reflects the x that DID persist (no reload, instant feedback).
- expect(commits[0].options.skipReload).toBe(true);
- expect(commits[0].options.instantPatch).toEqual({
- selector: "#puck-a",
- change: { kind: "set", props: { x: -50 } },
+ expect(commits).toHaveLength(1);
+ expect(commits[0].mutation).toEqual({
+ type: "update-properties",
+ animationId: "#puck-a-set",
+ properties: { x: -50, y: 30 },
});
- // Final (y) commit triggers the reload and carries the full {x,y} patch.
- expect(commits[1].options.softReload).toBe(true);
- expect(commits[1].options.instantPatch).toEqual({
+ expect(commits[0].options.softReload).toBe(true);
+ expect(commits[0].options.instantPatch).toEqual({
selector: "#puck-a",
change: { kind: "set", props: { x: -50, y: 30 } },
});
+ const mutation = commits[0].mutation as { properties: Record<string, number> };
+ const patch = commits[0].options.instantPatch as {
+ change: { props: Record<string, number> };
+ };
+ expect(patch.change.props).toEqual(mutation.properties);
});
- it("derives each instantPatch's props from the value in the SAME mutation that's POSTed", async () => {
+ it("ADDS a global gsap.set with a global-set instantPatch (off-timeline, no flash)", async () => {
const { commits, callbacks } = optionRecordingCallbacks();
await commitStaticGsapPosition(
selection(),
{ x: -50, y: 30 },
+ // fallow-ignore-next-line code-duplication
{ x: 0, y: 0 },
"#puck-a",
- existingPositionSet(),
+ null, // no existing set → `add` a new base gsap.set
callbacks,
);
- // The patch values must equal the mutation values — they're read out of the
- // same object, so a clean mutation can't ship alongside a stale patch.
- const xMutation = commits[0].mutation as { property: string; value: number };
- const yMutation = commits[1].mutation as { property: string; value: number };
- const xPatch = commits[0].options.instantPatch as {
- change: { props: Record<string, number> };
- };
- const yPatch = commits[1].options.instantPatch as {
- change: { props: Record<string, number> };
- };
- expect(xPatch.change.props[xMutation.property]).toBe(xMutation.value);
- expect(yPatch.change.props[yMutation.property]).toBe(yMutation.value);
- // The y commit's combined patch also carries the x mutation's value.
- expect(yPatch.change.props[xMutation.property]).toBe(xMutation.value);
+ expect(commits).toHaveLength(1);
+ expect(commits[0].mutation.type).toBe("add");
+ expect((commits[0].mutation as { global?: boolean }).global).toBe(true);
+ const patch = commits[0].options.instantPatch as { change: { kind: string } } | undefined;
+ expect(patch?.change.kind).toBe("global-set");
});
- it("ADDS a global gsap.set with a global-set instantPatch (off-timeline, no flash)", async () => {
+ it("creates one undo entry when updating an existing static position set", async () => {
const { commits, callbacks } = optionRecordingCallbacks();
await commitStaticGsapPosition(
selection(),
{ x: -50, y: 30 },
- // fallow-ignore-next-line code-duplication
{ x: 0, y: 0 },
"#puck-a",
- null, // no existing set → `add` a new base gsap.set
+ existingPositionSet(),
+ callbacks,
+ );
+
+ expect(commits).toHaveLength(1);
+ });
+});
+
+const existingSizeSet = (): GsapAnimation =>
+ ({
+ id: "#puck-a-size-set",
+ targetSelector: "#puck-a",
+ method: "set",
+ properties: { width: 100, height: 80 },
+ }) as unknown as GsapAnimation;
+
+describe("commitStaticGsapSize", () => {
+ it("updates an existing set with one update-properties mutation", async () => {
+ const { commits, callbacks } = optionRecordingCallbacks();
+
+ await commitStaticGsapSize(
+ selection(),
+ { width: 300.4, height: 199.6 },
+ "#puck-a",
+ existingSizeSet(),
+ callbacks,
+ );
+
+ expect(commits).toHaveLength(1);
+ expect(commits[0].mutation).toEqual({
+ type: "update-properties",
+ animationId: "#puck-a-size-set",
+ properties: { width: 300, height: 200 },
+ });
+ expect(commits.map((commit) => commit.mutation.type)).not.toContain("delete");
+ expect(commits.map((commit) => commit.mutation.type)).not.toContain("add");
+ });
+
+ it("adds exactly one set when no existing size set exists", async () => {
+ const { commits, callbacks } = optionRecordingCallbacks();
+
+ await commitStaticGsapSize(
+ selection(),
+ { width: 300, height: 200 },
+ "#puck-a",
+ null,
+ callbacks,
+ );
+
+ expect(commits).toHaveLength(1);
+ expect(commits[0].mutation).toMatchObject({
+ type: "add",
+ targetSelector: "#puck-a",
+ method: "set",
+ properties: { width: 300, height: 200 },
+ });
+ });
+
+ it("creates one undo entry for an existing static size set", async () => {
+ const { commits, callbacks } = optionRecordingCallbacks();
+
+ await commitStaticGsapSize(
+ selection(),
+ { width: 300, height: 200 },
+ "#puck-a",
+ existingSizeSet(),
callbacks,
);
expect(commits).toHaveLength(1);
- expect(commits[0].mutation.type).toBe("add");
- expect((commits[0].mutation as { global?: boolean }).global).toBe(true);
- const patch = commits[0].options.instantPatch as { change: { kind: string } } | undefined;
- expect(patch?.change.kind).toBe("global-set");
});
});
@@ -386,7 +442,7 @@ describe("static position hold recognition + heal (frozen duration-0 keyframed t
expect(found?.id).toBe("#puck-a-frozen");
});
- it("commitStaticGsapPosition heals a keyframed hold by delete + clean add-set (never update-property)", async () => {
+ it("heals a keyframed hold with one transaction ordered add before delete", async () => {
const { commits, callbacks } = optionRecordingCallbacks();
await commitStaticGsapPosition(
@@ -399,11 +455,55 @@ describe("static position hold recognition + heal (frozen duration-0 keyframed t
);
const types = commits.map((c) => c.mutation.type);
- // Can't update-property into keyframes — must delete the frozen tween and
- // write a clean static set, so the element becomes freely movable.
- expect(types).toEqual(["delete", "add"]);
- expect(types).not.toContain("update-property");
- expect((commits[1].mutation as { method?: string }).method).toBe("set");
+ expect(types).toEqual(["add", "delete"]);
+ expect(types).not.toContain("update-properties");
+ expect((commits[0].mutation as { method?: string }).method).toBe("set");
+ expect(commits[0].options.coalesceKey).toBe(commits[1].options.coalesceKey);
+ expect(commits[0].options.coalesceKey).toMatch(/^tx:Move layer:\d+$/);
+ });
+
+ it("keeps the original hold when the replacement add fails", async () => {
+ const mutationTypes: string[] = [];
+ const callbacks: GsapDragCommitCallbacks = {
+ commitMutation: async (_selection, mutation) => {
+ mutationTypes.push(mutation.type as string);
+ throw new Error("add failed");
+ },
+ };
+
+ await expect(
+ commitStaticGsapPosition(
+ selection(),
+ { x: -50, y: 30 },
+ { x: 0, y: 0 },
+ "#puck-a",
+ keyframedZeroDurationHold(),
+ callbacks,
+ ),
+ ).rejects.toThrow("add failed");
+ expect(mutationTypes).toEqual(["add"]);
+ });
+
+ it("leaves a recoverable duplicate when delete fails after the replacement add", async () => {
+ let holdCount = 1;
+ const callbacks: GsapDragCommitCallbacks = {
+ commitMutation: async (_selection, mutation) => {
+ if (mutation.type === "add") holdCount += 1;
+ if (mutation.type === "delete") throw new Error("delete failed");
+ },
+ };
+
+ await expect(
+ commitStaticGsapPosition(
+ selection(),
+ { x: -50, y: 30 },
+ { x: 0, y: 0 },
+ "#puck-a",
+ keyframedZeroDurationHold(),
+ callbacks,
+ ),
+ ).rejects.toThrow("delete failed");
+ expect(holdCount).toBe(2);
});
});
diff --git a/packages/studio/src/hooks/gsapDragCommit.ts b/packages/studio/src/hooks/gsapDragCommit.ts
index ed960e4dad..167ce438d5 100644
--- a/packages/studio/src/hooks/gsapDragCommit.ts
+++ b/packages/studio/src/hooks/gsapDragCommit.ts
@@ -15,10 +15,8 @@ import { roundTo3 } from "../utils/rounding";
import { computeElementPercentage } from "./gsapShared";
import { computeDraggedGsapPosition } from "./draggedGsapPosition";
import type { RuntimeTweenChange } from "./gsapRuntimePatch";
-import {
- setPatchFromUpdateProperties,
- setPatchFromUpdateProperty,
-} from "./gsapDragStaticSetHelpers";
+import { isGestureTransactionCommit, runGestureTransaction } from "./gestureTransaction";
+import { setPatchFromUpdateProperty } from "./gsapDragStaticSetHelpers";
export {
findExistingPositionWrite,
findRotationSetAnimation,
@@ -65,6 +63,46 @@ export function parkPlayheadOnKeyframe(anim: GsapAnimation, pct: number): void {
usePlayerStore.getState().requestSeek(roundTo3(ts + (pct / 100) * td));
}
+async function replaceKeyframedPositionHold(
+ selection: DomEditSelection,
+ selector: string,
+ existingSet: GsapAnimation,
+ properties: { x: number; y: number },
+ commitMutation: GsapDragCommitCallbacks["commitMutation"],
+): Promise<void> {
+ const persist = async (commit: GsapDragCommitCallbacks["commitMutation"]) => {
+ await commit(
+ selection,
+ {
+ type: "add",
+ targetSelector: selector,
+ method: "set",
+ position: 0,
+ properties,
+ global: true,
+ },
+ { label: "Move layer", skipReload: true },
+ );
+ await commit(
+ selection,
+ { type: "delete", animationId: existingSet.id },
+ { label: "Move layer", softReload: true },
+ );
+ };
+
+ if (isGestureTransactionCommit(commitMutation)) {
+ await persist(commitMutation);
+ return;
+ }
+ await runGestureTransaction({
+ element: selection.element,
+ label: "Move layer",
+ settle: () => undefined,
+ persist: async (commit) => persist(commit(commitMutation)),
+ restore: () => undefined,
+ });
+}
+
// ── Dynamic keyframe materialization ──────────────────────────────────────
export async function materializeIfDynamic(
@@ -116,7 +154,7 @@ export async function materializeIfDynamic(
* Commit a STATIC element drag as a `tl.set("#el",{x,y})` — the single-source
* position channel for elements with no position animation. Idempotent: a
* re-nudge of an element that already has a `set` UPDATES that set's x/y
- * (two `update-property` mutations) rather than stacking a second set or
+ * in one `update-properties` mutation rather than stacking a second set or
* converting it to keyframes (plan R2 / KTD3). New elements get one `add`
* mutation with `method:"set"` at position 0.
*/
@@ -132,70 +170,30 @@ export async function commitStaticGsapPosition(
if (existingSet) {
if (existingSet.keyframes) {
// Keyframed zero-duration hold (drag-path corruption): can't update-property
- // into keyframes — delete it and write a clean static set instead.
- const coalesceKey = `gsap:heal-static:${existingSet.id}`;
- await callbacks.commitMutation(
+ // into keyframes. Add the replacement first so either failure leaves at
+ // least one hold on disk, then delete the corrupt tween in one transaction.
+ await replaceKeyframedPositionHold(
selection,
- { type: "delete", animationId: existingSet.id },
- { label: "Move layer", skipReload: true, coalesceKey },
- );
- await callbacks.commitMutation(
- selection,
- {
- type: "add",
- targetSelector: selector,
- method: "set",
- position: 0,
- properties: { x: newX, y: newY },
- global: true,
- },
- {
- label: "Move layer",
- softReload: true,
- coalesceKey,
- instantPatch: { selector, change: { kind: "global-set", props: { x: newX, y: newY } } },
- },
+ selector,
+ existingSet,
+ { x: newX, y: newY },
+ callbacks.commitMutation,
);
return;
}
- // Update in place — two single-property mutations (the API updates one prop
- // per call). Coalesce them and reload only after the second lands.
- const coalesceKey = `gsap:set-nudge:${existingSet.id}`;
- // Build each mutation FIRST, then derive its instantPatch from the SAME
- // object that's POSTed — so a future caller can't ship a clean mutation with
- // a stale/malformed patch (the validated `value` flows straight into the
- // patch). `findUnsafeMutationValues` validates the mutation upstream.
- const xMutation = {
- type: "update-property",
+ const mutation = {
+ type: "update-properties",
animationId: existingSet.id,
- property: "x",
- value: newX,
- } as const;
- const yMutation = {
- type: "update-property",
- animationId: existingSet.id,
- property: "y",
- value: newY,
+ properties: { x: newX, y: newY },
} as const;
- // Patch BOTH coalesced commits. If the SECOND POST fails server-side, the
- // first (x) already persisted — patching its commit too means the live
- // preview still reflects what DID persist. The x commit carries skipReload
- // (no reload), so its instantPatch gives instant feedback without a reload;
- // the y commit triggers the soft reload (skipped when the patch applies).
const global = !!existingSet.global;
- await callbacks.commitMutation(selection, xMutation, {
- label: "Move layer",
- skipReload: true,
- coalesceKey,
- instantPatch: setPatchFromUpdateProperty(selector, xMutation, global),
- });
- await callbacks.commitMutation(selection, yMutation, {
+ await callbacks.commitMutation(selection, mutation, {
label: "Move layer",
softReload: true,
- coalesceKey,
- // Final commit of the coalesced x/y pair: carry both channels so the
- // runtime set lands the complete {x,y} pose in place.
- instantPatch: setPatchFromUpdateProperties(selector, [xMutation, yMutation], global),
+ instantPatch: {
+ selector,
+ change: { kind: global ? "global-set" : "set", props: mutation.properties },
+ },
});
return;
}
@@ -279,7 +277,7 @@ export async function commitStaticGsapRotation(
* tween: one keyframe at the playhead % renders NaN/0 at every other frame, so
* the element collapses/disappears (worst when resized off the 0% mark). A `set`
* holds the size at all times. Re-resizing an element that already has a size
- * `set` UPDATES it in place (two `update-property`, like x/y); a new element
+ * `set` UPDATES it in place with one `update-properties`; a new element
* gets one `add` with `method:"set"`.
*/
export async function commitStaticGsapSize(
@@ -292,18 +290,11 @@ export async function commitStaticGsapSize(
const width = Math.round(size.width);
const height = Math.round(size.height);
if (existingSet) {
- await callbacks.commitMutation(
- selection,
- { type: "delete", animationId: existingSet.id },
- { label: "Resize layer", skipReload: true },
- );
await callbacks.commitMutation(
selection,
{
- type: "add",
- targetSelector: selector,
- method: "set",
- position: 0,
+ type: "update-properties",
+ animationId: existingSet.id,
properties: { width, height },
},
{ label: "Resize layer", softReload: true },
@@ -394,10 +385,9 @@ export async function commitKeyframedSizeFromResize(
properties: Math.abs(p - pct) < 0.05 ? { width: newW, height: newH } : { ...prior },
}));
- // Add the size keyframe tween FIRST, then delete the old global hold. The two
- // commits aren't transactional, so ordering matters: if the delete fails the
- // size is preserved (animated, recoverable) rather than lost. Only the last
- // commit triggers the reload.
+ // Add the size keyframe tween FIRST, then delete the old global hold. The gesture
+ // transport applies both in one ordered batch; a plain commit fallback keeps the
+ // same recoverable ordering. Only the transaction's result triggers the reload.
const addLabel = `Resize (size keyframe ${pct.toFixed(0)}%)`;
await callbacks.commitMutation(
selection,
diff --git a/packages/studio/src/hooks/gsapDragStaticSetHelpers.ts b/packages/studio/src/hooks/gsapDragStaticSetHelpers.ts
index eda823c4e1..243ddbd818 100644
--- a/packages/studio/src/hooks/gsapDragStaticSetHelpers.ts
+++ b/packages/studio/src/hooks/gsapDragStaticSetHelpers.ts
@@ -1,6 +1,6 @@
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
-import { resolveTweenDuration } from "../utils/globalTimeCompiler";
import type { RuntimeTweenChange, SetPatchProps } from "./gsapRuntimePatch";
+import { isInstantHold } from "./gsapShared";
/** The shape of an `update-property` mutation a static-set nudge POSTs. */
interface UpdatePropertyMutation {
@@ -16,27 +16,17 @@ interface UpdatePropertyMutation {
* value the source write didn't (one source of truth). Each mutation contributes
* its `{property: value}` channel to the patch's props.
*/
-export function setPatchFromUpdateProperties(
+export function setPatchFromUpdateProperty(
selector: string,
- mutations: UpdatePropertyMutation[],
+ mutation: UpdatePropertyMutation,
global = false,
): { selector: string; change: RuntimeTweenChange } {
- const props: SetPatchProps = {};
- for (const m of mutations) props[m.property as keyof SetPatchProps] = m.value;
+ const props: SetPatchProps = { [mutation.property as keyof SetPatchProps]: mutation.value };
// An off-timeline `gsap.set` has no runtime tween to patch — apply it to the
// element directly. An on-timeline `tl.set` mutates its tween (so a re-seek keeps it).
return { selector, change: { kind: global ? "global-set" : "set", props } };
}
-/** Single-mutation convenience over {@link setPatchFromUpdateProperties}. */
-export function setPatchFromUpdateProperty(
- selector: string,
- mutation: UpdatePropertyMutation,
- global = false,
-): { selector: string; change: RuntimeTweenChange } {
- return setPatchFromUpdateProperties(selector, [mutation], global);
-}
-
/**
* Find the studio position-hold `set` for a selector — a `tl.set("#el",{x,y})`
* with no duration. This is what a static-element nudge writes/updates.
@@ -61,7 +51,8 @@ function findPositionSetAnimation(
* remove-all-keyframes leaves behind) is a held position too, and the next drag
* must UPDATE it in place rather than append a second `gsap.set` that fights it
* (the duplicate-position-write bug). Only zero-duration holds qualify — a
- * live-duration `to`/`from` is NOT a static hold (and in the static path it's a
+ * live-duration tween and a duration-zero `from` are NOT static holds (and in
+ * the static path they're a
* stale/phantom parse: re-committing it would resurrect a just-deleted tween).
* A keyframed zero-duration `to` is ALSO a static hold (a drag-path corruption
* artifact) and must be recognized so the static commit normalizes it.
@@ -75,10 +66,7 @@ export function findExistingPositionWrite(
if (set) return set;
return (
animations.find(
- (a) =>
- a.targetSelector === selector &&
- a.propertyGroup === "position" &&
- resolveTweenDuration(a) === 0,
+ (a) => a.targetSelector === selector && a.propertyGroup === "position" && isInstantHold(a),
) ?? null
);
}
@@ -89,7 +77,7 @@ export function findRotationSetAnimation(
): GsapAnimation | null {
return (
animations.find(
- (a) => a.method === "set" && a.targetSelector === selector && "rotation" in a.properties,
+ (a) => isInstantHold(a) && a.targetSelector === selector && "rotation" in a.properties,
) ?? null
);
}
@@ -101,7 +89,7 @@ export function findSizeSetAnimation(
return (
animations.find(
(a) =>
- a.method === "set" &&
+ isInstantHold(a) &&
a.targetSelector === selector &&
("width" in a.properties || "height" in a.properties),
) ?? null
diff --git a/packages/studio/src/hooks/gsapResizeIntercept.test.ts b/packages/studio/src/hooks/gsapResizeIntercept.test.ts
index 6a0d750883..4ed179dd66 100644
--- a/packages/studio/src/hooks/gsapResizeIntercept.test.ts
+++ b/packages/studio/src/hooks/gsapResizeIntercept.test.ts
@@ -3,6 +3,7 @@ import { afterEach, expect, it, vi } from "vitest";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import { usePlayerStore } from "../player/store/playerStore";
+import { computeCurrentPercentage } from "./gsapDragCommit";
import { tryGsapResizeIntercept } from "./gsapResizeIntercept";
afterEach(() => {
@@ -69,6 +70,74 @@ function keyframedScaleFixture(): GsapAnimation {
} as unknown as GsapAnimation;
}
+it("updates a duration-zero size hold in place instead of converting it to keyframes", async () => {
+ const el = document.createElement("div");
+ el.id = "box";
+ document.body.append(el);
+ const selection = { id: "box", selector: "#box", element: el } as DomEditSelection;
+ const instantSizeHold = {
+ id: "#box-to-0-size",
+ targetSelector: "#box",
+ propertyGroup: "size",
+ method: "to",
+ properties: { width: 150, height: 150 },
+ position: 0,
+ resolvedStart: 0,
+ duration: 0,
+ extras: { immediateRender: "__raw:true" },
+ } as unknown as GsapAnimation;
+ const commitMutation = vi.fn();
+
+ const handled = await tryGsapResizeIntercept(
+ selection,
+ { width: 344, height: 344 },
+ [instantSizeHold],
+ null,
+ commitMutation,
+ );
+
+ expect(handled).toBe(true);
+ expect(commitMutation).toHaveBeenCalledTimes(1);
+ expect(commitMutation.mock.calls[0]![1]).toEqual({
+ type: "update-properties",
+ animationId: "#box-to-0-size",
+ properties: { width: 344, height: 344 },
+ });
+ expect(commitMutation).not.toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ type: "convert-to-keyframes" }),
+ expect.anything(),
+ );
+ expect(commitMutation).not.toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ type: "add-keyframe" }),
+ expect.anything(),
+ );
+});
+
+it("computes a finite zero percentage for a zero-duration tween", () => {
+ const animation = {
+ id: "#box-to-0-size",
+ targetSelector: "#box",
+ propertyGroup: "size",
+ method: "to",
+ properties: { width: 150 },
+ resolvedStart: 1,
+ duration: 0,
+ } as unknown as GsapAnimation;
+ const selection = {
+ id: "box",
+ selector: "#box",
+ element: document.createElement("div"),
+ } as DomEditSelection;
+ usePlayerStore.setState({ currentTime: 5 });
+
+ const percentage = computeCurrentPercentage(selection, animation);
+
+ expect(Number.isFinite(percentage)).toBe(true);
+ expect(percentage).toBe(0);
+});
+
/** Drive one resize through the intercept, returning every committed mutation. */
async function runResize(
el: HTMLElement,
diff --git a/packages/studio/src/hooks/gsapResizeIntercept.ts b/packages/studio/src/hooks/gsapResizeIntercept.ts
index e7cc476703..a0042b6020 100644
--- a/packages/studio/src/hooks/gsapResizeIntercept.ts
+++ b/packages/studio/src/hooks/gsapResizeIntercept.ts
@@ -24,10 +24,11 @@ import type { GsapDragCommitCallbacks } from "./gsapDragCommit";
import { pickClosestToPlayhead, readGsapPositionFromIframe } from "./gsapPositionDetection";
import { commitWholePropertyOffset } from "./gsapWholePropertyOffsetCommit";
import { resolveTweenStart, resolveTweenDuration } from "../utils/globalTimeCompiler";
-import { selectorFromSelection } from "./gsapShared";
+import { isInstantHold, selectorFromSelection } from "./gsapShared";
import { roundTo3 } from "../utils/rounding";
import { resolveGroupTween, POSITION_CHANNELS } from "./gsapRuntimeBridge";
import { hasNonHoldTweenForElement } from "./gsapRuntimeKeyframes";
+import { logResize } from "../utils/resizeDebug";
const IDENTITY_ONE_PROPS = new Set(["opacity", "autoAlpha", "scale", "scaleX", "scaleY"]);
@@ -68,19 +69,27 @@ export async function tryGsapResizeIntercept(
);
let anim = resolved?.anim ?? null;
- if (!anim || anim.method === "set") {
+ logResize("intercept-enter", {
+ hasScaleGroup,
+ resizeGroup,
+ animMethod: anim?.method ?? null,
+ animId: anim?.id ?? null,
+ size,
+ });
+ if (!anim || isInstantHold(anim)) {
const sel = selectorFromSelection(selection);
if (!sel) return false;
- const sizeSet = anim?.method === "set" ? anim : findSizeSetAnimation(animations, sel);
+ const sizeSet = anim ?? findSizeSetAnimation(animations, sel);
// If the element is animated (has a real tween, not just a static size
// hold), keyframe the size at the playhead so other keyframes keep theirs —
// instead of a global set that resizes every frame.
if (resizeGroup === "size") {
const animatedTween = pickClosestToPlayhead(
- animations.filter((a) => a.method !== "set" && resolveTweenDuration(a) > 0),
+ animations.filter((a) => !isInstantHold(a) && resolveTweenDuration(a) > 0),
);
if (animatedTween) {
+ logResize("intercept-route", { route: "keyframed-size", tweenId: animatedTween.id });
const handled = await commitKeyframedSizeFromResize(
selection,
size,
@@ -93,6 +102,7 @@ export async function tryGsapResizeIntercept(
}
}
+ logResize("intercept-route", { route: "static-size-set", hadSizeSet: !!sizeSet, resizeGroup });
await commitStaticGsapSize(selection, size, sel, sizeSet, {
commitMutation,
fetchAnimations: fetchFallbackAnimations,
@@ -100,11 +110,12 @@ export async function tryGsapResizeIntercept(
return true;
}
+ const tweenDuration = resolveTweenDuration(anim);
+ if (tweenDuration <= 0) return false;
+
const { activeKeyframePct, setActiveKeyframePct } = usePlayerStore.getState();
const pct = activeKeyframePct ?? computeCurrentPercentage(selection, anim);
if (activeKeyframePct != null) setActiveKeyframePct(null);
- const coalesceKey = `gsap:resize:${anim.id}`;
-
const selector = selectorFromSelection(selection);
// Scope every capture to the resize group — same contract as the rotation
// intercept. Unfiltered, an opacity-touching intro tween on the element
@@ -144,6 +155,16 @@ export async function tryGsapResizeIntercept(
// shorthand when the two agree (aspect-true drags, shift-drags).
nonUniformScale = Math.abs(newScaleX - newScaleY) > 0.01;
resizeProps = nonUniformScale ? { scaleX: newScaleX, scaleY: newScaleY } : { scale: newScaleX };
+ logResize("intercept-route", {
+ route: "scale-tween",
+ cssW,
+ cssH,
+ liveScaleX,
+ liveScaleY,
+ newScaleX,
+ newScaleY,
+ nonUniformScale,
+ });
scaleDraftEl = el;
// Where the user DROPPED the box: the draft (anchor-pinned to the
// gesture-start top-left) is still applied here, so this rect is exactly
@@ -184,6 +205,7 @@ export async function tryGsapResizeIntercept(
POSITION_CHANNELS,
);
if (hasLivePositionTween) {
+ logResize("scale-finalize", { skipped: "live-position-tween" });
return;
}
// The scale commit has rendered (instant patch or soft-reload seek) and the
@@ -200,6 +222,13 @@ export async function tryGsapResizeIntercept(
x: Math.round(gsapPos.x + residual.x),
y: Math.round(gsapPos.y + residual.y),
};
+ logResize("scale-finalize", {
+ dropPoint: scaleDraftDropPoint,
+ post: { x: post.x, y: post.y },
+ residual,
+ gsapPos,
+ corrected,
+ });
// Correct the LIVE runtime NOW, synchronously: the soft reload above just
// rendered the committed scale around the element center — NOT at the drop
// point — and everything up to here runs in the same microtask chain as
@@ -249,7 +278,7 @@ export async function tryGsapResizeIntercept(
const ct = usePlayerStore.getState().currentTime;
const ts = resolveTweenStart(anim);
- const td = resolveTweenDuration(anim);
+ const td = tweenDuration;
const outsideRange = ts !== null && td > 0 && (ct < ts - 0.01 || ct > ts + td + 0.01); // Convert flat tweens to keyframes only for in-range resizes.
// Outside-range uses the extend path which handles everything atomically.
if (!outsideRange) {
@@ -264,7 +293,7 @@ export async function tryGsapResizeIntercept(
await commitMutation(
selection,
{ type: "convert-to-keyframes", animationId: anim.id, resolvedFromValues },
- { label: "Convert to keyframes for resize", skipReload: true, coalesceKey },
+ { label: "Convert to keyframes for resize" },
);
if (fetchFallbackAnimations) {
const fresh = await fetchFallbackAnimations();
@@ -353,7 +382,6 @@ export async function tryGsapResizeIntercept(
? `Resize (extended to ${ct.toFixed(2)}s)`
: `Resize (keyframe ${Math.round(((ct - newStart) / newDuration) * 1000) / 10}%)`,
softReload: true,
- coalesceKey,
},
);
await finalizeScaleResizeCommit();
@@ -376,7 +404,7 @@ export async function tryGsapResizeIntercept(
properties: resizeProps,
backfillDefaults,
},
- { label: `Resize (keyframe ${pct}%)`, softReload: true, coalesceKey },
+ { label: `Resize (keyframe ${pct}%)`, softReload: true },
);
await finalizeScaleResizeCommit();
return true;
diff --git a/packages/studio/src/hooks/gsapRuntimeBridge.test.ts b/packages/studio/src/hooks/gsapRuntimeBridge.test.ts
index a358095116..7c78c05872 100644
--- a/packages/studio/src/hooks/gsapRuntimeBridge.test.ts
+++ b/packages/studio/src/hooks/gsapRuntimeBridge.test.ts
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
-import { tryGsapDragIntercept } from "./gsapRuntimeBridge";
+import { tryGsapDragIntercept, tryGsapRotationIntercept } from "./gsapRuntimeBridge";
import { usePlayerStore } from "../player/store/playerStore";
/**
@@ -90,7 +90,7 @@ describe("tryGsapDragIntercept — stale-parse guard (no resurrection after dele
expect(mutation.type).not.toBe("add-keyframe");
});
- it("forwards instantPatch on BOTH coalesced commits when updating an existing static set", async () => {
+ it("forwards one complete instantPatch when atomically updating an existing static set", async () => {
const commitMutation = vi.fn();
const iframe = fakeIframe("puck-b", []); // runtime empty → STATIC path
// An existing position-hold `set` for the selector → update-in-place (not add).
@@ -113,16 +113,14 @@ describe("tryGsapDragIntercept — stale-parse guard (no resurrection after dele
);
expect(handled).toBe(true);
- // The coalesced update-property pair both carry an instantPatch so a partial
- // (second-POST) failure still leaves the preview patched for what persisted:
- // the x commit patches {x}, the final y commit patches the full {x,y}.
- const updates = commitMutation.mock.calls.filter(([, m]) => m.type === "update-property");
- expect(updates).toHaveLength(2);
- expect(updates[0][2].instantPatch).toEqual({
- selector: "#puck-b",
- change: { kind: "set", props: { x: -50 } },
+ const updates = commitMutation.mock.calls.filter(([, m]) => m.type === "update-properties");
+ expect(updates).toHaveLength(1);
+ expect(updates[0][1]).toEqual({
+ type: "update-properties",
+ animationId: "#puck-b-set",
+ properties: { x: -50, y: 30 },
});
- expect(updates[1][2].instantPatch).toEqual({
+ expect(updates[0][2].instantPatch).toEqual({
selector: "#puck-b",
change: { kind: "set", props: { x: -50, y: 30 } },
});
@@ -154,9 +152,9 @@ describe("tryGsapDragIntercept — stale-parse guard (no resurrection after dele
);
expect(handled).toBe(true);
- // In-place update (2 coalesced update-property), NOT an `add`/`add-keyframe`.
+ // One atomic in-place update, NOT an `add`/`add-keyframe`.
const types = commitMutation.mock.calls.map(([, m]) => m.type);
- expect(types.every((t: string) => t === "update-property")).toBe(true);
+ expect(types).toEqual(["update-properties"]);
expect(types).not.toContain("add");
expect(types).not.toContain("add-keyframe");
});
@@ -180,6 +178,44 @@ describe("tryGsapDragIntercept — stale-parse guard (no resurrection after dele
});
});
+describe("tryGsapRotationIntercept — instant holds", () => {
+ it("updates a duration-zero fromTo hold instead of converting it to keyframes", async () => {
+ const rotationHold = {
+ id: "#puck-b-fromTo-0-rotation",
+ targetSelector: "#puck-b",
+ propertyGroup: "rotation",
+ method: "fromTo",
+ fromProperties: { rotation: 0 },
+ properties: { rotation: 30 },
+ position: 0,
+ resolvedStart: 0,
+ duration: 0,
+ } as unknown as GsapAnimation;
+ const commitMutation = vi.fn();
+
+ const handled = await tryGsapRotationIntercept(
+ selection,
+ 75,
+ [rotationHold],
+ null,
+ commitMutation,
+ );
+
+ expect(handled).toBe(true);
+ expect(commitMutation).toHaveBeenCalledTimes(1);
+ expect(commitMutation.mock.calls[0]![1]).toEqual({
+ type: "update-property",
+ animationId: rotationHold.id,
+ property: "rotation",
+ value: 75,
+ });
+ const types = commitMutation.mock.calls.map(([, mutation]) => mutation.type);
+ expect(types).not.toContain("convert-to-keyframes");
+ expect(types).not.toContain("add-keyframe");
+ expect(types).not.toContain("add");
+ });
+});
+
// Regression (#1808): with the global auto-keyframe toggle off, dragging an
// element that already has a keyframed position tween must shift the whole
// tween (a "replace-with-keyframes" carrying every original percentage) —
diff --git a/packages/studio/src/hooks/gsapRuntimeBridge.ts b/packages/studio/src/hooks/gsapRuntimeBridge.ts
index 601532300c..d102e7a81b 100644
--- a/packages/studio/src/hooks/gsapRuntimeBridge.ts
+++ b/packages/studio/src/hooks/gsapRuntimeBridge.ts
@@ -26,7 +26,7 @@ import {
import { commitWholePropertyOffset } from "./gsapWholePropertyOffsetCommit";
import { resolveTweenDuration } from "../utils/globalTimeCompiler";
import type { GsapDragCommitCallbacks } from "./gsapDragCommit";
-import { selectorFromSelection } from "./gsapShared";
+import { isInstantHold, selectorFromSelection } from "./gsapShared";
import {
findGsapPositionAnimation,
pickClosestToPlayhead,
@@ -211,7 +211,7 @@ export async function tryGsapDragIntercept(
const hasKeyframedPosTween = !!posAnim?.keyframes && resolveTweenDuration(posAnim) > 0;
if (!hasNonHold && !hasKeyframedPosTween) {
const existingSet =
- posAnim && posAnim.method === "set" && posAnim.targetSelector === selector
+ posAnim && isInstantHold(posAnim) && posAnim.targetSelector === selector
? posAnim
: findExistingPositionWrite(resolvedAnimations, selector);
await commitStaticGsapPosition(selection, offset, gsapPos, selector, existingSet, {
@@ -300,8 +300,8 @@ export async function tryGsapRotationIntercept(
// mirroring the static position set. Idempotent: re-rotate updates an existing
// rotation set in place, else add a new one. This replaces the old
// `--hf-studio-rotation` CSS-var fallback (the same dual-channel bug class).
- if (!anim) {
- const existingSet = findRotationSetAnimation(resolvedAnimations, selector);
+ if (!anim || isInstantHold(anim)) {
+ const existingSet = anim ?? findRotationSetAnimation(resolvedAnimations, selector);
await commitStaticGsapRotation(selection, newRotation, selector, existingSet, {
commitMutation,
fetchAnimations: fetchFallbackAnimations,
diff --git a/packages/studio/src/hooks/gsapScriptCommitTypes.ts b/packages/studio/src/hooks/gsapScriptCommitTypes.ts
index e60b1282bf..4de90da3d0 100644
--- a/packages/studio/src/hooks/gsapScriptCommitTypes.ts
+++ b/packages/studio/src/hooks/gsapScriptCommitTypes.ts
@@ -16,6 +16,7 @@ export interface MutationResult {
export interface CommitMutationOptions {
label: string;
coalesceKey?: string;
+ coalesceMs?: number;
softReload?: boolean;
skipReload?: boolean;
beforeReload?: () => void;
@@ -38,11 +39,20 @@ export interface CommitMutationOptions {
instantPatch?: { selector: string; change: RuntimeTweenChange };
}
-export type CommitMutation = (
- selection: DomEditSelection,
- mutation: Record<string, unknown>,
- options: CommitMutationOptions,
-) => Promise<void>;
+export interface CommitMutationCall {
+ selection: DomEditSelection;
+ mutation: Record<string, unknown>;
+ options: CommitMutationOptions;
+}
+
+export interface CommitMutation {
+ (
+ selection: DomEditSelection,
+ mutation: Record<string, unknown>,
+ options: CommitMutationOptions,
+ ): Promise<void>;
+ batch?: (calls: CommitMutationCall[], options: CommitMutationOptions) => Promise<void>;
+}
export type SafeGsapCommitMutation = (
selection: DomEditSelection,
@@ -66,6 +76,7 @@ export interface GsapScriptCommitsParams {
label: string;
kind: EditHistoryKind;
coalesceKey?: string;
+ coalesceMs?: number;
files: Record<string, { before: string; after: string }>;
}) => Promise<void>;
};
diff --git a/packages/studio/src/hooks/gsapShared.test.ts b/packages/studio/src/hooks/gsapShared.test.ts
index b31c377534..ba45743488 100644
--- a/packages/studio/src/hooks/gsapShared.test.ts
+++ b/packages/studio/src/hooks/gsapShared.test.ts
@@ -1,5 +1,23 @@
import { describe, it, expect } from "vitest";
-import { parsePercentageKeyframes } from "./gsapShared";
+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
+import { isInstantHold, parsePercentageKeyframes } from "./gsapShared";
+
+describe("isInstantHold", () => {
+ const animation = (method: GsapAnimation["method"], duration?: number) =>
+ ({ method, duration }) as unknown as GsapAnimation;
+
+ it("classifies set and duration-zero to/fromTo writes as instant holds", () => {
+ expect(isInstantHold(animation("set"))).toBe(true);
+ expect(isInstantHold(animation("to", 0))).toBe(true);
+ expect(isInstantHold(animation("fromTo", 0))).toBe(true);
+ });
+
+ it("does not classify live tweens or duration-zero from writes as instant holds", () => {
+ expect(isInstantHold(animation("to", 1))).toBe(false);
+ expect(isInstantHold(animation("fromTo"))).toBe(false);
+ expect(isInstantHold(animation("from", 0))).toBe(false);
+ });
+});
describe("parsePercentageKeyframes", () => {
it("parses the object/percentage form", () => {
diff --git a/packages/studio/src/hooks/gsapShared.ts b/packages/studio/src/hooks/gsapShared.ts
index 0b5fccfb0b..459f303b46 100644
--- a/packages/studio/src/hooks/gsapShared.ts
+++ b/packages/studio/src/hooks/gsapShared.ts
@@ -33,6 +33,19 @@ export const PROPERTY_DEFAULTS: Record<string, number> = {
height: 100,
};
+/**
+ * A timeline write that applies an instantaneous value and then holds it.
+ * `set()` is always a hold; authored `to()` / `fromTo()` tweens are holds only
+ * when their resolved duration is exactly zero.
+ */
+export function isInstantHold(animation: GsapAnimation): boolean {
+ return (
+ animation.method === "set" ||
+ ((animation.method === "to" || animation.method === "fromTo") &&
+ resolveTweenDuration(animation) === 0)
+ );
+}
+
// ── Selector resolution ───────────────────────────────────────────────────────
/**
@@ -61,6 +74,7 @@ export function computeElementPercentage(
if (animation) {
const start = resolveTweenStart(animation);
const duration = resolveTweenDuration(animation);
+ if (duration <= 0) return 0;
if (start !== null) {
return absoluteToPercentage(currentTime, start, duration);
}
diff --git a/packages/studio/src/hooks/patchDocumentRootDuration.test.ts b/packages/studio/src/hooks/patchDocumentRootDuration.test.ts
new file mode 100644
index 0000000000..ab152914c8
--- /dev/null
+++ b/packages/studio/src/hooks/patchDocumentRootDuration.test.ts
@@ -0,0 +1,71 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from "vitest";
+import { patchDocumentRootDuration } from "./timelineEditingHelpers";
+
+// The regression these guard against: timing edits now soft-reload instead of
+// full-reloading the iframe, so the runtime recomputes the composition length
+// from the ROOT's `data-duration` and posts it back — overwriting the studio's
+// optimistic duration readout. Patching the live root's `data-duration` in the
+// same tick keeps the runtime's post-soft-reload report in agreement, so the
+// readout stays live on grow AND shrink instead of snapping back.
+function parse(html: string): Document {
+ return new DOMParser().parseFromString(html, "text/html");
+}
+
+describe("patchDocumentRootDuration", () => {
+ it("writes the content end onto the TOP-LEVEL composition root (grow)", () => {
+ const doc = parse(`
+ <div data-composition-id="root" data-duration="15.18">
+ <div data-composition-id="scene" data-start="0" data-duration="8"></div>
+ <div data-start="12" data-duration="8"></div>
+ </div>
+ `);
+ expect(patchDocumentRootDuration(doc, 20)).toBe(true);
+ const root = doc.querySelector('[data-composition-id="root"]');
+ expect(root?.getAttribute("data-duration")).toBe("20");
+ // Nested sub-composition is untouched — only the outermost root is the length.
+ expect(doc.querySelector('[data-composition-id="scene"]')?.getAttribute("data-duration")).toBe(
+ "8",
+ );
+ });
+
+ it("shrinks the root duration too (not grow-only)", () => {
+ const doc = parse(`<div data-composition-id="root" data-duration="15.18"></div>`);
+ expect(patchDocumentRootDuration(doc, 6.5)).toBe(true);
+ expect(doc.querySelector("[data-composition-id]")?.getAttribute("data-duration")).toBe("6.5");
+ });
+
+ it("picks the composition with no ancestor composition as the root", () => {
+ // Root appears AFTER a nested one in document order — selection must be by
+ // ancestry, not first-match, matching the runtime's own root resolver.
+ const doc = parse(`
+ <section data-composition-id="root" data-duration="10">
+ <div data-composition-id="inner" data-duration="4"></div>
+ </section>
+ `);
+ patchDocumentRootDuration(doc, 12);
+ expect(doc.querySelector('[data-composition-id="root"]')?.getAttribute("data-duration")).toBe(
+ "12",
+ );
+ expect(doc.querySelector('[data-composition-id="inner"]')?.getAttribute("data-duration")).toBe(
+ "4",
+ );
+ });
+
+ it("no-ops on a non-positive or non-finite content end (never collapses to 0)", () => {
+ const doc = parse(`<div data-composition-id="root" data-duration="15.18"></div>`);
+ expect(patchDocumentRootDuration(doc, 0)).toBe(false);
+ expect(patchDocumentRootDuration(doc, -3)).toBe(false);
+ expect(patchDocumentRootDuration(doc, Number.NaN)).toBe(false);
+ expect(doc.querySelector("[data-composition-id]")?.getAttribute("data-duration")).toBe("15.18");
+ });
+
+ it("no-ops when there is no composition root and reports false", () => {
+ const doc = parse(`<div data-start="0" data-duration="5"></div>`);
+ expect(patchDocumentRootDuration(doc, 10)).toBe(false);
+ });
+
+ it("returns false for a null document", () => {
+ expect(patchDocumentRootDuration(null, 10)).toBe(false);
+ });
+});
diff --git a/packages/studio/src/hooks/timelineEditingGsap.ts b/packages/studio/src/hooks/timelineEditingGsap.ts
new file mode 100644
index 0000000000..e1f7aabb3c
--- /dev/null
+++ b/packages/studio/src/hooks/timelineEditingGsap.ts
@@ -0,0 +1,14 @@
+import { formatTimelineAttributeNumber } from "../player/components/timelineEditing";
+
+export function patchDocumentRootDuration(
+ doc: Document | null | undefined,
+ contentEnd: number,
+): boolean {
+ if (!doc || !Number.isFinite(contentEnd) || contentEnd <= 0) return false;
+ const nodes = Array.from(doc.querySelectorAll("[data-composition-id]"));
+ const root =
+ nodes.find((node) => !node.parentElement?.closest("[data-composition-id]")) ?? nodes[0] ?? null;
+ if (!root) return false;
+ root.setAttribute("data-duration", formatTimelineAttributeNumber(contentEnd));
+ return true;
+}
diff --git a/packages/studio/src/hooks/timelineEditingHelpers.test.ts b/packages/studio/src/hooks/timelineEditingHelpers.test.ts
index 0d31cb50cc..238f30f2cb 100644
--- a/packages/studio/src/hooks/timelineEditingHelpers.test.ts
+++ b/packages/studio/src/hooks/timelineEditingHelpers.test.ts
@@ -1,8 +1,13 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from "vitest";
-import { applyTimelineStackingReorder, extendRootDurationIfNeeded } from "./timelineEditingHelpers";
+import {
+ applyTimelineStackingReorder,
+ deleteSelectedKeyframes,
+ extendRootDurationIfNeeded,
+} from "./timelineEditingHelpers";
import type { TimelineElement } from "../player/store/playerStore";
import { usePlayerStore } from "../player/store/playerStore";
+import type { CommitMutationOptions } from "./gsapScriptCommitTypes";
afterEach(() => {
usePlayerStore.getState().reset();
@@ -102,3 +107,31 @@ describe("extendRootDurationIfNeeded", () => {
expect(usePlayerStore.getState().duration).toBe(5);
});
});
+
+describe("deleteSelectedKeyframes", () => {
+ it("coalesces all removals and reloads only after the last one", () => {
+ usePlayerStore.setState({
+ selectedElementId: "card",
+ selectedKeyframes: new Set(["card:10", "card:50", "card:90"]),
+ });
+ const handleGsapRemoveKeyframe =
+ vi.fn<(animId: string, pct: number, options?: Partial<CommitMutationOptions>) => void>();
+
+ deleteSelectedKeyframes({
+ selectedGsapAnimations: [{ id: "card-position", keyframes: {} }],
+ handleGsapRemoveKeyframe,
+ });
+
+ expect(handleGsapRemoveKeyframe).toHaveBeenCalledTimes(3);
+ const options = handleGsapRemoveKeyframe.mock.calls.map((call) => call[2]);
+ expect(new Set(options.map((entry) => entry?.coalesceKey)).size).toBe(1);
+ expect(options).toEqual([
+ expect.objectContaining({ coalesceMs: Infinity, skipReload: true }),
+ expect.objectContaining({ coalesceMs: Infinity, skipReload: true }),
+ expect.objectContaining({ coalesceMs: Infinity, softReload: true }),
+ ]);
+ expect(options[0]).not.toHaveProperty("softReload");
+ expect(options[1]).not.toHaveProperty("softReload");
+ expect(options[2]).not.toHaveProperty("skipReload");
+ });
+});
diff --git a/packages/studio/src/hooks/timelineEditingHelpers.ts b/packages/studio/src/hooks/timelineEditingHelpers.ts
index 28d2e09ece..ebd9f5e949 100644
--- a/packages/studio/src/hooks/timelineEditingHelpers.ts
+++ b/packages/studio/src/hooks/timelineEditingHelpers.ts
@@ -6,12 +6,10 @@ import {
} from "../player/components/timelineEditing";
import { getElementZIndex } from "../player/lib/layerOrdering";
import { getTimelineElementIdentity } from "../player/lib/timelineElementHelpers";
-import { saveProjectFilesWithHistory } from "../utils/studioFileHistory";
-import { selectedKeyframePercentagesForElement } from "../utils/keyframeSelection";
-import type { EditHistoryKind } from "../utils/editHistory";
+import { saveProjectFilesWithHistory, type RecordEditInput } from "../utils/studioFileHistory";
import type { TimelineZIndexReorderCommit } from "./useTimelineEditingTypes";
import { extendRootDurationInSource } from "../utils/rootDuration";
-
+export { deleteSelectedKeyframes } from "./deleteSelectedKeyframes";
function isHTMLElement(element: Element | null): element is HTMLElement {
if (!element) return false;
// Use the element's OWN realm's HTMLElement: timeline clips live in the preview
@@ -20,7 +18,6 @@ function isHTMLElement(element: Element | null): element is HTMLElement {
const Ctor = element.ownerDocument?.defaultView?.HTMLElement ?? globalThis.HTMLElement;
return element instanceof Ctor;
}
-
/**
* Resolve a timeline vertical move to a z-index stacking reorder and commit it
* through the shared layers-panel reorder path. Reads live sibling z-index from
@@ -38,13 +35,12 @@ export function applyTimelineStackingReorder(input: {
iframe: HTMLIFrameElement | null;
activeCompPath: string | null;
commit: TimelineZIndexReorderCommit | null | undefined;
+ coalesceKey?: string;
}): Promise<void> {
// Audio has no visual stacking; a vertical drag on it must never write z-index.
if (input.element.tag === "audio") return Promise.resolve();
-
const intent = input.stackingReorder ?? null;
if (intent == null || intent.zIndexChanges.length === 0) return Promise.resolve();
-
// Resolve each change's live element from the change's OWN locator (the intent
// is self-contained), falling back to the top-level element list. Sub-comp
// children aren't in `timelineElements`, so a list-only lookup would miss them.
@@ -67,7 +63,6 @@ export function applyTimelineStackingReorder(input: {
sourceFile: string;
key: string;
}> = [];
-
for (const change of intent.zIndexChanges) {
const sibling = siblingByKey.get(change.key);
const domId = change.domId ?? sibling?.domId;
@@ -86,48 +81,17 @@ export function applyTimelineStackingReorder(input: {
key: change.key,
});
}
-
if (commitEntries.length === 0) return Promise.resolve();
- return input.commit?.(commitEntries) ?? Promise.resolve();
-}
-
-/**
- * Remove the keyframes currently selected in the player store from the active
- * element's GSAP animation. Reads selection lazily so it stays correct when
- * invoked from a ref callback. Extracted from StudioApp to keep it under the
- * studio 600-LOC cap.
- */
-export function deleteSelectedKeyframes(session: {
- selectedGsapAnimations: readonly { id: string; keyframes?: unknown }[];
- handleGsapRemoveKeyframe: (animId: string, pct: number) => void;
-}): void {
- const { selectedKeyframes, selectedElementId } = usePlayerStore.getState();
- const animation = session.selectedGsapAnimations.find((anim) => anim.keyframes);
- if (!animation) return;
- // Only the active element's keyframes; a stale cross-element selection must not delete here.
- for (const pct of selectedKeyframePercentagesForElement(selectedKeyframes, selectedElementId)) {
- session.handleGsapRemoveKeyframe(animation.id, pct);
- }
+ return input.commit?.(commitEntries, input.coalesceKey) ?? Promise.resolve();
}
-
export function extendRootDurationIfNeeded(newEnd: number): boolean {
const store = usePlayerStore.getState();
if (newEnd <= store.duration) return false;
store.setDuration(newEnd);
return true;
}
-
// ── Types ──
-
-export interface RecordEditInput {
- label: string;
- kind: EditHistoryKind;
- coalesceKey?: string;
- /** Per-entry coalesce window override (ms); lets a slow follow-up still merge. */
- coalesceMs?: number;
- files: Record<string, { before: string; after: string }>;
-}
-
+export type { RecordEditInput } from "../utils/studioFileHistory";
export function buildPatchTarget(element: {
domId?: string;
hfId?: string;
@@ -150,9 +114,7 @@ export function buildPatchTarget(element: {
}
return null;
}
-
export type PatchTarget = NonNullable<ReturnType<typeof buildPatchTarget>>;
-
// The runtime re-reads data-start/data-duration from the DOM on each sync tick
// (packages/core/src/runtime/init.ts:1324-1368), so attribute mutations here are
// picked up automatically on the next frame without a rebind call.
@@ -172,7 +134,6 @@ export function findTimelineElementInIframe(
return null;
}
}
-
export function patchIframeDomTiming(
iframe: HTMLIFrameElement | null,
element: TimelineElement,
@@ -186,7 +147,6 @@ export function patchIframeDomTiming(
// Cross-origin or mid-navigation — file save is enqueued; iframe patch is best-effort.
}
}
-
function postRootDurationToPreview(
iframe: HTMLIFrameElement | null,
durationSeconds: number,
@@ -203,7 +163,6 @@ function postRootDurationToPreview(
"*",
);
}
-
// fallow-ignore-next-line complexity
function resolveResizePlaybackStart(
original: string,
@@ -236,12 +195,26 @@ export function buildTimelineMoveTimingPatch(
target: PatchTarget,
start: number,
duration: number,
+ track?: number,
): string {
- const patched = applyPatchByTarget(original, target, {
+ if (!Number.isFinite(start) || !Number.isFinite(duration)) {
+ console.warn(
+ `[Timeline] buildTimelineMoveTimingPatch: non-finite timing (start=${start}, duration=${duration}) — patch skipped`,
+ );
+ return original;
+ }
+ let patched = applyPatchByTarget(original, target, {
type: "attribute",
property: "start",
value: formatTimelineAttributeNumber(start),
});
+ if (track != null && Number.isFinite(track)) {
+ patched = applyPatchByTarget(patched, target, {
+ type: "attribute",
+ property: "track-index",
+ value: formatTimelineAttributeNumber(track),
+ });
+ }
return extendRootDurationInSource(patched, start + duration);
}
@@ -595,5 +568,6 @@ export function foldedScaleGsapMutation(input: {
});
}
-// Re-export applyPatchByTarget for use in the hook (avoids double import in callers)
export { applyPatchByTarget, formatTimelineAttributeNumber };
+
+export { patchDocumentRootDuration } from "./timelineEditingGsap";
diff --git a/packages/studio/src/hooks/timelineMoveAdapter.test.ts b/packages/studio/src/hooks/timelineMoveAdapter.test.ts
new file mode 100644
index 0000000000..65b77c9451
--- /dev/null
+++ b/packages/studio/src/hooks/timelineMoveAdapter.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it, vi } from "vitest";
+import type { TimelineElement } from "../player";
+import { persistTimelineMoveEditsAtomically } from "./timelineMoveAdapter";
+
+const element = (id: string, track: number): TimelineElement => ({
+ id,
+ key: id,
+ tag: "div",
+ start: 0,
+ duration: 2,
+ track,
+});
+
+describe("persistTimelineMoveEditsAtomically", () => {
+ it("persists two vertical edits as one group with the gesture coalesce key", async () => {
+ const handleTimelineGroupMove = vi.fn().mockResolvedValue(undefined);
+ const edits = [
+ { element: element("a", 0), updates: { start: 1, track: 1 } },
+ { element: element("b", 1), updates: { start: 3, track: 2 } },
+ ];
+ await persistTimelineMoveEditsAtomically(edits, "clip-lane-move:7", "track-insert", {
+ handleTimelineGroupMove,
+ });
+ expect(handleTimelineGroupMove).toHaveBeenCalledTimes(1);
+ expect(handleTimelineGroupMove).toHaveBeenCalledWith(
+ [
+ { element: edits[0].element, start: 1, track: 1 },
+ { element: edits[1].element, start: 3, track: 2 },
+ ],
+ { coalesceKey: "clip-lane-move:7" },
+ );
+ });
+
+ it("does not persist track attrs for a single z-only lane reorder", async () => {
+ const handleTimelineGroupMove = vi.fn().mockResolvedValue(undefined);
+ const edit = { element: element("a", 0), updates: { start: 1, track: 1 } };
+ await persistTimelineMoveEditsAtomically([edit], "clip-lane-move:7", "lane-reorder", {
+ handleTimelineGroupMove,
+ });
+ expect(handleTimelineGroupMove).toHaveBeenCalledWith([{ element: edit.element, start: 1 }], {
+ coalesceKey: "clip-lane-move:7",
+ });
+ });
+
+ it("does not persist track attrs for a multi-selection lane drag", async () => {
+ const handleTimelineGroupMove = vi.fn().mockResolvedValue(undefined);
+ const edits = [
+ { element: element("a", 0), updates: { start: 1, track: 1 } },
+ { element: element("b", 2), updates: { start: 3, track: 2 } },
+ ];
+ await persistTimelineMoveEditsAtomically(edits, "clip-lane-move:7", "lane-reorder", {
+ handleTimelineGroupMove,
+ });
+ expect(handleTimelineGroupMove).toHaveBeenCalledWith(
+ [
+ { element: edits[0].element, start: 1 },
+ { element: edits[1].element, start: 3 },
+ ],
+ { coalesceKey: "clip-lane-move:7" },
+ );
+ });
+
+ it("rejects without retrying individual members when the atomic batch fails", async () => {
+ const failure = new Error("batch failed");
+ const handleTimelineGroupMove = vi.fn().mockRejectedValue(failure);
+ const edits = [
+ { element: element("a", 0), updates: { start: 1, track: 1 } },
+ { element: element("b", 1), updates: { start: 3, track: 2 } },
+ ];
+ await expect(
+ persistTimelineMoveEditsAtomically(edits, "clip-lane-move:7", "track-insert", {
+ handleTimelineGroupMove,
+ }),
+ ).rejects.toBe(failure);
+ expect(handleTimelineGroupMove).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/studio/src/hooks/timelineMoveAdapter.ts b/packages/studio/src/hooks/timelineMoveAdapter.ts
new file mode 100644
index 0000000000..e64c770763
--- /dev/null
+++ b/packages/studio/src/hooks/timelineMoveAdapter.ts
@@ -0,0 +1,37 @@
+import type { TimelineElement } from "../player";
+import type {
+ TimelineGroupCommitOptions,
+ TimelineGroupMoveChange,
+} from "./useTimelineGroupEditing";
+
+interface MoveEdit {
+ element: TimelineElement;
+ updates: Pick<TimelineElement, "start" | "track">;
+}
+
+interface AtomicMoveDeps {
+ handleTimelineGroupMove: (
+ changes: TimelineGroupMoveChange[],
+ options?: TimelineGroupCommitOptions,
+ ) => Promise<void>;
+}
+
+export type TimelineMoveOperation = "timing" | "lane-reorder" | "track-insert";
+
+export function persistTimelineMoveEditsAtomically(
+ edits: MoveEdit[],
+ coalesceKey: string | undefined,
+ operation: TimelineMoveOperation,
+ deps: AtomicMoveDeps,
+): Promise<void> {
+ return deps.handleTimelineGroupMove(
+ edits.map(({ element, updates }) => ({
+ element,
+ start: updates.start,
+ // A single vertical edit is the z-only reorder path. Multi-edit gestures
+ // are track inserts/ripples and must persist every resulting lane index.
+ track: operation === "track-insert" ? updates.track : undefined,
+ })),
+ { coalesceKey },
+ );
+}
diff --git a/packages/studio/src/hooks/useAnimatedPropertyCommit.test.tsx b/packages/studio/src/hooks/useAnimatedPropertyCommit.test.tsx
index f5eeed3d35..f969b661dd 100644
--- a/packages/studio/src/hooks/useAnimatedPropertyCommit.test.tsx
+++ b/packages/studio/src/hooks/useAnimatedPropertyCommit.test.tsx
@@ -1,12 +1,12 @@
// @vitest-environment happy-dom
import React, { act } from "react";
-import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import { usePlayerStore } from "../player/store/playerStore";
import { useAnimatedPropertyCommit } from "./useAnimatedPropertyCommit";
+import { mountReactHarness } from "./domSelectionTestHarness";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -58,13 +58,7 @@ function renderHookWith(
onReady(commitAnimatedProperties);
return null;
}
- const host = document.createElement("div");
- document.body.append(host);
- const root = createRoot(host);
- act(() => {
- root.render(<Harness />);
- });
- return root;
+ return mountReactHarness(<Harness />);
}
function renderCommitHook(
@@ -163,4 +157,38 @@ describe("commitStaticSet group routing", () => {
expect(update!.mutation.animationId).toBe("#box-set-0-position");
expect(update!.label).toBe("Move layer");
});
+
+ it("width edit updates its duration-zero size hold instead of appending a set", async () => {
+ const instantSizeHold = {
+ id: "#box-to-0-size",
+ targetSelector: "#box",
+ propertyGroup: "size",
+ method: "to",
+ properties: { width: 150, height: 150 },
+ resolvedStart: 0,
+ duration: 0,
+ extras: { immediateRender: "__raw:true" },
+ } as unknown as GsapAnimation;
+ const committed: Array<{ mutation: Record<string, unknown>; label: string }> = [];
+ let commit!: Commit;
+ renderHookWith(
+ [positionSet, instantSizeHold],
+ (mutation, label) => committed.push({ mutation, label }),
+ (c) => (commit = c),
+ );
+
+ await act(async () => {
+ await commit(selection, { width: 344 });
+ });
+
+ expect(committed).toHaveLength(1);
+ expect(committed[0]!.mutation).toEqual({
+ type: "update-properties",
+ animationId: instantSizeHold.id,
+ properties: { width: 344 },
+ });
+ expect(committed[0]!.label).toBe("Resize layer");
+ expect(committed.some(({ mutation }) => mutation.type === "add")).toBe(false);
+ expect(committed[0]!.mutation.animationId).not.toBe(positionSet.id);
+ });
});
diff --git a/packages/studio/src/hooks/useAnimatedPropertyCommit.ts b/packages/studio/src/hooks/useAnimatedPropertyCommit.ts
index e1cd37b967..a454a4bf66 100644
--- a/packages/studio/src/hooks/useAnimatedPropertyCommit.ts
+++ b/packages/studio/src/hooks/useAnimatedPropertyCommit.ts
@@ -14,7 +14,7 @@ import type { DomEditSelection } from "../components/editor/domEditingTypes";
import { usePlayerStore } from "../player/store/playerStore";
import { readAllAnimatedProperties, readGsapProperty } from "./gsapRuntimeBridge";
import type { SetPatchProps } from "./gsapRuntimePatch";
-import { selectorFromSelection, computeElementPercentage } from "./gsapShared";
+import { selectorFromSelection, computeElementPercentage, isInstantHold } from "./gsapShared";
import { resolveTweenStart, resolveTweenDuration } from "../utils/globalTimeCompiler";
import { roundTo3 } from "../utils/rounding";
import { commitWholePropertyOffset } from "./gsapWholePropertyOffsetCommit";
@@ -161,8 +161,8 @@ async function commitSetProps(
/**
* Static element (no keyframes on ANY of its tweens): persist the 3D props as a
* `tl.set` — NEVER keyframes. Mirrors manual drag / resize / rotate, which `tl.set`
- * a static element instead of animating it. Updates an existing `set` in place, or
- * creates a dedicated `set` at position 0 when the element has none.
+ * a static element instead of animating it. Updates an existing same-group static
+ * hold in place, or creates a dedicated `set` at position 0 when the element has none.
*/
async function commitStaticSet(
selection: DomEditSelection,
@@ -172,12 +172,12 @@ async function commitStaticSet(
commit: Commit,
): Promise<void> {
if (!selector) return;
- // One commit per PROPERTY GROUP, each into a set that owns that group — never a
- // flat `to`/`from`, and never a foreign-group set (a width edit used to merge
- // into the element's position set, producing a mixed set the split machinery
- // exists to prevent). Within a group everything batches into ONE commit: a
- // set's id is group-derived, so a per-prop loop would shift the id mid-way and
- // 404 the next update.
+ // One commit per PROPERTY GROUP, each into a static write that owns that group —
+ // never a live tween, and never a foreign-group write (a width edit used to
+ // merge into the element's position set, producing a mixed write the split
+ // machinery exists to prevent). Within a group everything batches into ONE
+ // commit: a write's id is group-derived, so a per-prop loop would shift the id
+ // mid-way and 404 the next update.
const byGroup = new Map<string, [string, number | string][]>();
for (const entry of propEntries) {
const group = classifyPropertyGroup(entry[0]);
@@ -185,24 +185,24 @@ async function commitStaticSet(
batch.push(entry);
byGroup.set(group, batch);
}
- const sets = animations.filter((a) => a.method === "set" && a.targetSelector === selector);
+ const staticWrites = animations.filter((a) => isInstantHold(a) && a.targetSelector === selector);
// Resolve every group's target BEFORE committing anything, and coalesce
- // groups that land on the SAME set into one commit: the `sets` snapshot is
- // captured once, so if two groups resolved to one legacy mixed set, a first
+ // groups that land on the SAME write into one commit: the snapshot is captured
+ // once, so if two groups resolved to one legacy mixed write, a first
// commit could re-shape it server-side and leave the second chasing a stale
// id (404 on legacy pre-split files).
- const byTargetSet = new Map<GsapAnimation, [string, number | string][]>();
+ const byTargetWrite = new Map<GsapAnimation, [string, number | string][]>();
const newSetBatches: [string, number | string][][] = [];
for (const [group, batch] of byGroup) {
- const existingSet = findGroupOwningSet(sets, group);
- if (existingSet) {
- byTargetSet.set(existingSet, [...(byTargetSet.get(existingSet) ?? []), ...batch]);
+ const existingWrite = findGroupOwningStaticWrite(staticWrites, group);
+ if (existingWrite) {
+ byTargetWrite.set(existingWrite, [...(byTargetWrite.get(existingWrite) ?? []), ...batch]);
} else {
newSetBatches.push(batch);
}
}
- for (const [targetSet, batch] of byTargetSet) {
- await commitSetProps(selection, targetSet, batch, selector, animations, commit);
+ for (const [targetWrite, batch] of byTargetWrite) {
+ await commitSetProps(selection, targetWrite, batch, selector, animations, commit);
}
// Fresh adds don't reshape existing sets, so their ids can't go stale.
for (const batch of newSetBatches) {
@@ -211,14 +211,19 @@ async function commitStaticSet(
}
/**
- * The set that owns a property group: one already dedicated to the group wins;
- * else a mixed set that already carries a property of the group (merging
- * same-group values there beats spawning a second writer for the channel).
+ * The static write that owns a property group: one already dedicated to the
+ * group wins; else a mixed write that already carries a property of the group
+ * (merging same-group values there beats spawning a second writer for the channel).
*/
-function findGroupOwningSet(sets: GsapAnimation[], group: string): GsapAnimation | undefined {
+function findGroupOwningStaticWrite(
+ staticWrites: GsapAnimation[],
+ group: string,
+): GsapAnimation | undefined {
return (
- sets.find((a) => a.propertyGroup === group) ??
- sets.find((a) => Object.keys(a.properties).some((k) => classifyPropertyGroup(k) === group))
+ staticWrites.find((a) => a.propertyGroup === group) ??
+ staticWrites.find((a) =>
+ Object.keys(a.properties).some((k) => classifyPropertyGroup(k) === group),
+ )
);
}
@@ -445,8 +450,8 @@ export function useAnimatedPropertyCommit(deps: CommitAnimatedPropertyDeps) {
}
// Existing static hold on a NON-animated element — merge the props into the
- // `set` in place (maybeAutoKeyframeSet no-ops when nothing else is keyframed).
- if (anim?.method === "set") {
+ // same write (maybeAutoKeyframeSet no-ops when nothing else is keyframed).
+ if (anim && isInstantHold(anim)) {
await commitSetProps(
selection,
anim,
diff --git a/packages/studio/src/hooks/useAppHotkeys.ts b/packages/studio/src/hooks/useAppHotkeys.ts
index 77f6f57988..165bab8e69 100644
--- a/packages/studio/src/hooks/useAppHotkeys.ts
+++ b/packages/studio/src/hooks/useAppHotkeys.ts
@@ -4,7 +4,7 @@ import type { TimelineElement } from "../player";
import type { DomEditSelection } from "../components/editor/domEditing";
import type { LeftSidebarHandle } from "../components/sidebar/LeftSidebar";
import { STUDIO_MOTION_PATH } from "../components/editor/studioMotion";
-import { shouldHandleTimelineToggleHotkey, isEditableTarget } from "../utils/timelineDiscovery";
+import { isEditableTarget } from "../utils/timelineDiscovery";
import { shouldIgnoreHistoryShortcut } from "../utils/studioHelpers";
import { canSplitElement } from "../utils/timelineElementSplit";
import { STUDIO_RAZOR_TOOL_ENABLED } from "../components/editor/manualEditingAvailability";
@@ -81,6 +81,8 @@ interface HistoryResult {
reason?: string;
label?: string;
paths?: string[];
+ /** Per-file restored/previous content, used to soft-apply the preview. */
+ files?: Record<string, { previous: string; restored: string }>;
}
interface HistoryFileCallbacks {
readFile: (path: string) => Promise<string>;
@@ -96,7 +98,6 @@ interface EditHistoryHandle {
}
interface UseAppHotkeysParams {
- toggleTimelineVisibility: () => void;
handleTimelineElementDelete: (element: TimelineElement) => Promise<void>;
handleTimelineElementSplit: (element: TimelineElement, splitTime: number) => Promise<void>;
handleDomEditElementDelete: (selection: DomEditSelection) => Promise<void>;
@@ -108,7 +109,10 @@ interface UseAppHotkeysParams {
writeProjectFile: (path: string, content: string) => Promise<void>;
domEditSaveTimestampRef: React.MutableRefObject<number>;
showToast: (message: string, tone?: "error" | "info") => void;
- syncHistoryPreviewAfterApply: (paths: string[] | undefined) => Promise<void>;
+ syncHistoryPreviewAfterApply: (restore: {
+ paths?: string[];
+ files?: Record<string, { previous: string; restored: string }>;
+ }) => Promise<void>;
waitForPendingDomEditSaves: () => Promise<void>;
leftSidebarRef: React.RefObject<LeftSidebarHandle | null>;
handleCopy: () => boolean;
@@ -135,7 +139,6 @@ interface UseAppHotkeysParams {
// ── Extracted keydown dispatch (pure function, no hooks) ──
interface HotkeyCallbacks {
- toggleTimelineVisibility: () => void;
handleTimelineElementDelete: (element: TimelineElement) => Promise<void>;
handleTimelineElementSplit: (element: TimelineElement, splitTime: number) => Promise<void>;
handleDomEditElementDelete: (selection: DomEditSelection) => Promise<void>;
@@ -291,9 +294,14 @@ function dispatchPlainKey(event: KeyboardEvent, key: string, cb: HotkeyCallbacks
return;
}
}
- const { selectedElementId, elements } = usePlayerStore.getState();
- if (selectedElementId) {
- const el = elements.find((e) => (e.key ?? e.id) === selectedElementId);
+ // Delete acts on the primary selection OR the marquee multi-selection —
+ // the delete handler expands a clip that is part of the multi-selection
+ // into an atomic delete of the whole selection (single undo).
+ const { selectedElementId, selectedElementIds, elements } = usePlayerStore.getState();
+ const selectionKeys = new Set(selectedElementIds);
+ if (selectedElementId) selectionKeys.add(selectedElementId);
+ if (selectionKeys.size > 0) {
+ const el = elements.find((e) => selectionKeys.has(e.key ?? e.id));
if (el) {
event.preventDefault();
void cb.handleTimelineElementDelete(el);
@@ -317,7 +325,6 @@ function dispatchPlainKey(event: KeyboardEvent, key: string, cb: HotkeyCallbacks
// ── Hook ──
export function useAppHotkeys({
- toggleTimelineVisibility,
handleTimelineElementDelete,
handleTimelineElementSplit,
handleDomEditElementDelete,
@@ -346,15 +353,6 @@ export function useAppHotkeys({
const previewHotkeyWindowRef = useRef<Window | null>(null);
const previewHistoryCleanupRef = useRef<(() => void) | null>(null);
- const handleTimelineToggleHotkey = useCallback(
- (event: KeyboardEvent) => {
- if (!shouldHandleTimelineToggleHotkey(event)) return;
- event.preventDefault();
- toggleTimelineVisibility();
- },
- [toggleTimelineVisibility],
- );
-
// ── Undo / Redo ──
const readHistoryFile = useCallback(
@@ -397,7 +395,7 @@ export function useAppHotkeys({
if (activeCompPath && result.paths?.includes(activeCompPath)) {
forceReloadSdkSession?.();
}
- await syncHistoryPreviewAfterApply(result.paths);
+ await syncHistoryPreviewAfterApply({ paths: result.paths, files: result.files });
showToast(`${direction === "undo" ? "Undid" : "Redid"} ${result.label}`, "info");
}
},
@@ -421,7 +419,6 @@ export function useAppHotkeys({
const cbRef = useRef<HotkeyCallbacks>(null!);
cbRef.current = {
- toggleTimelineVisibility,
handleTimelineElementDelete,
handleTimelineElementSplit,
handleDomEditElementDelete,
@@ -444,11 +441,6 @@ export function useAppHotkeys({
const handleAppKeyDown = useCallback((event: KeyboardEvent) => {
const cb = cbRef.current;
- if (shouldHandleTimelineToggleHotkey(event)) {
- event.preventDefault();
- cb.toggleTimelineVisibility();
- return;
- }
const key = event.key.toLowerCase();
if (event.metaKey || event.ctrlKey) {
dispatchModifierKey(event, key, cb);
@@ -537,6 +529,5 @@ export function useAppHotkeys({
handleRedo,
syncPreviewTimelineHotkey,
syncPreviewHistoryHotkey,
- handleTimelineToggleHotkey,
};
}
diff --git a/packages/studio/src/hooks/useBlockHandlers.ts b/packages/studio/src/hooks/useBlockHandlers.ts
index a80afa1c8c..886c219ec4 100644
--- a/packages/studio/src/hooks/useBlockHandlers.ts
+++ b/packages/studio/src/hooks/useBlockHandlers.ts
@@ -2,7 +2,7 @@
* Block drop/add handlers for the Studio.
* Extracted from App.tsx to keep file sizes under the 600-line limit.
*/
-import { useCallback, useMemo, useState } from "react";
+import { useCallback, useMemo, useRef, useState } from "react";
import type { TimelineElement } from "../player";
import { usePlayerStore } from "../player";
import { addBlockToProject } from "../utils/blockInstaller";
@@ -83,17 +83,41 @@ export function useBlockHandlers({
],
);
+ // Block installs hit the server and end in a full preview reload; without a
+ // guard, repeat drops while one is in flight stack duplicate installs.
+ const installingBlockRef = useRef(false);
+ const runBlockInstall = useCallback(
+ async <T>(blockName: string, install: () => Promise<T>): Promise<T | null> => {
+ if (installingBlockRef.current) {
+ blockCtx.showToast("A block is already installing — one moment…", "info");
+ return null;
+ }
+ installingBlockRef.current = true;
+ blockCtx.showToast(`Adding ${blockName}…`, "info");
+ try {
+ return await install();
+ } finally {
+ installingBlockRef.current = false;
+ }
+ },
+ [blockCtx],
+ );
+
const handleAddBlock = useCallback(
(blockName: string) => {
if (!projectId) return;
+ // fallow-ignore-next-line complexity
void (async () => {
- const result = await addBlockToProject({
- projectId,
- blockName,
- ...blockCtx,
- previewIframe: previewIframeRef.current,
- currentTime: usePlayerStore.getState().currentTime,
- });
+ const result = await runBlockInstall(blockName, () =>
+ addBlockToProject({
+ projectId,
+ blockName,
+ ...blockCtx,
+ previewIframe: previewIframeRef.current,
+ currentTime: usePlayerStore.getState().currentTime,
+ }),
+ );
+ if (result === null) return;
const params = result?.block.type === "hyperframes:block" ? result.block.params : undefined;
if (params?.length) {
setActiveBlockParams({
@@ -107,37 +131,41 @@ export function useBlockHandlers({
}
})();
},
- [projectId, blockCtx, previewIframeRef, setRightCollapsed, setRightPanelTab],
+ [projectId, blockCtx, previewIframeRef, runBlockInstall, setRightCollapsed, setRightPanelTab],
);
const handleTimelineBlockDrop = useCallback(
(blockName: string, placement: { start: number; track: number }) => {
if (!projectId) return;
- void addBlockToProject({
- projectId,
- blockName,
- placement,
- ...blockCtx,
- previewIframe: previewIframeRef.current,
- currentTime: usePlayerStore.getState().currentTime,
- });
+ void runBlockInstall(blockName, () =>
+ addBlockToProject({
+ projectId,
+ blockName,
+ placement,
+ ...blockCtx,
+ previewIframe: previewIframeRef.current,
+ currentTime: usePlayerStore.getState().currentTime,
+ }),
+ );
},
- [projectId, blockCtx, previewIframeRef],
+ [projectId, blockCtx, previewIframeRef, runBlockInstall],
);
const handlePreviewBlockDrop = useCallback(
(blockName: string, position: { left: number; top: number }) => {
if (!projectId) return;
- void addBlockToProject({
- projectId,
- blockName,
- visualPosition: position,
- ...blockCtx,
- previewIframe: previewIframeRef.current,
- currentTime: usePlayerStore.getState().currentTime,
- });
+ void runBlockInstall(blockName, () =>
+ addBlockToProject({
+ projectId,
+ blockName,
+ visualPosition: position,
+ ...blockCtx,
+ previewIframe: previewIframeRef.current,
+ currentTime: usePlayerStore.getState().currentTime,
+ }),
+ );
},
- [projectId, blockCtx, previewIframeRef],
+ [projectId, blockCtx, previewIframeRef, runBlockInstall],
);
return {
diff --git a/packages/studio/src/hooks/useContextMenuDismiss.ts b/packages/studio/src/hooks/useContextMenuDismiss.ts
index c6d04579a6..796a84a495 100644
--- a/packages/studio/src/hooks/useContextMenuDismiss.ts
+++ b/packages/studio/src/hooks/useContextMenuDismiss.ts
@@ -1,26 +1,50 @@
import { useCallback, useEffect, useRef, type RefObject } from "react";
/**
- * Shared dismiss logic for context menus: closes on outside click or Escape.
- * Returns a ref to attach to the menu container element.
+ * Shared dismiss logic for context menus: closes on ANY pointerdown outside the
+ * menu (mouse, pen, or touch), or Escape.
+ *
+ * Two failure modes this guards against, both seen in the canvas editor:
+ *
+ * 1. The menu lives inside DomEditOverlay, whose own pointer handlers call
+ * `event.stopPropagation()` on several branches (marquee start, shift-select).
+ * A bubble-phase `mousedown`/`pointerdown` listener on `document` never fires
+ * for those events — the overlay eats them first — so the menu stayed open.
+ * Listening in the CAPTURE phase runs this dismiss BEFORE any bubble-phase
+ * stopPropagation, so an outside press always closes the menu.
+ *
+ * 2. `mousedown` alone misses pointer/touch-only gestures. `pointerdown` is the
+ * superset (fires for mouse, pen, and touch) and is exactly the event the
+ * overlay itself acts on, so hooking it here dismisses on the same press that
+ * starts a canvas gesture — no second click required.
*/
export function useContextMenuDismiss(onClose: () => void): RefObject<HTMLDivElement | null> {
const menuRef = useRef<HTMLDivElement>(null);
const dismiss = useCallback(
- (e: MouseEvent | KeyboardEvent) => {
- if (e instanceof KeyboardEvent && e.key !== "Escape") return;
- if (e instanceof MouseEvent && menuRef.current?.contains(e.target as Node)) return;
+ (e: PointerEvent | MouseEvent | KeyboardEvent) => {
+ if (e instanceof KeyboardEvent) {
+ if (e.key === "Escape") onClose();
+ return;
+ }
+ // Any press inside the menu is a menu interaction — leave it open (the
+ // item's own handler will close it after acting).
+ if (menuRef.current?.contains(e.target as Node)) return;
onClose();
},
[onClose],
);
useEffect(() => {
- document.addEventListener("mousedown", dismiss);
+ // Capture phase so overlay/iframe-side handlers that stopPropagation on the
+ // bubble phase can't swallow the dismiss. `pointerdown` covers mouse + touch
+ // + pen; keep `mousedown` too for any synthetic-mouse path that skips it.
+ document.addEventListener("pointerdown", dismiss, true);
+ document.addEventListener("mousedown", dismiss, true);
document.addEventListener("keydown", dismiss);
return () => {
- document.removeEventListener("mousedown", dismiss);
+ document.removeEventListener("pointerdown", dismiss, true);
+ document.removeEventListener("mousedown", dismiss, true);
document.removeEventListener("keydown", dismiss);
};
}, [dismiss]);
diff --git a/packages/studio/src/hooks/useDomEditCommits.test.tsx b/packages/studio/src/hooks/useDomEditCommits.test.tsx
index b56f04fe18..410d3700c9 100644
--- a/packages/studio/src/hooks/useDomEditCommits.test.tsx
+++ b/packages/studio/src/hooks/useDomEditCommits.test.tsx
@@ -6,6 +6,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { MutableRefObject } from "react";
import type { DomEditSelection, DomEditTextField } from "../components/editor/domEditing";
import type { ImportedFontAsset } from "../components/editor/fontAssets";
+import { usePlayerStore } from "../player";
import { StudioSaveHttpError } from "../utils/studioSaveDiagnostics";
import { trackStudioEvent } from "../utils/studioTelemetry";
import { useDomEditCommits } from "./useDomEditCommits";
@@ -27,6 +28,7 @@ interface RenderedDomEditCommits {
hook: ReturnType<typeof useDomEditCommits>;
showToast: ReturnType<typeof makeShowToast>;
recordEdit: ReturnType<typeof vi.fn<() => Promise<void>>>;
+ reloadPreview: ReturnType<typeof vi.fn>;
cleanup: () => void;
}
@@ -209,6 +211,7 @@ function renderDomEditCommits(
const previewIframeRef: MutableRefObject<HTMLIFrameElement | null> = { current: iframe };
const projectIdRef: MutableRefObject<string | null> = { current: "p1" };
const domEditSaveTimestampRef: MutableRefObject<number> = { current: 0 };
+ const reloadPreview = vi.fn();
function Probe() {
captured.current = useDomEditCommits({
@@ -223,7 +226,7 @@ function renderDomEditCommits(
importedFontAssetsRef: { current: options.importedFontAssets ?? [] },
projectId: "p1",
projectIdRef,
- reloadPreview: vi.fn(),
+ reloadPreview,
domEditSelection: selection,
applyDomSelection: vi.fn(),
clearDomSelection: vi.fn(),
@@ -244,6 +247,7 @@ function renderDomEditCommits(
hook: captured.current,
showToast,
recordEdit,
+ reloadPreview,
cleanup: () => {
act(() => {
root.unmount();
@@ -253,6 +257,155 @@ function renderDomEditCommits(
} satisfies RenderedDomEditCommits;
}
+describe("useDomEditCommits z-index reorder persistence", () => {
+ beforeEach(() => {
+ ensureCssEscape();
+ vi.clearAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+ });
+
+ it("persists an N-element reorder with one batch POST, one undo entry, and one reload", async () => {
+ const original =
+ '<div id="a" style="z-index: 1"></div><div id="b" style="z-index: 2"></div><div id="c" style="z-index: 3"></div>';
+ const after =
+ '<div id="a" style="z-index: 3"></div><div id="b" style="z-index: 2"></div><div id="c" style="z-index: 1"></div>';
+ const fetchMock = vi.fn(
+ async (
+ input: Parameters<typeof fetch>[0],
+ _init?: Parameters<typeof fetch>[1],
+ ): Promise<Response> => {
+ const url = requestUrl(input);
+ if (url.includes("/api/projects/p1/files/")) return jsonResponse({ content: original });
+ if (url.includes("/file-mutations/patch-elements-batch/")) {
+ return jsonResponse({
+ ok: true,
+ changed: true,
+ matched: [true, true, true],
+ content: after,
+ });
+ }
+ if (url.includes("/file-mutations/patch-element/")) {
+ return jsonResponse({ ok: true, changed: true, matched: true, content: after });
+ }
+ throw new Error(`Unexpected fetch: ${url}`);
+ },
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const { iframe, element } = createPreviewElement(
+ '<div data-hf-id="hf-card"></div><div id="b"></div><div id="c"></div>',
+ );
+ element.id = "a";
+ const elements = [
+ element,
+ iframe.contentDocument!.getElementById("b")!,
+ iframe.contentDocument!.getElementById("c")!,
+ ];
+ const rendered = renderDomEditCommits(createSelection(element), iframe);
+
+ try {
+ await act(async () => {
+ await rendered.hook.handleDomZIndexReorderCommit(
+ elements.map((item, index) => ({
+ element: item,
+ zIndex: 3 - index,
+ id: item.id,
+ sourceFile: "index.html",
+ })),
+ "z-reorder:test",
+ );
+ });
+
+ const batchPosts = fetchMock.mock.calls.filter(([input]) =>
+ requestUrl(input).includes("/file-mutations/patch-elements-batch/"),
+ );
+ const singlePosts = fetchMock.mock.calls.filter(([input]) =>
+ requestUrl(input).includes("/file-mutations/patch-element/"),
+ );
+ 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" }) }),
+ ]),
+ });
+ expect(rendered.recordEdit).toHaveBeenCalledTimes(1);
+ expect(rendered.recordEdit).toHaveBeenCalledWith({
+ label: "Reorder layers",
+ kind: "manual",
+ coalesceKey: "z-reorder:test",
+ files: { "index.html": { before: original, after } },
+ });
+ expect(rendered.reloadPreview).toHaveBeenCalledTimes(1);
+ } finally {
+ rendered.cleanup();
+ }
+ });
+
+ 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>';
+ 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({ error: "batch rejected" }, 500);
+ }
+ throw new Error(`Unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ const writeProjectFile = vi.fn(async () => {});
+ const { iframe, element } = createPreviewElement(
+ '<div data-hf-id="hf-card" style="z-index: 7"></div><div id="b"></div>',
+ );
+ element.id = "a";
+ const second = iframe.contentDocument!.getElementById("b")!;
+ usePlayerStore.getState().setElements([
+ { id: "a", tag: "div", start: 0, duration: 1, track: 0, zIndex: 7, hasExplicitZIndex: true },
+ { id: "b", tag: "div", start: 0, duration: 1, track: 1, zIndex: 0, hasExplicitZIndex: false },
+ ]);
+ const rendered = renderDomEditCommits(createSelection(element), iframe, { writeProjectFile });
+
+ try {
+ let rejection: unknown;
+ await act(async () => {
+ try {
+ await rendered.hook.handleDomZIndexReorderCommit([
+ { element, zIndex: 2, id: "a", sourceFile: "index.html", key: "a" },
+ { element: second, zIndex: 1, id: "b", sourceFile: "index.html", key: "b" },
+ ]);
+ } catch (error) {
+ rejection = error;
+ }
+ });
+
+ expect(rejection).toBeInstanceOf(Error);
+ expect((rejection as Error).message).toContain("batch rejected");
+ expect(element.style.zIndex).toBe("7");
+ expect(second.style.zIndex).toBe("");
+ expect(
+ usePlayerStore
+ .getState()
+ .elements.map(({ zIndex, hasExplicitZIndex }) => ({ zIndex, hasExplicitZIndex })),
+ ).toEqual([
+ { zIndex: 7, hasExplicitZIndex: true },
+ { zIndex: 0, hasExplicitZIndex: false },
+ ]);
+ expect(writeProjectFile).not.toHaveBeenCalled();
+ expect(rendered.recordEdit).not.toHaveBeenCalled();
+ expect(rendered.reloadPreview).not.toHaveBeenCalled();
+ expect(
+ fetchMock.mock.calls.filter(([input]) =>
+ requestUrl(input).includes("/file-mutations/patch-elements-batch/"),
+ ),
+ ).toHaveLength(1);
+ } finally {
+ rendered.cleanup();
+ }
+ });
+});
+
async function commitStyleAgainst(response: Parameters<typeof stubPatchFetch>[0]) {
stubPatchFetch(response);
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
diff --git a/packages/studio/src/hooks/useDomEditCommits.ts b/packages/studio/src/hooks/useDomEditCommits.ts
index 3ae522f837..349d1889ba 100644
--- a/packages/studio/src/hooks/useDomEditCommits.ts
+++ b/packages/studio/src/hooks/useDomEditCommits.ts
@@ -4,11 +4,19 @@ import { FONT_EXT } from "../utils/mediaTypes";
import { trackStudioEvent } from "../utils/studioTelemetry";
import { primaryFontFamilyValue } from "../utils/studioFontHelpers";
-import { createStudioSaveHttpError } from "../utils/studioSaveDiagnostics";
+import {
+ createStudioSaveHttpError,
+ StudioSaveHttpError,
+ trackStudioSaveFailure,
+} from "../utils/studioSaveDiagnostics";
import { buildDomEditPatchTarget, type DomEditSelection } from "../components/editor/domEditing";
import { fontFamilyFromAssetPath, type ImportedFontAsset } from "../components/editor/fontAssets";
import type { EditHistoryKind } from "../utils/editHistory";
-import type { PersistDomEditOperations } from "./domEditCommitTypes";
+import type {
+ CommitDomEditPatchBatches,
+ DomEditPatchBatch,
+ PersistDomEditOperations,
+} from "./domEditCommitTypes";
import type { PatchOperation } from "../utils/sourcePatcher";
import {
DomEditPersistUnsafeValueError,
@@ -20,6 +28,7 @@ import { useDomEditTextCommits } from "./useDomEditTextCommits";
import { useDomGeometryCommits } from "./useDomGeometryCommits";
import { useElementLifecycleOps } from "./useElementLifecycleOps";
import { formatFieldsSuffix } from "./gsapScriptCommitHelpers";
+import { readProjectFileContent } from "../utils/studioFileHistory";
// ── Helpers ──
@@ -48,9 +57,36 @@ interface RecordEditInput {
label: string;
kind: EditHistoryKind;
coalesceKey?: string;
+ coalesceMs?: number;
files: Record<string, { before: string; after: string }>;
}
+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 }),
+ },
+ );
+ if (!response.ok) {
+ const rejection = await readErrorResponseBody(response);
+ throw new StudioSaveHttpError(formatPatchRejectionMessage(rejection), response.status);
+ }
+ const result = (await response.json()) as {
+ changed?: boolean;
+ content?: string;
+ };
+ return {
+ sourceFile: batch.sourceFile,
+ changed: result.changed === true,
+ before,
+ after: typeof result.content === "string" ? result.content : before,
+ };
+}
+
export interface UseDomEditCommitsParams {
activeCompPath: string | null;
previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>;
@@ -271,6 +307,7 @@ export function useDomEditCommits({
label: options?.label ?? "Edit layer",
kind: "manual",
coalesceKey: options?.coalesceKey,
+ coalesceMs: options?.coalesceMs,
files: { [targetPath]: { before: originalContent, after: finalContent } },
});
forceReloadSdkSession?.();
@@ -292,6 +329,66 @@ 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 },
+ );
+ }
+
+ 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?.();
+ reloadPreview();
+ }).catch((error) => {
+ const alreadyToasted =
+ (error instanceof StudioSaveHttpError ||
+ error instanceof DomEditPersistUnsafeValueError) &&
+ error.alreadyToasted;
+ if (!alreadyToasted) {
+ showToast(error instanceof Error ? error.message : "Failed to reorder layers", "error");
+ }
+ trackStudioSaveFailure({
+ source: "dom_edit",
+ error,
+ filePath: batches.map((batch) => batch.sourceFile).join(","),
+ mutationType: "z-reorder",
+ label: options.label,
+ });
+ throw error;
+ }),
+ [
+ domEditSaveTimestampRef,
+ editHistory,
+ forceReloadSdkSession,
+ projectIdRef,
+ queueDomEditSave,
+ reloadPreview,
+ showToast,
+ ],
+ );
+
// ── Text & style commits (delegated to useDomEditTextCommits) ──
const {
@@ -352,7 +449,7 @@ export function useDomEditCommits({
onTrySdkDelete,
onReorderShadow,
forceReloadSdkSession,
- commitPositionPatchToHtml,
+ commitDomEditPatchBatches,
});
return {
diff --git a/packages/studio/src/hooks/useDomEditPositionPatchCommit.ts b/packages/studio/src/hooks/useDomEditPositionPatchCommit.ts
index 335658011e..1141a91d7c 100644
--- a/packages/studio/src/hooks/useDomEditPositionPatchCommit.ts
+++ b/packages/studio/src/hooks/useDomEditPositionPatchCommit.ts
@@ -15,6 +15,7 @@ interface UseDomEditPositionPatchCommitParams {
interface PositionPatchOptions {
label: string;
coalesceKey: string;
+ coalesceMs?: number;
skipRefresh?: boolean;
}
@@ -30,6 +31,7 @@ export function useDomEditPositionPatchCommit({
await persistDomEditOperations(selection, patches, {
label: options.label,
coalesceKey: options.coalesceKey,
+ coalesceMs: options.coalesceMs,
skipRefresh: options.skipRefresh ?? true,
});
}).catch((error) => {
diff --git a/packages/studio/src/hooks/useDomEditSession.ts b/packages/studio/src/hooks/useDomEditSession.ts
index 182cc5251e..f8cba7f987 100644
--- a/packages/studio/src/hooks/useDomEditSession.ts
+++ b/packages/studio/src/hooks/useDomEditSession.ts
@@ -1,6 +1,6 @@
import { useCallback } from "react";
import { trackStudioEvent } from "../utils/studioTelemetry";
-import type { TimelineElement } from "../player";
+import type { SelectElementOptions, TimelineElement } from "../player";
import type { ImportedFontAsset } from "../components/editor/fontAssets";
import type { EditHistoryKind } from "../utils/editHistory";
import type { RightPanelTab } from "../utils/studioHelpers";
@@ -38,7 +38,7 @@ export interface UseDomEditSessionParams {
compositionLoading: boolean;
previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>;
timelineElements: TimelineElement[];
- setSelectedTimelineElementId: (id: string | null) => void;
+ setSelectedTimelineElementId: (id: string | null, options?: SelectElementOptions) => void;
setRightCollapsed: (collapsed: boolean) => void;
setRightPanelTab: (tab: RightPanelTab) => void;
showToast: (message: string, tone?: "error" | "info") => void;
diff --git a/packages/studio/src/hooks/useDomEditTextCommits.test.tsx b/packages/studio/src/hooks/useDomEditTextCommits.test.tsx
new file mode 100644
index 0000000000..7632880dae
--- /dev/null
+++ b/packages/studio/src/hooks/useDomEditTextCommits.test.tsx
@@ -0,0 +1,135 @@
+// @vitest-environment jsdom
+import { act } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { DomEditSelection, DomEditTextField } from "../components/editor/domEditing";
+import { mountReactHarness } from "./domSelectionTestHarness";
+import { useDomEditTextCommits, type UseDomEditTextCommitsParams } from "./useDomEditTextCommits";
+
+Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true);
+
+interface Deferred<T> {
+ promise: Promise<T>;
+ resolve: (value: T | PromiseLike<T>) => void;
+ reject: (reason?: unknown) => void;
+}
+
+function createDeferred<T>(): Deferred<T> {
+ let resolve: Deferred<T>["resolve"] | undefined;
+ let reject: Deferred<T>["reject"] | undefined;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ if (!resolve || !reject) throw new Error("deferred callbacks were not initialized");
+ return { promise, resolve, reject };
+}
+
+function textField(value: string): DomEditTextField {
+ return {
+ key: "self",
+ label: "Text",
+ value,
+ tagName: "div",
+ attributes: [],
+ inlineStyles: {},
+ computedStyles: {},
+ source: "self",
+ };
+}
+
+function selectionFor(element: HTMLElement): DomEditSelection {
+ return {
+ id: element.id,
+ element,
+ label: "Card",
+ tagName: "div",
+ sourceFile: "index.html",
+ compositionPath: "index.html",
+ isCompositionHost: false,
+ isInsideLockedComposition: false,
+ boundingBox: { x: 0, y: 0, width: 100, height: 100 },
+ textContent: element.textContent,
+ dataAttributes: {},
+ inlineStyles: {},
+ computedStyles: {},
+ textFields: [textField(element.textContent ?? "")],
+ capabilities: {
+ canSelect: true,
+ canEditStyles: true,
+ canCrop: true,
+ canMove: true,
+ canResize: true,
+ canApplyManualOffset: true,
+ canApplyManualSize: true,
+ canApplyManualRotation: true,
+ },
+ };
+}
+
+let cleanup: (() => void) | null = null;
+
+function renderTextCommitHook(params: UseDomEditTextCommitsParams) {
+ const captured: { hook: ReturnType<typeof useDomEditTextCommits> | null } = { hook: null };
+ function TextCommitProbe() {
+ captured.hook = useDomEditTextCommits(params);
+ return null;
+ }
+ const root = mountReactHarness(<TextCommitProbe />);
+ cleanup = () => act(() => root.unmount());
+ if (!captured.hook) throw new Error("hook did not initialize");
+ return captured.hook;
+}
+
+afterEach(() => {
+ cleanup?.();
+ cleanup = null;
+ document.body.replaceChildren();
+ vi.restoreAllMocks();
+});
+
+describe("useDomEditTextCommits", () => {
+ it("does not let a stale failed fields commit revert newer text", async () => {
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ const doc = iframe.contentDocument;
+ if (!doc) throw new Error("expected iframe document");
+ doc.body.innerHTML = '<div id="card">Original</div>';
+ const element = doc.getElementById("card");
+ const HTMLElementCtor = doc.defaultView?.HTMLElement;
+ if (!HTMLElementCtor || !(element instanceof HTMLElementCtor)) {
+ throw new Error("expected preview element");
+ }
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ const selection = selectionFor(element);
+ const stalePersist = createDeferred<void>();
+ const persistDomEditOperations = vi
+ .fn()
+ .mockImplementationOnce(() => stalePersist.promise)
+ .mockResolvedValueOnce(undefined);
+ const hook = renderTextCommitHook({
+ activeCompPath: "index.html",
+ previewIframeRef: { current: iframe },
+ showToast: vi.fn(),
+ domEditSelection: selection,
+ applyDomSelection: vi.fn(),
+ refreshDomEditSelectionFromPreview: vi.fn(),
+ buildDomSelectionFromTarget: vi.fn(async () => null),
+ persistDomEditOperations,
+ resolveImportedFontAsset: () => null,
+ });
+
+ let staleCommit: Promise<void> | undefined;
+ act(() => {
+ staleCommit = hook.commitDomTextFields(selection, [textField("Stale")]);
+ });
+ await act(async () => {
+ await hook.commitDomTextFields(selection, [textField("Newest")]);
+ });
+ stalePersist.reject(new Error("stale request failed"));
+ await act(async () => {
+ await staleCommit;
+ });
+
+ expect(element.innerHTML).toBe("Newest");
+ });
+});
diff --git a/packages/studio/src/hooks/useDomEditTextCommits.ts b/packages/studio/src/hooks/useDomEditTextCommits.ts
index 36061f1a19..cbce289123 100644
--- a/packages/studio/src/hooks/useDomEditTextCommits.ts
+++ b/packages/studio/src/hooks/useDomEditTextCommits.ts
@@ -174,7 +174,11 @@ export function useDomEditTextCommits({
let editedElement: HTMLElement | null = null;
let previousInlineValue: string | null = null;
const operations = buildDomStyleCommitOperations(property, value, isImageBackgroundCommit);
- const skipRefresh = property !== "z-index";
+ // Inline-style commits never full-reload the preview (that blanks the iframe
+ // until it re-renders): the live element was already mutated optimistically in
+ // apply(). z-index is no exception — setting `element.style.zIndex` restacks the
+ // element in-browser immediately, so a reload would only cost a black blink.
+ const skipRefresh = true;
await runDomEditCommit({
capture: () => {
@@ -305,6 +309,7 @@ export function useDomEditTextCommits({
nextTextFields: DomEditTextField[],
options?: { importedFont?: ImportedFontAsset | null },
) => {
+ const isLatestTextCommit = bumpDomEditCommitVersion(domTextCommitVersionRef);
const textCommit = planDomTextCommit(
selection.textFields,
nextTextFields,
@@ -344,14 +349,14 @@ export function useDomEditTextCommits({
: undefined,
});
},
- shouldRevert: () => true,
+ shouldRevert: () => isLatestTextCommit(),
revert: () => {
if (!editedElement || previousInnerHtml === null) return;
editedElement.innerHTML = previousInnerHtml;
},
onError: (error) =>
reportDomEditPersistFailure(selection, textCommit.operations, error, showToast),
- shouldResync: () => true,
+ shouldResync: isLatestTextCommit,
resync: () =>
resyncDomTextSelectionFromPreview(
doc,
diff --git a/packages/studio/src/hooks/useDomEditWiring.ts b/packages/studio/src/hooks/useDomEditWiring.ts
index c4c3706c1e..f598cb54e3 100644
--- a/packages/studio/src/hooks/useDomEditWiring.ts
+++ b/packages/studio/src/hooks/useDomEditWiring.ts
@@ -11,7 +11,6 @@ import { useCallback, useEffect, useRef } from "react";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import { STUDIO_GSAP_PANEL_ENABLED } from "../components/editor/manualEditingAvailability";
import { usePlayerStore } from "../player";
-import { resolveTimelineIdForSelection } from "../utils/studioHelpers";
import { useDomEditPreviewSync } from "./useDomEditPreviewSync";
import { useGsapAnimationsForElement, usePopulateKeyframeCacheForFile } from "./useGsapTweenCache";
import { useGsapAnimationFetchFallback } from "./useGsapAnimationFetchFallback";
@@ -171,14 +170,13 @@ export function useDomEditWiring({
useEffect(() => {
if (!domEditSelection?.id) return;
- const { selectedElementId, elements, setSelectionAnchor } = usePlayerStore.getState();
- // Resolve through the canonical resolver (source-file + ancestor + active-comp
- // fallback) rather than a narrow domId/id match, so a sub-composition selection
- // maps to the same clip the rest of the selection pipeline picks. Use the
- // anchor-only setter: this is a DOM->store echo and must not collapse a group.
- const key = resolveTimelineIdForSelection(domEditSelection, elements, activeCompPath);
- if (key && key !== selectedElementId) setSelectionAnchor(key);
- }, [domEditSelection, activeCompPath]);
+ const { selectedElementId, elements, setSelectedElementId } = usePlayerStore.getState();
+ const matchKey = elements.find(
+ (el) => el.domId === domEditSelection.id || el.id === domEditSelection.id,
+ );
+ const key = matchKey ? (matchKey.key ?? matchKey.id) : null;
+ if (key && key !== selectedElementId) setSelectedElementId(key);
+ }, [domEditSelection?.id]);
// ── GSAP cache sync ──
diff --git a/packages/studio/src/hooks/useDomGeometryCommits.ts b/packages/studio/src/hooks/useDomGeometryCommits.ts
index ab81e4adfc..667f3caea9 100644
--- a/packages/studio/src/hooks/useDomGeometryCommits.ts
+++ b/packages/studio/src/hooks/useDomGeometryCommits.ts
@@ -61,14 +61,29 @@ export function useDomGeometryCommits({
);
const handleDomBoxSizeCommit = useCallback(
- (selection: DomEditSelection, next: { width: number; height: number }) => {
+ (
+ selection: DomEditSelection,
+ next: { width: number; height: number },
+ offset?: { x: number; y: number },
+ ) => {
if (isElementGsapTargeted(previewIframeRef.current, selection.element)) {
const error = new Error(GSAP_CSS_FALLBACK_BLOCKED_MESSAGE);
showToast(error.message, "error");
return Promise.reject(error);
}
applyStudioBoxSize(selection.element, next);
- return commitPositionPatchToHtml(selection, buildBoxSizePatches(selection.element), {
+ // Anchored-corner resize (NW/NE/SW) also moves the element to keep the
+ // opposite corner fixed. Apply the offset and emit BOTH patch sets in a
+ // SINGLE commit: one persist = one undo entry, and there is no
+ // intermediate re-stamp where the new size is in source but the anchor
+ // offset is not (that frame was the release "jump"). Both builders read
+ // the already-mutated live element, so concatenation is safe.
+ const patches = buildBoxSizePatches(selection.element);
+ if (offset) {
+ applyStudioPathOffset(selection.element, offset);
+ patches.push(...buildPathOffsetPatches(selection.element));
+ }
+ return commitPositionPatchToHtml(selection, patches, {
label: "Resize layer box",
coalesceKey: `box-size:${getDomEditTargetKey(selection)}`,
});
diff --git a/packages/studio/src/hooks/useDomSelection.test.ts b/packages/studio/src/hooks/useDomSelection.test.ts
index b7628c4379..53f4524644 100644
--- a/packages/studio/src/hooks/useDomSelection.test.ts
+++ b/packages/studio/src/hooks/useDomSelection.test.ts
@@ -2,9 +2,7 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import type { TimelineElement } from "../player";
-import { usePlayerStore } from "../player/store/playerStore";
+import { describe, expect, it, vi } from "vitest";
import { installReactActEnvironment, makeSelection } from "./domSelectionTestHarness";
import { useDomSelection } from "./useDomSelection";
@@ -14,7 +12,6 @@ interface HarnessProps {
activeCompPath: string | null;
projectId: string | null;
refreshKey: number;
- timelineElements?: TimelineElement[];
}
function renderHarness(initialProps: HarnessProps): {
@@ -35,7 +32,7 @@ function renderHarness(initialProps: HarnessProps): {
compIdToSrc: new Map(),
captionEditMode: false,
previewIframeRef: { current: null },
- timelineElements: props.timelineElements ?? [],
+ timelineElements: [],
setSelectedTimelineElementId: vi.fn(),
setRightCollapsed: vi.fn(),
setRightPanelTab: vi.fn(),
@@ -67,10 +64,6 @@ function renderHarness(initialProps: HarnessProps): {
};
}
-afterEach(() => {
- usePlayerStore.getState().reset();
-});
-
function setupSelectedHarness() {
const element = document.createElement("div");
element.id = "headline";
@@ -138,31 +131,4 @@ describe("useDomSelection", () => {
expect(harness.current().domEditSelection).toBe(selection);
harness.cleanup();
});
-
- it("keeps preview marquee selections mirrored to the full timeline selection set", () => {
- const first = document.createElement("div");
- first.id = "clip-1";
- const second = document.createElement("div");
- second.id = "clip-2";
- const firstSelection = makeSelection("First", first);
- const secondSelection = makeSelection("Second", second);
- const harness = renderHarness({
- activeCompPath: "intro.html",
- projectId: "project-1",
- refreshKey: 0,
- timelineElements: [
- { id: "clip-1", domId: "clip-1", tag: "div", start: 0, duration: 1, track: 0 },
- { id: "clip-2", domId: "clip-2", tag: "div", start: 1, duration: 1, track: 1 },
- ],
- });
-
- act(() => harness.current().applyMarqueeSelection([secondSelection, firstSelection], false));
-
- const state = usePlayerStore.getState();
- expect([...state.selectedElementIds]).toEqual(["clip-2", "clip-1"]);
- expect(state.selectedElementId).toBe("clip-2");
- expect(harness.current().domEditGroupSelections).toHaveLength(2);
- expect(harness.current().domEditSelection).toBe(secondSelection);
- harness.cleanup();
- });
});
diff --git a/packages/studio/src/hooks/useDomSelection.ts b/packages/studio/src/hooks/useDomSelection.ts
index 3fd25c9158..903894c7e9 100644
--- a/packages/studio/src/hooks/useDomSelection.ts
+++ b/packages/studio/src/hooks/useDomSelection.ts
@@ -1,10 +1,14 @@
import { useState, useCallback, useRef, useEffect } from "react";
-import type { TimelineElement } from "../player";
+import type { SelectElementOptions, TimelineElement } from "../player";
import {
getAllPreviewTargetsFromPointer,
getPreviewTargetFromPointer,
} from "../utils/studioPreviewHelpers";
-import { resolveTimelineIdForSelection, type RightPanelTab } from "../utils/studioHelpers";
+import {
+ findMatchingTimelineElementId,
+ findTimelineIdByAncestor,
+ type RightPanelTab,
+} from "../utils/studioHelpers";
import {
domEditSelectionsTargetSame,
domEditSelectionInGroup,
@@ -20,7 +24,6 @@ import {
type DomEditSelection,
} from "../components/editor/domEditing";
import { reapplyPositionEditsAfterSeek } from "../components/editor/manualEdits";
-import { usePlayerStore } from "../player/store/playerStore";
// ── Types ──
@@ -44,7 +47,7 @@ export interface UseDomSelectionParams {
captionEditMode: boolean;
previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>;
timelineElements: TimelineElement[];
- setSelectedTimelineElementId: (id: string | null) => void;
+ setSelectedTimelineElementId: (id: string | null, options?: SelectElementOptions) => void;
setRightCollapsed: (collapsed: boolean) => void;
setRightPanelTab: (tab: RightPanelTab) => void;
previewIframe: HTMLIFrameElement | null;
@@ -92,6 +95,7 @@ export interface UseDomSelectionReturn {
) => Promise<DomEditSelection | null>;
handleTimelineElementSelect: (element: TimelineElement | null) => Promise<void>;
refreshDomEditSelectionFromPreview: (selection: DomEditSelection) => Promise<void>;
+ refreshDomEditGroupSelectionsFromPreview: (selections: DomEditSelection[]) => Promise<void>;
applyMarqueeSelection: (selections: DomEditSelection[], additive: boolean) => void;
}
@@ -206,42 +210,27 @@ export function useDomSelection({
if (nextSelection) {
if (options?.revealPanel !== false) {
setRightCollapsed(false);
- // Keep the Variables tab in place — selecting elements is part of
- // the bind flow there; yanking to Design would lose the context.
+ // Keep the Variables tab in place — selecting elements is part of the bind
+ // flow there; yanking to Design would lose the context.
if (rightPanelTabRef.current !== "variables") {
setRightPanelTab("design");
}
}
- // Mirror the whole DOM group to the store so it stays the single source of
- // truth: a single selection collapses to one id; a preserved group (echo
- // during a gesture) keeps every member instead of shrinking to the anchor.
- const anchorId = resolveTimelineIdForSelection(
- nextSelection,
- timelineElements,
- activeCompPath,
- );
- const groupIds = nextGroup
- .map((selection) =>
- resolveTimelineIdForSelection(selection, timelineElements, activeCompPath),
- )
- .filter((id): id is string => Boolean(id));
- if (groupIds.length > 0) {
- usePlayerStore.getState().setSelection(groupIds, anchorId);
- } else {
- setSelectedTimelineElementId(anchorId);
- }
+ const nextSelectedTimelineId =
+ findMatchingTimelineElementId(nextSelection, timelineElements) ??
+ findTimelineIdByAncestor(
+ nextSelection.element,
+ timelineElements,
+ nextSelection.sourceFile || "index.html",
+ );
+ // Late marquee notify: a primary already in the live set must not collapse it.
+ setSelectedTimelineElementId(nextSelectedTimelineId, { preserveSet: true });
return;
}
setSelectedTimelineElementId(null);
},
- [
- setSelectedTimelineElementId,
- timelineElements,
- setRightCollapsed,
- setRightPanelTab,
- activeCompPath,
- ],
+ [setSelectedTimelineElementId, timelineElements, setRightCollapsed, setRightPanelTab],
);
const clearDomSelection = useCallback(() => {
@@ -424,6 +413,55 @@ export function useDomSelection({
[activeCompPath, applyDomSelection, buildDomSelectionFromTarget, previewIframeRef],
);
+ const refreshDomEditGroupSelectionsFromPreview = useCallback(
+ // fallow-ignore-next-line complexity
+ async (selections: DomEditSelection[]) => {
+ const iframe = previewIframeRef.current;
+ let doc: Document | null = null;
+ try {
+ doc = iframe?.contentDocument ?? null;
+ } catch {
+ return;
+ }
+ if (!doc) return;
+
+ const nextGroup: DomEditSelection[] = [];
+ for (const selection of selections) {
+ const element = findElementForSelection(doc, selection, activeCompPath);
+ if (!element) continue;
+ const nextSelection = await buildDomSelectionFromTarget(element);
+ if (nextSelection) nextGroup.push(nextSelection);
+ }
+ if (nextGroup.length === 0) return;
+
+ const currentSelection = domEditSelectionRef.current;
+ const nextSelection =
+ nextGroup.find((selection) => domEditSelectionsTargetSame(selection, currentSelection)) ??
+ nextGroup[0] ??
+ null;
+
+ domEditSelectionRef.current = nextSelection;
+ domEditGroupSelectionsRef.current = nextGroup;
+ setDomEditSelection(nextSelection);
+ setDomEditGroupSelections(nextGroup);
+
+ if (nextSelection) {
+ setSelectedTimelineElementId(
+ findMatchingTimelineElementId(nextSelection, timelineElements),
+ );
+ } else {
+ setSelectedTimelineElementId(null);
+ }
+ },
+ [
+ activeCompPath,
+ buildDomSelectionFromTarget,
+ setSelectedTimelineElementId,
+ timelineElements,
+ previewIframeRef,
+ ],
+ );
+
// ── Effects ──
// Clear hover unconditionally on composition/project/preview change
@@ -471,8 +509,7 @@ export function useDomSelection({
const applyMarqueeSelection = useCallback(
// fallow-ignore-next-line complexity
(selections: DomEditSelection[], additive: boolean) => {
- // Honor the inspector-panels kill switch like applyDomSelection does, so
- // marquee can't land selections while the inspector UI is suppressed.
+ // Honor the inspector-panels kill switch like applyDomSelection does.
if (!STUDIO_INSPECTOR_PANELS_ENABLED) {
domEditSelectionRef.current = null;
domEditGroupSelectionsRef.current = [];
@@ -493,8 +530,7 @@ export function useDomSelection({
if (!domEditSelectionInGroup(nextGroup, s)) nextGroup = [...nextGroup, s];
}
} else {
- // Dedupe by target: under select-as-unit several marquee'd members collapse
- // to the same group, which must count as one selection, not many duplicates.
+ // Dedupe by target: select-as-unit collapses marquee'd members to one group.
nextGroup = [];
for (const s of selections) {
if (!domEditSelectionInGroup(nextGroup, s)) nextGroup.push(s);
@@ -505,23 +541,16 @@ export function useDomSelection({
domEditGroupSelectionsRef.current = nextGroup;
setDomEditSelection(nextSelection);
setDomEditGroupSelections(nextGroup);
- const nextTimelineId = resolveTimelineIdForSelection(
- nextSelection,
- timelineElements,
- activeCompPath,
- );
- const nextTimelineIds = nextGroup
- .map((selection) =>
- resolveTimelineIdForSelection(selection, timelineElements, activeCompPath),
- )
- .filter((id): id is string => Boolean(id));
- if (nextTimelineIds.length > 0) {
- usePlayerStore.getState().setSelection(nextTimelineIds, nextTimelineId);
- } else {
- setSelectedTimelineElementId(null);
- }
+ const nextTimelineId =
+ findMatchingTimelineElementId(nextSelection, timelineElements) ??
+ findTimelineIdByAncestor(
+ nextSelection.element,
+ timelineElements,
+ nextSelection.sourceFile || "index.html",
+ );
+ setSelectedTimelineElementId(nextTimelineId);
},
- [applyDomSelection, timelineElements, setSelectedTimelineElementId, activeCompPath],
+ [applyDomSelection, timelineElements, setSelectedTimelineElementId],
);
// Disabled inspector effect
@@ -558,6 +587,7 @@ export function useDomSelection({
buildDomSelectionForTimelineElement,
handleTimelineElementSelect,
refreshDomEditSelectionFromPreview,
+ refreshDomEditGroupSelectionsFromPreview,
applyMarqueeSelection,
};
}
diff --git a/packages/studio/src/hooks/useDomSelectionSelectionGuards.test.ts b/packages/studio/src/hooks/useDomSelectionSelectionGuards.test.ts
new file mode 100644
index 0000000000..dce0655946
--- /dev/null
+++ b/packages/studio/src/hooks/useDomSelectionSelectionGuards.test.ts
@@ -0,0 +1,276 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { installReactActEnvironment, makeSelection } from "./domSelectionTestHarness";
+import type { DomEditSelection } from "../components/editor/domEditing";
+import type { SelectElementOptions, TimelineElement } from "../player";
+import { usePlayerStore } from "../player";
+
+installReactActEnvironment();
+
+// ── Module mocks ──
+// Control the async selection-resolution ordering so the race guard can be
+// exercised deterministically, and neutralise the DOM re-apply side effect.
+vi.mock("../components/editor/manualEdits", () => ({
+ reapplyPositionEditsAfterSeek: () => undefined,
+}));
+
+const deferreds = new Map<string, { promise: Promise<DomEditSelection>; resolve: () => void }>();
+
+function deferredFor(el: HTMLElement): Promise<DomEditSelection> {
+ const id = el.id;
+ let resolveFn: () => void = () => undefined;
+ const promise = new Promise<DomEditSelection>((resolve) => {
+ resolveFn = () => resolve(makeSelection(id.toUpperCase(), el));
+ });
+ deferreds.set(id, { promise, resolve: resolveFn });
+ return promise;
+}
+
+vi.mock("../components/editor/domEditing", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../components/editor/domEditing")>();
+ return {
+ ...actual,
+ findElementForTimelineElement: (doc: Document, element: { id?: string }) =>
+ element.id ? doc.getElementById(element.id) : null,
+ resolveDomEditSelection: (startEl: HTMLElement | null) =>
+ startEl ? deferredFor(startEl) : Promise.resolve(null),
+ };
+});
+
+// Imported after the mocks so the hook picks up the mocked modules.
+const { useDomSelection } = await import("./useDomSelection");
+
+interface HarnessProps {
+ rightPanelTab: "design" | "variables";
+ setRightPanelTab: (tab: "design" | "variables") => void;
+ iframe: HTMLIFrameElement | null;
+ timelineElements: TimelineElement[];
+ setSelectedTimelineElementId?: (id: string | null, options?: SelectElementOptions) => void;
+}
+
+function renderHarness(props: HarnessProps) {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ let currentHook: ReturnType<typeof useDomSelection> | null = null;
+
+ function Harness() {
+ currentHook = useDomSelection({
+ projectId: "project-1",
+ activeCompPath: "index.html",
+ isMasterView: false,
+ compIdToSrc: new Map(),
+ captionEditMode: false,
+ previewIframeRef: { current: props.iframe },
+ timelineElements: props.timelineElements,
+ setSelectedTimelineElementId: props.setSelectedTimelineElementId ?? vi.fn(),
+ setRightCollapsed: vi.fn(),
+ setRightPanelTab: props.setRightPanelTab,
+ previewIframe: props.iframe,
+ refreshKey: 0,
+ rightPanelTab: props.rightPanelTab,
+ });
+ return null;
+ }
+
+ act(() => root.render(React.createElement(Harness)));
+
+ return {
+ current: () => {
+ if (!currentHook) throw new Error("Expected hook result");
+ return currentHook;
+ },
+ cleanup: () => {
+ act(() => root.unmount());
+ host.remove();
+ },
+ };
+}
+
+describe("useDomSelection — Variables tab preservation", () => {
+ it("does not yank the user off the Variables tab when selecting on canvas", () => {
+ const setRightPanelTab = vi.fn();
+ const el = document.createElement("div");
+ el.id = "headline";
+ const harness = renderHarness({
+ rightPanelTab: "variables",
+ setRightPanelTab,
+ iframe: null,
+ timelineElements: [],
+ });
+
+ act(() => harness.current().applyDomSelection(makeSelection("Headline", el)));
+
+ expect(setRightPanelTab).not.toHaveBeenCalled();
+ harness.cleanup();
+ });
+
+ it("switches to the Design tab when not on Variables (control)", () => {
+ const setRightPanelTab = vi.fn();
+ const el = document.createElement("div");
+ el.id = "headline";
+ const harness = renderHarness({
+ rightPanelTab: "design",
+ setRightPanelTab,
+ iframe: null,
+ timelineElements: [],
+ });
+
+ act(() => harness.current().applyDomSelection(makeSelection("Headline", el)));
+
+ expect(setRightPanelTab).toHaveBeenCalledWith("design");
+ harness.cleanup();
+ });
+});
+
+describe("useDomSelection — timeline-select race guard", () => {
+ beforeEach(() => deferreds.clear());
+ afterEach(() => deferreds.clear());
+
+ it("a stale async resolution never clobbers a newer selection", async () => {
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ const doc = iframe.contentDocument!;
+ const elA = doc.createElement("div");
+ elA.id = "a";
+ const elB = doc.createElement("div");
+ elB.id = "b";
+ doc.body.append(elA, elB);
+
+ const elementA: TimelineElement = { id: "a", tag: "div", start: 0, duration: 1, track: 0 };
+ const elementB: TimelineElement = { id: "b", tag: "div", start: 0, duration: 1, track: 0 };
+
+ const harness = renderHarness({
+ rightPanelTab: "design",
+ setRightPanelTab: vi.fn(),
+ iframe,
+ timelineElements: [elementA, elementB],
+ });
+
+ // Fire A then B; both suspend on their (pending) resolveDomEditSelection.
+ let pA: Promise<void> = Promise.resolve();
+ let pB: Promise<void> = Promise.resolve();
+ act(() => {
+ pA = harness.current().handleTimelineElementSelect(elementA);
+ pB = harness.current().handleTimelineElementSelect(elementB);
+ });
+
+ // Resolve the NEWER select (B) first, then the older one (A) last.
+ await act(async () => {
+ deferreds.get("b")?.resolve();
+ await pB;
+ });
+ await act(async () => {
+ deferreds.get("a")?.resolve();
+ await pA;
+ });
+
+ // The stale A resolution must be dropped: B wins.
+ expect(harness.current().domEditSelection?.id).toBe("b");
+ harness.cleanup();
+ iframe.remove();
+ });
+});
+
+describe("useDomSelection — marquee multi-select survives the late async primary", () => {
+ beforeEach(() => {
+ deferreds.clear();
+ const store = usePlayerStore.getState();
+ store.setSelectedElementId(null);
+ store.clearSelectedElementIds();
+ });
+ afterEach(() => {
+ deferreds.clear();
+ const store = usePlayerStore.getState();
+ store.setSelectedElementId(null);
+ store.clearSelectedElementIds();
+ });
+
+ function timelineEl(id: string): TimelineElement {
+ return { id, domId: id, tag: "div", start: 0, duration: 1, track: 0 };
+ }
+
+ // Reproduces the reported regression: a marquee over N clips leaves N members in
+ // selectedElementIds, then the inspector-open notify (finishMarquee →
+ // handleTimelineElementSelect → applyDomSelection) resolves LATE and writes the
+ // primary again. Before the fix that late write collapsed the set to one clip.
+ it("keeps all N members when a late primary-set targets a set member", async () => {
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ const doc = iframe.contentDocument!;
+ for (const id of ["a", "b", "c"]) {
+ const el = doc.createElement("div");
+ el.id = id;
+ doc.body.append(el);
+ }
+
+ const store = usePlayerStore.getState();
+ // Marquee end state: primary written first, then the full set (real ordering).
+ store.setSelectedElementId("a");
+ store.setSelectedElementIds(new Set(["a", "b", "c"]));
+
+ const harness = renderHarness({
+ rightPanelTab: "design",
+ setRightPanelTab: vi.fn(),
+ iframe,
+ timelineElements: [timelineEl("a"), timelineEl("b"), timelineEl("c")],
+ // Wire the real store write so applyDomSelection's collapse decision is exercised.
+ setSelectedTimelineElementId: usePlayerStore.getState().setSelectedElementId,
+ });
+
+ let pending: Promise<void> = Promise.resolve();
+ act(() => {
+ pending = harness.current().handleTimelineElementSelect(timelineEl("a"));
+ });
+ await act(async () => {
+ deferreds.get("a")?.resolve();
+ await pending;
+ });
+
+ expect(usePlayerStore.getState().selectedElementIds.size).toBe(3);
+ expect(usePlayerStore.getState().selectedElementId).toBe("a");
+ harness.cleanup();
+ iframe.remove();
+ });
+
+ it("collapses the set when a late primary-set targets a non-member (fresh click)", async () => {
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ const doc = iframe.contentDocument!;
+ for (const id of ["a", "b", "d"]) {
+ const el = doc.createElement("div");
+ el.id = id;
+ doc.body.append(el);
+ }
+
+ const store = usePlayerStore.getState();
+ // Stale set left over from a previous gesture.
+ store.setSelectedElementId("a");
+ store.setSelectedElementIds(new Set(["a", "b"]));
+
+ const harness = renderHarness({
+ rightPanelTab: "design",
+ setRightPanelTab: vi.fn(),
+ iframe,
+ timelineElements: [timelineEl("a"), timelineEl("b"), timelineEl("d")],
+ setSelectedTimelineElementId: usePlayerStore.getState().setSelectedElementId,
+ });
+
+ let pending: Promise<void> = Promise.resolve();
+ act(() => {
+ pending = harness.current().handleTimelineElementSelect(timelineEl("d"));
+ });
+ await act(async () => {
+ deferreds.get("d")?.resolve();
+ await pending;
+ });
+
+ expect(usePlayerStore.getState().selectedElementIds.size).toBe(0);
+ expect(usePlayerStore.getState().selectedElementId).toBe("d");
+ harness.cleanup();
+ iframe.remove();
+ });
+});
diff --git a/packages/studio/src/hooks/useElementLifecycleOps.test.tsx b/packages/studio/src/hooks/useElementLifecycleOps.test.tsx
new file mode 100644
index 0000000000..18468ab56a
--- /dev/null
+++ b/packages/studio/src/hooks/useElementLifecycleOps.test.tsx
@@ -0,0 +1,258 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { usePlayerStore } from "../player";
+import type { DomEditPatchBatch } from "./domEditCommitTypes";
+import { useElementLifecycleOps } from "./useElementLifecycleOps";
+import { mountReactHarness } from "./domSelectionTestHarness";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+afterEach(() => {
+ document.body.innerHTML = "";
+ usePlayerStore.getState().setElements([]);
+ vi.unstubAllGlobals();
+});
+
+interface BatchOptions {
+ label: string;
+ coalesceKey: string;
+}
+
+interface CapturedBatchCall {
+ batches: DomEditPatchBatch[];
+ options: BatchOptions;
+}
+
+type ReorderCommit = (
+ entries: Array<{
+ element: HTMLElement;
+ zIndex: number;
+ id?: string;
+ selector?: string;
+ selectorIndex?: number;
+ sourceFile: string;
+ key?: string;
+ }>,
+ coalesceKeyOverride?: string,
+) => Promise<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 });
+ },
+ });
+ onReady(handleDomZIndexReorderCommit);
+ return null;
+ }
+ return mountReactHarness(<Harness />);
+}
+
+/** Append the element, mount the reorder hook, and run one commit through act. */
+async function runReorderCommit(el: HTMLElement, entries: Parameters<ReorderCommit>[0]) {
+ document.body.appendChild(el);
+
+ const captured: CapturedBatchCall[] = [];
+ let commit: ReorderCommit | undefined;
+ const root = renderReorderHook(captured, (fn) => (commit = fn));
+
+ await act(async () => {
+ commit!(entries);
+ });
+
+ return { captured, root };
+}
+
+describe("useElementLifecycleOps — z-index reorder payload", () => {
+ // Regression: an id-less canvas element (e.g. a caption `.sub` div, which
+ // carries only data-hf-id + class) once had its absent id coerced to `null`
+ // (`entry.id ?? null`). The DOM-patch guard rejects a null `body.target.id`,
+ // so "move to back" toasted "unsafe values" and nothing persisted. The target
+ // id must be `undefined` (dropped on the wire), letting hfId / selector match.
+ it("never sends a null target id for an id-less element", async () => {
+ const el = document.createElement("div");
+ el.className = "sub clip";
+ el.setAttribute("data-hf-id", "hf-card");
+
+ const { captured, root } = await runReorderCommit(el, [
+ {
+ element: el,
+ zIndex: 0,
+ // id intentionally absent — the id-less element case.
+ selector: ".sub.clip",
+ selectorIndex: 3,
+ sourceFile: "index.html",
+ },
+ ]);
+
+ const target = captured[0]?.batches[0]?.patches[0]?.target;
+ expect(captured).toHaveLength(1);
+ expect(target?.id).toBeUndefined();
+ expect(target?.id).not.toBeNull();
+ // The element stays addressable via hfId (and selector) instead.
+ expect(target?.hfId).toBe("hf-card");
+
+ act(() => root.unmount());
+ });
+
+ it("preserves a real id when the element has one", async () => {
+ const el = document.createElement("video");
+ el.id = "v-hero";
+ el.setAttribute("data-hf-id", "hf-ezl2");
+
+ const { captured, root } = await runReorderCommit(el, [
+ { element: el, zIndex: 2, id: "v-hero", selector: "#v-hero", sourceFile: "index.html" },
+ ]);
+
+ expect(captured).toHaveLength(1);
+ expect(captured[0]?.batches[0]?.patches[0]?.target.id).toBe("v-hero");
+
+ act(() => root.unmount());
+ });
+
+ it("threads the lane gesture key into z-index persistence", async () => {
+ const el = document.createElement("div");
+ el.id = "clip-a";
+ document.body.appendChild(el);
+ const captured: CapturedBatchCall[] = [];
+ let commit: ReorderCommit | undefined;
+ const root = renderReorderHook(captured, (fn) => (commit = fn));
+
+ await act(async () => {
+ await commit!(
+ [{ element: el, zIndex: 4, id: "clip-a", sourceFile: "index.html" }],
+ "clip-lane-move:7",
+ );
+ });
+
+ expect(captured).toHaveLength(1);
+ expect(captured[0]?.options.coalesceKey).toBe("clip-lane-move:7");
+ act(() => root.unmount());
+ });
+
+ it("creates one batch per source file in a multi-file reorder", async () => {
+ const elements = ["clip-a", "clip-b", "clip-c"].map((id) => {
+ const element = document.createElement("div");
+ element.id = id;
+ document.body.appendChild(element);
+ return element;
+ });
+ const captured: CapturedBatchCall[] = [];
+ let commit: ReorderCommit | undefined;
+ const root = renderReorderHook(captured, (fn) => (commit = fn));
+
+ await act(async () => {
+ await commit!(
+ elements.map((element, index) => ({
+ element,
+ zIndex: index + 1,
+ id: element.id,
+ sourceFile: index < 2 ? "index.html" : "compositions/scene.html",
+ })),
+ );
+ });
+
+ expect(captured).toHaveLength(1);
+ expect(
+ captured[0]?.batches.map(({ sourceFile, patches }) => [sourceFile, patches.length]),
+ ).toEqual([
+ ["index.html", 2],
+ ["compositions/scene.html", 1],
+ ]);
+ 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 () => {});
+ const forceReloadSdkSession = vi.fn();
+ const originalError = new Error("second patch failed");
+ const elements = ["clip-a", "clip-b", "clip-c"].map((id, index) => {
+ const element = document.createElement("div");
+ element.id = id;
+ element.style.zIndex = String(index + 10);
+ document.body.appendChild(element);
+ return element;
+ });
+ usePlayerStore.getState().setElements(
+ elements.map((element, index) => ({
+ id: element.id,
+ tag: "div",
+ start: 0,
+ duration: 1,
+ track: index,
+ zIndex: index + 10,
+ hasExplicitZIndex: false,
+ })),
+ );
+
+ 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;
+ }),
+ });
+ commit = handleDomZIndexReorderCommit;
+ return null;
+ }
+ const root = mountReactHarness(<Harness />);
+
+ let rejection: unknown;
+ await act(async () => {
+ try {
+ await commit!(
+ elements.map((element, index) => ({
+ element,
+ zIndex: 3 - index,
+ id: element.id,
+ sourceFile: "index.html",
+ key: element.id,
+ })),
+ "clip-lane-move:failure",
+ );
+ } catch (error) {
+ rejection = error;
+ }
+ });
+
+ expect(rejection).toBe(originalError);
+ expect(elements.map((element) => element.style.zIndex)).toEqual(["10", "11", "12"]);
+ expect(
+ usePlayerStore
+ .getState()
+ .elements.map(({ zIndex, hasExplicitZIndex }) => ({ zIndex, hasExplicitZIndex })),
+ ).toEqual([
+ { zIndex: 10, hasExplicitZIndex: false },
+ { zIndex: 11, hasExplicitZIndex: false },
+ { zIndex: 12, hasExplicitZIndex: false },
+ ]);
+ expect(writeProjectFile).not.toHaveBeenCalled();
+ expect(recordEdit).not.toHaveBeenCalled();
+ expect(forceReloadSdkSession).not.toHaveBeenCalled();
+ act(() => root.unmount());
+ });
+});
diff --git a/packages/studio/src/hooks/useElementLifecycleOps.ts b/packages/studio/src/hooks/useElementLifecycleOps.ts
index e59e1b042f..eb5b8e077b 100644
--- a/packages/studio/src/hooks/useElementLifecycleOps.ts
+++ b/packages/studio/src/hooks/useElementLifecycleOps.ts
@@ -1,42 +1,26 @@
import { useCallback } from "react";
import { usePlayerStore } from "../player";
-import { saveProjectFilesWithHistory } from "../utils/studioFileHistory";
+import {
+ readProjectFileContent,
+ saveProjectFilesWithHistory,
+ type DomEditCommitBaseParams,
+} from "../utils/studioFileHistory";
import { createStudioSaveHttpError } from "../utils/studioSaveDiagnostics";
import {
buildDomEditPatchTarget,
readHfId,
type DomEditSelection,
} from "../components/editor/domEditing";
-import type { PatchOperation } from "../utils/sourcePatcher";
-import type { EditHistoryKind } from "../utils/editHistory";
-
-interface RecordEditInput {
- label: string;
- kind: EditHistoryKind;
- coalesceKey?: string;
- files: Record<string, { before: string; after: string }>;
-}
+import type { CommitDomEditPatchBatches, DomEditPatchBatch } from "./domEditCommitTypes";
-interface UseElementLifecycleOpsParams {
- activeCompPath: string | null;
- showToast: (message: string, tone?: "error" | "info") => void;
- writeProjectFile: (path: string, content: string) => Promise<void>;
- domEditSaveTimestampRef: React.MutableRefObject<number>;
- editHistory: { recordEdit: (entry: RecordEditInput) => Promise<void> };
- projectIdRef: React.MutableRefObject<string | null>;
- reloadPreview: () => void;
- clearDomSelection: () => void;
+interface UseElementLifecycleOpsParams extends DomEditCommitBaseParams {
/** Route delete through SDK when session resolves the hf-id; returns true if handled. */
onTrySdkDelete?: (hfId: string, originalContent: string, targetPath: string) => Promise<boolean>;
/** Resolver-shadow tripwire for the reordered targets (telemetry-only, decoupled from cutover). */
onReorderShadow?: (targets: string[]) => void;
/** Resync the SDK session after a server-fallback delete. */
forceReloadSdkSession?: () => void;
- commitPositionPatchToHtml: (
- selection: DomEditSelection,
- patches: PatchOperation[],
- options: { label: string; coalesceKey: string; skipRefresh?: boolean },
- ) => Promise<void>;
+ commitDomEditPatchBatches: CommitDomEditPatchBatches;
/** Stage 7 Step 3b: called after a successful server-side element delete (shadow). */
onElementDeleted?: (selection: DomEditSelection) => void;
}
@@ -53,7 +37,7 @@ export function useElementLifecycleOps({
onTrySdkDelete,
onReorderShadow,
forceReloadSdkSession,
- commitPositionPatchToHtml,
+ commitDomEditPatchBatches,
onElementDeleted,
}: UseElementLifecycleOpsParams) {
// fallow-ignore-next-line complexity
@@ -66,17 +50,7 @@ export function useElementLifecycleOps({
const targetPath = selection.sourceFile || activeCompPath || "index.html";
try {
- const response = await fetch(
- `/api/projects/${pid}/files/${encodeURIComponent(targetPath)}`,
- );
- if (!response.ok) {
- throw await createStudioSaveHttpError(response, `Failed to read ${targetPath}`);
- }
-
- const data = (await response.json()) as { content?: string };
- const originalContent = data.content;
- if (typeof originalContent !== "string")
- throw new Error(`Missing file contents for ${targetPath}`);
+ const originalContent = await readProjectFileContent(pid, targetPath);
const patchTarget = buildDomEditPatchTarget(selection);
if (!patchTarget.id && !patchTarget.selector && !patchTarget.hfId) {
@@ -156,8 +130,8 @@ export function useElementLifecycleOps({
],
);
- // ponytail: z-index reorder writes inline-style patches via commitPositionPatchToHtml →
- // persistDomEditOperations → onTrySdkPersist, so it is already SDK-cut-over as setStyle.
+ // 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.
// No SDK reorder/reparent op exists; DOM sibling order stays server-authoritative if ever needed.
const handleDomZIndexReorderCommit = useCallback(
// fallow-ignore-next-line complexity
@@ -171,6 +145,7 @@ export function useElementLifecycleOps({
sourceFile: string;
key?: string;
}>,
+ gestureCoalesceKey?: string,
) => {
if (entries.length === 0) return Promise.resolve();
// Resolver shadow (telemetry-only, decoupled from cutover): record whether
@@ -178,11 +153,12 @@ export function useElementLifecycleOps({
onReorderShadow?.(
entries.map((e) => readHfId(e.element)).filter((id): id is string => id != null),
);
- const coalesceKey = `z-reorder:${entries.map((e) => e.id ?? e.selector ?? e.element.getAttribute("data-hf-id") ?? "el").join(":")}`;
- const saves: Array<Promise<void>> = [];
+ const coalesceKey =
+ gestureCoalesceKey ??
+ `z-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 (let i = 0; i < entries.length; i++) {
- const entry = entries[i];
+ for (const entry of entries) {
const priorZIndex = entry.element.style.zIndex;
const priorPosition = entry.element.style.position;
const priorStoreEntry = entry.key
@@ -218,39 +194,32 @@ export function useElementLifecycleOps({
});
}
});
- saves.push(
- commitPositionPatchToHtml(
- {
- element: entry.element,
- id: entry.id ?? null,
- hfId: readHfId(entry.element),
- selector: entry.selector,
- selectorIndex: entry.selectorIndex,
- sourceFile: entry.sourceFile,
- } as unknown as DomEditSelection,
- patches,
- {
- label: "Reorder layers",
- coalesceKey,
- skipRefresh: i < entries.length - 1,
- },
- ),
- );
+ 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);
}
- // Resolves once every z-index patch is persisted so a same-file timing write
+ 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).
- return Promise.allSettled(saves).then((settled) => {
- const rejected = settled.find(
- (result): result is PromiseRejectedResult => result.status === "rejected",
- );
- if (rejected) {
+ return commitDomEditPatchBatches(batches, { label: "Reorder layers", coalesceKey }).catch(
+ (error) => {
for (const rollback of rollbacks) rollback();
- return Promise.reject(rejected.reason);
- }
- return undefined;
- });
+ throw error;
+ },
+ );
},
- [commitPositionPatchToHtml, onReorderShadow],
+ [commitDomEditPatchBatches, onReorderShadow],
);
return {
diff --git a/packages/studio/src/hooks/useEnableKeyframes.test.ts b/packages/studio/src/hooks/useEnableKeyframes.test.ts
index 47826780ac..3967edf518 100644
--- a/packages/studio/src/hooks/useEnableKeyframes.test.ts
+++ b/packages/studio/src/hooks/useEnableKeyframes.test.ts
@@ -1,4 +1,7 @@
-import { describe, expect, it } from "vitest";
+// @vitest-environment happy-dom
+import { act, createElement, useRef } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import {
@@ -7,8 +10,20 @@ import {
isPlayheadWithinTween,
promoteSetToKeyframes,
resolveNewTweenRange,
+ useEnableKeyframes,
type EnableKeyframesSession,
} from "./useEnableKeyframes";
+import { usePlayerStore } from "../player/store/playerStore";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let cleanup: (() => void) | null = null;
+afterEach(() => {
+ cleanup?.();
+ cleanup = null;
+ vi.unstubAllGlobals();
+ window.location.hash = "";
+});
function anim(overrides: Partial<GsapAnimation>): GsapAnimation {
return {
@@ -203,3 +218,129 @@ describe("promoteSetToKeyframes — auto endpoint", () => {
expect(kfs[0].percentage).toBe(0);
});
});
+
+function renderEnableKeyframes(session: EnableKeyframesSession): () => Promise<void> {
+ let enable: (() => Promise<void>) | null = null;
+ function Probe() {
+ const sessionRef = useRef<EnableKeyframesSession | undefined>(session);
+ enable = useEnableKeyframes(sessionRef);
+ return null;
+ }
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ act(() => root.render(createElement(Probe)));
+ cleanup = () => act(() => root.unmount());
+ if (!enable) throw new Error("hook did not initialize");
+ return enable;
+}
+
+function flatTweenResponses(flat: GsapAnimation, converted: GsapAnimation) {
+ const responses = [{ animations: [flat] }, { animations: [converted] }];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => ({
+ ok: true,
+ json: async () => responses.shift() ?? { animations: [] },
+ })),
+ );
+}
+
+function makeElementSelection(): DomEditSelection {
+ const element = document.body.appendChild(document.createElement("div"));
+ element.id = "el";
+ return {
+ id: "el",
+ selector: "#el",
+ sourceFile: "index.html",
+ element,
+ } as DomEditSelection;
+}
+
+function stubFlatTweenConversion(id: string): {
+ flat: GsapAnimation;
+ converted: GsapAnimation;
+} {
+ const flat = anim({ id, position: 1, duration: 1, properties: { x: 10 } });
+ const converted = anim({
+ id,
+ position: 1,
+ duration: 1,
+ keyframes: {
+ format: "object-array",
+ keyframes: [
+ { percentage: 0, properties: { x: 0 } },
+ { percentage: 100, properties: { x: 10 } },
+ ],
+ },
+ });
+ flatTweenResponses(flat, converted);
+ return { flat, converted };
+}
+
+describe("useEnableKeyframes — flat tween transaction", () => {
+ it("skips the convert reload and coalesces an outside-range terminal soft reload", async () => {
+ window.location.hash = "#/project/test-project";
+ usePlayerStore.setState({ currentTime: 3 });
+ const selection = makeElementSelection();
+ const { flat } = stubFlatTweenConversion("flat-1");
+ const handleConvert = vi.fn(async () => undefined);
+ const commitMutation = vi.fn(async () => undefined);
+ const enable = renderEnableKeyframes({
+ domEditSelection: selection,
+ selectedGsapAnimations: [flat],
+ previewIframeRef: {
+ current: {
+ contentWindow: { gsap: { getProperty: () => 10 } },
+ } as unknown as HTMLIFrameElement,
+ },
+ handleGsapAddAnimation: vi.fn(),
+ handleGsapConvertToKeyframes: handleConvert,
+ handleGsapRemoveKeyframe: vi.fn(),
+ commitMutation,
+ });
+
+ await act(async () => enable());
+
+ const convertOptions = handleConvert.mock.calls[0]?.[3];
+ const terminalOptions = commitMutation.mock.calls[0]?.[1];
+ expect(convertOptions).toMatchObject({ skipReload: true, coalesceMs: Infinity });
+ expect(terminalOptions).toMatchObject({
+ softReload: true,
+ coalesceKey: convertOptions?.coalesceKey,
+ });
+ expect(convertOptions?.coalesceKey).toEqual(expect.any(String));
+ });
+
+ it("passes the convert coalesce key to an inside-range batch edit", async () => {
+ window.location.hash = "#/project/test-project";
+ usePlayerStore.setState({ currentTime: 1.5 });
+ const selection = makeElementSelection();
+ const { flat } = stubFlatTweenConversion("flat-2");
+ const handleConvert = vi.fn(async () => undefined);
+ const addKeyframeBatch = vi.fn(async () => undefined);
+ const enable = renderEnableKeyframes({
+ domEditSelection: selection,
+ selectedGsapAnimations: [flat],
+ previewIframeRef: {
+ current: {
+ contentWindow: { gsap: { getProperty: () => 5 } },
+ } as unknown as HTMLIFrameElement,
+ },
+ handleGsapAddAnimation: vi.fn(),
+ handleGsapConvertToKeyframes: handleConvert,
+ handleGsapRemoveKeyframe: vi.fn(),
+ handleGsapAddKeyframeBatch: addKeyframeBatch,
+ });
+
+ await act(async () => enable());
+
+ const convertOptions = handleConvert.mock.calls[0]?.[3];
+ expect(addKeyframeBatch.mock.calls[0]?.[3]).toEqual({
+ softReload: true,
+ coalesceKey: convertOptions?.coalesceKey,
+ // Must carry the convert phase's infinite window so the inside-range
+ // apply folds into one undo entry regardless of round-trip latency.
+ coalesceMs: Infinity,
+ });
+ });
+});
diff --git a/packages/studio/src/hooks/useEnableKeyframes.ts b/packages/studio/src/hooks/useEnableKeyframes.ts
index 3c9558ab1a..805af7bcb6 100644
--- a/packages/studio/src/hooks/useEnableKeyframes.ts
+++ b/packages/studio/src/hooks/useEnableKeyframes.ts
@@ -12,7 +12,7 @@ import type { GsapAnimation, GsapPercentageKeyframe } from "@hyperframes/core/gs
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import { usePlayerStore } from "../player/store/playerStore";
import { fetchParsedAnimations, getAnimationsForElement } from "./useGsapTweenCache";
-import { selectorFromSelection, computeElementPercentage } from "./gsapShared";
+import { selectorFromSelection, computeElementPercentage, isInstantHold } from "./gsapShared";
import {
resolveTweenStart,
resolveTweenDuration,
@@ -21,6 +21,9 @@ import {
import { POSITION_PROPS } from "./gsapRuntimeReaders";
import { roundTo3 } from "../utils/rounding";
import { nearestPointOnPath } from "../components/editor/motionPathGeometry";
+import type { CommitMutationOptions } from "./gsapScriptCommitTypes";
+
+let enableKeyframesTransactionCounter = 0;
export interface EnableKeyframesSession {
domEditSelection: DomEditSelection | null;
@@ -30,16 +33,19 @@ export interface EnableKeyframesSession {
handleGsapConvertToKeyframes: (
animId: string,
resolvedFromValues?: Record<string, number | string>,
+ duration?: number,
+ commitOverrides?: Partial<CommitMutationOptions>,
) => void | Promise<void>;
handleGsapRemoveKeyframe: (animId: string, pct: number) => void;
handleGsapAddKeyframeBatch?: (
animId: string,
pct: number,
properties: Record<string, number | string>,
+ commitOverrides?: Partial<CommitMutationOptions>,
) => Promise<void>;
commitMutation?: (
mutation: Record<string, unknown>,
- options: { label: string; softReload?: boolean },
+ options: CommitMutationOptions,
) => Promise<void>;
}
@@ -107,6 +113,36 @@ export function buildExtendedKeyframes(
return { position: roundTo3(newStart), duration: newDuration, keyframes };
}
+async function replaceSetWithSingleKeyframe(
+ session: EnableKeyframesSession,
+ sel: DomEditSelection,
+ setAnim: GsapAnimation,
+ t: number,
+ iframe: HTMLIFrameElement | null,
+ selector: string,
+): Promise<void> {
+ const position = readElementPosition(iframe, sel, setAnim);
+ if (Object.keys(position).length === 0) {
+ for (const [key, held] of Object.entries(setAnim.properties ?? {})) {
+ if (typeof held === "number") position[key] = held;
+ }
+ }
+ if (Object.keys(position).length === 0 || !session.commitMutation) return;
+ const range = resolveNewTweenRange(sel.dataAttributes?.start, sel.dataAttributes?.duration, t);
+ await session.commitMutation(
+ {
+ type: "replace-with-keyframes",
+ animationId: setAnim.id,
+ targetSelector: selector,
+ position: roundTo3(range.start),
+ duration: roundTo3(range.duration),
+ keyframes: [{ percentage: 0, properties: position }],
+ ease: setAnim.ease,
+ },
+ { label: "Enable keyframes", softReload: true },
+ );
+}
+
// fallow-ignore-next-line complexity
function readElementPosition(
iframe: HTMLIFrameElement | null,
@@ -199,6 +235,7 @@ async function applyKeyframeAtPlayhead(
kfAnim: GsapAnimation,
t: number,
iframe: HTMLIFrameElement | null,
+ commitOverrides?: Partial<CommitMutationOptions>,
): Promise<void> {
if (!isPlayheadWithinTween(kfAnim, t)) {
const position = readElementPosition(iframe, sel, kfAnim);
@@ -215,7 +252,11 @@ async function applyKeyframeAtPlayhead(
keyframes: extended.keyframes,
ease: kfAnim.ease,
},
- { label: "Add keyframe", softReload: true },
+ {
+ label: "Add keyframe",
+ softReload: true,
+ ...commitOverrides,
+ },
);
}
return;
@@ -229,7 +270,7 @@ async function applyKeyframeAtPlayhead(
if (session.handleGsapAddKeyframeBatch) {
const position = readElementPosition(iframe, sel, kfAnim);
if (Object.keys(position).length > 0) {
- await session.handleGsapAddKeyframeBatch(kfAnim.id, pct, position);
+ await session.handleGsapAddKeyframeBatch(kfAnim.id, pct, position, commitOverrides);
}
}
}
@@ -259,27 +300,7 @@ export async function promoteSetToKeyframes(
// the set with a single keyframe at the playhead holding its value, matching the
// no-animation branch: one diamond the user can build motion from.
if (t <= setStart) {
- const position = readElementPosition(iframe, sel, setAnim);
- if (Object.keys(position).length === 0) {
- for (const key of Object.keys(setAnim.properties ?? {})) {
- const held = setAnim.properties?.[key];
- if (typeof held === "number") position[key] = held;
- }
- }
- if (Object.keys(position).length === 0) return;
- const range = resolveNewTweenRange(sel.dataAttributes?.start, sel.dataAttributes?.duration, t);
- await session.commitMutation(
- {
- type: "replace-with-keyframes",
- animationId: setAnim.id,
- targetSelector: selector,
- position: roundTo3(range.start),
- duration: roundTo3(range.duration),
- keyframes: [{ percentage: 0, properties: position }],
- ease: setAnim.ease,
- },
- { label: "Enable keyframes", softReload: true },
- );
+ await replaceSetWithSingleKeyframe(session, sel, setAnim, t, iframe, selector);
return;
}
const endPosition = readElementPosition(iframe, sel, setAnim);
@@ -395,8 +416,8 @@ export function useEnableKeyframes(
// the curve.
const arcAnim = anims.find((a) => a.arcPath);
const kfAnim = anims.find((a) => a.keyframes && !a.arcPath);
- const setAnim = anims.find((a) => a.method === "set" && !a.keyframes && !a.arcPath);
- const flatAnim = anims.find((a) => !a.keyframes && !a.arcPath && a.method !== "set");
+ const setAnim = anims.find((a) => isInstantHold(a) && !a.keyframes && !a.arcPath);
+ const flatAnim = anims.find((a) => !a.keyframes && !a.arcPath && !isInstantHold(a));
if (arcAnim) {
await applyArcWaypointAtPlayhead(session, sel, arcAnim, t, iframe);
@@ -409,9 +430,32 @@ export function useEnableKeyframes(
// resolvedFromValues, so the 0%/100% stops keep the real start→end motion
// (passing the playhead value would flatten it). Then apply uniformly so an
// out-of-range playhead extends the range just like a keyframe tween.
- await session.handleGsapConvertToKeyframes(flatAnim.id);
+ enableKeyframesTransactionCounter += 1;
+ const coalesceKey = `enable-keyframes:${flatAnim.id}:${enableKeyframesTransactionCounter}`;
+ const convertCommitOverrides: Partial<CommitMutationOptions> = {
+ skipReload: true,
+ coalesceKey,
+ coalesceMs: Number.POSITIVE_INFINITY,
+ };
+ await session.handleGsapConvertToKeyframes(
+ flatAnim.id,
+ undefined,
+ undefined,
+ convertCommitOverrides,
+ );
const converted = (await fetchAnimationsForElement(sel)).find((a) => a.keyframes);
- if (converted) await applyKeyframeAtPlayhead(session, sel, converted, t, iframe);
+ if (converted) {
+ const applyCommitOverrides: Partial<CommitMutationOptions> = {
+ softReload: true,
+ coalesceKey,
+ // Must match the convert phase's window: editHistory keys coalescing
+ // off the incoming entry, so without Infinity here the apply (landing
+ // after two POSTs + a fetch) falls back to the 300ms default and the
+ // conversion splits into two undo entries under real latency.
+ coalesceMs: Number.POSITIVE_INFINITY,
+ };
+ await applyKeyframeAtPlayhead(session, sel, converted, t, iframe, applyCommitOverrides);
+ }
} else {
const position = readElementPosition(iframe, sel, null);
const { start: elStart, duration: elDuration } = resolveNewTweenRange(
diff --git a/packages/studio/src/hooks/useGestureCommit.test.tsx b/packages/studio/src/hooks/useGestureCommit.test.tsx
new file mode 100644
index 0000000000..e67df39695
--- /dev/null
+++ b/packages/studio/src/hooks/useGestureCommit.test.tsx
@@ -0,0 +1,130 @@
+// @vitest-environment jsdom
+import { act } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { DomEditSelection } from "../components/editor/domEditing";
+import { usePlayerStore } from "../player";
+import { mountReactHarness } from "./domSelectionTestHarness";
+import type { CommitMutationOptions } from "./gsapScriptCommitTypes";
+import { useGestureCommit } from "./useGestureCommit";
+
+const gestureRecording = vi.hoisted(() => ({
+ startRecording: vi.fn(),
+ stopRecording: vi.fn(() => [
+ { time: 0, properties: { x: 0, y: 0, opacity: 1 } },
+ { time: 0.5, properties: { x: 50, y: 25, opacity: 0.5 } },
+ { time: 1, properties: { x: 100, y: 50, opacity: 0 } },
+ ]),
+ clearSamples: vi.fn(),
+ cancelRecording: vi.fn(),
+ isRecording: false,
+ recordingDuration: 0,
+ samplesRef: { current: [] },
+ trailRef: { current: [] },
+}));
+
+vi.mock("./useGestureRecording", () => ({
+ useGestureRecording: () => gestureRecording,
+}));
+
+vi.mock("../utils/rdpSimplify", () => ({
+ simplifyGestureSamples: () =>
+ new Map([
+ [0, { x: 0, y: 0, opacity: 1 }],
+ [50, { x: 50, y: 25, opacity: 0.5 }],
+ [100, { x: 100, y: 50, opacity: 0 }],
+ ]),
+}));
+
+vi.mock("../utils/gestureSmoother", () => ({
+ smoothGestureKeyframes: (keyframes: unknown) => keyframes,
+}));
+
+vi.mock("../utils/velocityEaseFitter", () => ({
+ fitEasesFromVelocity: (keyframes: unknown) => keyframes,
+}));
+
+Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true);
+
+let cleanup: (() => void) | null = null;
+
+afterEach(() => {
+ cleanup?.();
+ cleanup = null;
+ usePlayerStore.getState().reset();
+ document.body.replaceChildren();
+ vi.clearAllMocks();
+});
+
+function makeSelection(element: HTMLElement): DomEditSelection {
+ return {
+ id: element.id,
+ element,
+ label: "Card",
+ tagName: "div",
+ sourceFile: "index.html",
+ compositionPath: "index.html",
+ isCompositionHost: false,
+ isInsideLockedComposition: false,
+ boundingBox: { x: 0, y: 0, width: 100, height: 100 },
+ textContent: null,
+ dataAttributes: { start: "0", duration: "2" },
+ inlineStyles: {},
+ computedStyles: {},
+ textFields: [],
+ capabilities: {
+ canSelect: true,
+ canEditStyles: true,
+ canCrop: true,
+ canMove: true,
+ canResize: true,
+ canApplyManualOffset: true,
+ canApplyManualSize: true,
+ canApplyManualRotation: true,
+ },
+ };
+}
+
+describe("useGestureCommit", () => {
+ it("coalesces property-group commits and reloads only the terminal group", async () => {
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ const element = document.createElement("div");
+ element.id = "card";
+ const commitMutation = vi.fn<
+ (mutation: Record<string, unknown>, options: CommitMutationOptions) => Promise<void>
+ >(async () => {});
+ const sessionRef = {
+ current: {
+ domEditSelection: makeSelection(element),
+ selectedGsapAnimations: [],
+ commitMutation,
+ },
+ };
+ const captured: { hook: ReturnType<typeof useGestureCommit> | null } = { hook: null };
+ function Probe() {
+ captured.hook = useGestureCommit({
+ domEditSessionRef: sessionRef,
+ previewIframeRef: { current: iframe },
+ showToast: vi.fn(),
+ isGestureRecordingRef: { current: false },
+ });
+ return null;
+ }
+ const root = mountReactHarness(<Probe />);
+ cleanup = () => act(() => root.unmount());
+ if (!captured.hook) throw new Error("hook did not initialize");
+
+ act(() => captured.hook?.handleToggleRecording());
+ act(() => captured.hook?.handleToggleRecording());
+ await act(async () => {
+ await vi.waitFor(() => expect(commitMutation).toHaveBeenCalledTimes(2));
+ });
+
+ const options = commitMutation.mock.calls.map((call) => call[1]);
+ expect(new Set(options.map((entry) => entry.coalesceKey)).size).toBe(1);
+ expect(options[0]).toEqual(expect.objectContaining({ coalesceMs: Infinity, skipReload: true }));
+ expect(options[0]).not.toHaveProperty("softReload");
+ expect(options[1]).toEqual(expect.objectContaining({ coalesceMs: Infinity, softReload: true }));
+ expect(options[1]).not.toHaveProperty("skipReload");
+ });
+});
diff --git a/packages/studio/src/hooks/useGestureCommit.ts b/packages/studio/src/hooks/useGestureCommit.ts
index a63963be63..a0aba6747f 100644
--- a/packages/studio/src/hooks/useGestureCommit.ts
+++ b/packages/studio/src/hooks/useGestureCommit.ts
@@ -10,8 +10,10 @@ import { smoothGestureKeyframes } from "../utils/gestureSmoother";
import { usePlayerStore } from "../player";
import type { DomEditSelection } from "../components/editor/domEditing";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
+import type { CommitMutationOptions } from "./gsapScriptCommitTypes";
import { roundTo3 } from "../utils/rounding";
import { classifyPropertyGroup } from "@hyperframes/core/gsap-parser";
+import { isInstantHold } from "./gsapShared";
type RecordedKeyframe = {
percentage: number;
@@ -68,10 +70,18 @@ interface GestureSessionRef {
selectedGsapAnimations?: GsapAnimation[];
commitMutation?: (
mutation: Record<string, unknown>,
- options: { label: string; softReload?: boolean },
+ options: CommitMutationOptions,
) => Promise<void>;
}
+/** Only the LAST group in a per-group commit loop reloads the preview; the
+ * earlier ones skip it, so a multi-group gesture recording is one reload. */
+function reloadOnlyLast(index: number, count: number): Partial<CommitMutationOptions> {
+ return index === count - 1 ? { softReload: true } : { skipReload: true };
+}
+
+let gestureRecordingCommitCounter = 0;
+
interface UseGestureCommitParams {
domEditSessionRef: React.MutableRefObject<GestureSessionRef>;
previewIframeRef: React.RefObject<HTMLIFrameElement | null>;
@@ -112,6 +122,10 @@ export function useGestureCommit({
return;
}
commitInFlightRef.current = true;
+ const coalesceOptions = {
+ coalesceKey: `gesture-recording:${++gestureRecordingCommitCounter}`,
+ coalesceMs: Number.POSITIVE_INFINITY,
+ };
gestureStateRef.current = "idle";
isGestureRecordingRef.current = false;
const frozenSamples = gestureRecording.stopRecording();
@@ -175,9 +189,9 @@ export function useGestureCommit({
? allAnims.find((a) => a.propertyGroup === "position" && a.targetSelector === selector)
: undefined;
if (existingPositionTween) {
- if (existingPositionTween.method === "set") {
- // A `set` is a static hold, not a tween to merge into — replace it with
- // the recorded motion (which already starts from the set's position).
+ if (isInstantHold(existingPositionTween)) {
+ // An instant hold is not a tween to merge into — replace it with the
+ // recorded motion (which already starts from the held position).
await liveSession.commitMutation(
{
type: "replace-with-keyframes",
@@ -242,7 +256,8 @@ export function useGestureCommit({
// Emit one tween per property group so a mixed-prop gesture (e.g.
// x/y + opacity) doesn't collapse into an untagged legacy mixed
// tween that the position-only drag intercept can't edit.
- for (const groupKfs of partitionKeyframesByGroup(keyframes)) {
+ const keyframeGroups = partitionKeyframesByGroup(keyframes);
+ for (const [index, groupKfs] of keyframeGroups.entries()) {
await liveSession.commitMutation(
{
type: "add-with-keyframes",
@@ -256,14 +271,19 @@ export function useGestureCommit({
// not inherit a sigmoid.
easeEach: "none",
},
- { label: "Gesture recording (new range)", softReload: true },
+ {
+ label: "Gesture recording (new range)",
+ ...coalesceOptions,
+ ...reloadOnlyLast(index, keyframeGroups.length),
+ },
);
}
}
}
} else {
// No existing tween — same per-group split as the new-range branch above.
- for (const groupKfs of partitionKeyframesByGroup(keyframes)) {
+ const keyframeGroups = partitionKeyframesByGroup(keyframes);
+ for (const [index, groupKfs] of keyframeGroups.entries()) {
await liveSession.commitMutation(
{
type: "add-with-keyframes",
@@ -274,7 +294,11 @@ export function useGestureCommit({
// Linear fallback (see above) — constant-speed segments stay linear.
easeEach: "none",
},
- { label: "Gesture recording", softReload: true },
+ {
+ label: "Gesture recording",
+ ...coalesceOptions,
+ ...reloadOnlyLast(index, keyframeGroups.length),
+ },
);
}
}
diff --git a/packages/studio/src/hooks/useGroupCommits.ts b/packages/studio/src/hooks/useGroupCommits.ts
index 144117eede..6e838f1dbe 100644
--- a/packages/studio/src/hooks/useGroupCommits.ts
+++ b/packages/studio/src/hooks/useGroupCommits.ts
@@ -1,25 +1,12 @@
import { useCallback } from "react";
-import { saveProjectFilesWithHistory } from "../utils/studioFileHistory";
-import { createStudioSaveHttpError } from "../utils/studioSaveDiagnostics";
+import {
+ readProjectFileContent,
+ saveProjectFilesWithHistory,
+ type DomEditCommitBaseParams,
+} from "../utils/studioFileHistory";
import { buildDomEditPatchTarget, type DomEditSelection } from "../components/editor/domEditing";
-import type { EditHistoryKind } from "../utils/editHistory";
-interface RecordEditInput {
- label: string;
- kind: EditHistoryKind;
- coalesceKey?: string;
- files: Record<string, { before: string; after: string }>;
-}
-
-interface UseGroupCommitsParams {
- activeCompPath: string | null;
- showToast: (message: string, tone?: "error" | "info") => void;
- writeProjectFile: (path: string, content: string) => Promise<void>;
- domEditSaveTimestampRef: React.MutableRefObject<number>;
- editHistory: { recordEdit: (entry: RecordEditInput) => Promise<void> };
- projectIdRef: React.MutableRefObject<string | null>;
- reloadPreview: () => void;
- clearDomSelection: () => void;
+interface UseGroupCommitsParams extends DomEditCommitBaseParams {
/** Resync the SDK session after a server-side write (the wrapper/unwrap changes
* structure the in-memory doc doesn't know about). */
forceReloadSdkSession?: () => void;
@@ -81,15 +68,7 @@ async function commitStructuralMutation(
| "reloadPreview"
>,
): Promise<{ content?: string; groupId?: string }> {
- const response = await fetch(`/api/projects/${pid}/files/${encodeURIComponent(targetPath)}`);
- if (!response.ok) {
- throw await createStudioSaveHttpError(response, `Failed to read ${targetPath}`);
- }
- const data = (await response.json()) as { content?: string };
- const originalContent = data.content;
- if (typeof originalContent !== "string") {
- throw new Error(`Missing file contents for ${targetPath}`);
- }
+ const originalContent = await readProjectFileContent(pid, targetPath);
deps.domEditSaveTimestampRef.current = Date.now();
const mutateResponse = await fetch(
diff --git a/packages/studio/src/hooks/useGsapAwareEditing.test.tsx b/packages/studio/src/hooks/useGsapAwareEditing.test.tsx
new file mode 100644
index 0000000000..69a675f110
--- /dev/null
+++ b/packages/studio/src/hooks/useGsapAwareEditing.test.tsx
@@ -0,0 +1,239 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
+import type { DomEditSelection } from "../components/editor/domEditingTypes";
+import type { DomEditGroupPathOffsetCommit } from "../components/editor/DomEditOverlay";
+import { mountReactHarness } from "./domSelectionTestHarness";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ resize: vi.fn(),
+ drag: vi.fn(),
+ readPosition: vi.fn(),
+ setPosition: vi.fn(),
+}));
+
+vi.mock("./gsapResizeIntercept", () => ({ tryGsapResizeIntercept: mocks.resize }));
+vi.mock("./gsapRuntimeBridge", () => ({
+ POSITION_CHANNELS: ["x", "y"],
+ tryGsapDragIntercept: mocks.drag,
+ tryGsapRotationIntercept: vi.fn(),
+}));
+vi.mock("./gsapPositionDetection", () => ({
+ readGsapPositionFromIframe: mocks.readPosition,
+}));
+vi.mock("../utils/elementGsap", () => ({ setElementGsapPosition: mocks.setPosition }));
+vi.mock("./useAnimatedPropertyCommit", () => ({
+ useAnimatedPropertyCommit: () => ({
+ commitAnimatedProperty: vi.fn(),
+ commitAnimatedProperties: vi.fn(),
+ }),
+}));
+vi.mock("./useSafeGsapCommitMutation", () => ({
+ useGsapSaveFailureTelemetry: () => vi.fn(),
+ useSafeGsapCommitMutation: (commit: unknown) => commit,
+}));
+
+import { useGsapAwareEditing } from "./useGsapAwareEditing";
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+function mountResizeHandler(animations: GsapAnimation[]) {
+ const element = document.createElement("div");
+ const selection = { element, id: "clip", selector: "#clip" } as unknown as DomEditSelection;
+ const fallback = vi.fn().mockResolvedValue(undefined);
+ const commitMutation = vi.fn().mockResolvedValue(undefined);
+ let resize:
+ | ((
+ selection: DomEditSelection,
+ size: { width: number; height: number },
+ offset?: { x: number; y: number },
+ restore?: () => void,
+ ) => Promise<void>)
+ | null = null;
+ function Harness() {
+ resize = useGsapAwareEditing({
+ domEditSelection: selection,
+ selectedGsapAnimations: animations,
+ gsapCommitMutation: commitMutation,
+ previewIframeRef: { current: null },
+ showToast: vi.fn(),
+ bumpGsapCache: vi.fn(),
+ makeFetchFallback: () => vi.fn().mockResolvedValue(animations),
+ trackGsapInteractionFailure: vi.fn(),
+ handleDomBoxSizeCommit: fallback,
+ addGsapAnimation: vi.fn(),
+ convertToKeyframes: vi.fn(),
+ setArcPath: vi.fn(),
+ updateArcSegment: vi.fn(),
+ }).handleGsapAwareBoxSizeCommit;
+ return null;
+ }
+ const root = mountReactHarness(<Harness />);
+ return { selection, fallback, commitMutation, resize: resize!, root };
+}
+
+describe("useGsapAwareEditing anchored resize", () => {
+ it("forwards the anchor offset to the DOM fallback when GSAP does not handle resize", async () => {
+ mocks.resize.mockResolvedValue(false);
+ const h = mountResizeHandler([]);
+ await act(() => h.resize(h.selection, { width: 300, height: 200 }, { x: -50, y: -25 }));
+ expect(h.fallback).toHaveBeenCalledWith(
+ h.selection,
+ { width: 300, height: 200 },
+ { x: -50, y: -25 },
+ );
+ act(() => h.root.unmount());
+ });
+
+ it("persists the anchor exactly once through GSAP position when size route handles resize", async () => {
+ mocks.resize.mockResolvedValue(true);
+ mocks.drag.mockResolvedValue(true);
+ const h = mountResizeHandler([]);
+ await act(() => h.resize(h.selection, { width: 300, height: 200 }, { x: -50, y: -25 }));
+ expect(h.fallback).not.toHaveBeenCalled();
+ expect(mocks.drag).toHaveBeenCalledTimes(1);
+ expect(mocks.drag.mock.calls[0]![1]).toEqual({ x: -50, y: -25 });
+ act(() => h.root.unmount());
+ });
+
+ it("settles the live GSAP position before resize persistence reaches its first await", async () => {
+ let resolveResize!: (handled: boolean) => void;
+ const pendingResize = new Promise<boolean>((resolve) => {
+ resolveResize = resolve;
+ });
+ mocks.resize.mockReturnValue(pendingResize);
+ mocks.drag.mockResolvedValue(true);
+ mocks.readPosition.mockReturnValue({ x: 120.4, y: 80.2 });
+ const h = mountResizeHandler([]);
+ h.selection.element.setAttribute("data-hf-drag-gsap-base-x", "120.4");
+ h.selection.element.setAttribute("data-hf-drag-gsap-base-y", "80.2");
+ h.selection.element.setAttribute("data-hf-drag-initial-offset-x", "0");
+ h.selection.element.setAttribute("data-hf-drag-initial-offset-y", "0");
+
+ let commit!: Promise<void>;
+ act(() => {
+ commit = h.resize(h.selection, { width: 300, height: 200 }, { x: -50.2, y: -25.6 });
+ });
+
+ expect(mocks.setPosition).toHaveBeenCalledWith(h.selection.element, 70, 55);
+ expect(mocks.setPosition.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.resize.mock.invocationCallOrder[0]!,
+ );
+
+ resolveResize(true);
+ await act(() => commit);
+ act(() => h.root.unmount());
+ });
+
+ it("passes a transaction-scoped commit wrapper into the resize path", async () => {
+ mocks.resize.mockImplementation(async (selection, _size, _animations, _iframe, commit) => {
+ await commit(selection, { type: "resize" }, { label: "Resize", softReload: true });
+ return true;
+ });
+ const h = mountResizeHandler([]);
+
+ await act(() => h.resize(h.selection, { width: 300, height: 200 }));
+
+ expect(h.commitMutation).toHaveBeenCalledWith(
+ h.selection,
+ { type: "resize" },
+ expect.objectContaining({
+ coalesceKey: expect.stringMatching(/^tx:Resize layer:\d+$/),
+ softReload: true,
+ }),
+ );
+ act(() => h.root.unmount());
+ });
+
+ it("folds a group drag's member writes into one undo entry via a shared coalesceKey", async () => {
+ const capturedKeys: Array<string | undefined> = [];
+ mocks.drag.mockImplementation(
+ async (
+ selection: DomEditSelection,
+ _next: unknown,
+ _anims: unknown,
+ _iframe: unknown,
+ commit: (
+ s: DomEditSelection,
+ m: unknown,
+ o: { coalesceKey?: string; label?: string; softReload?: boolean },
+ ) => Promise<void>,
+ ) => {
+ await commit(selection, { type: "move" }, { label: "Move", softReload: true });
+ return true;
+ },
+ );
+ const commitMutation = vi.fn(
+ (_s: DomEditSelection, _m: unknown, o: { coalesceKey?: string }) => {
+ capturedKeys.push(o.coalesceKey);
+ return Promise.resolve();
+ },
+ );
+ let groupCommit!: (updates: DomEditGroupPathOffsetCommit[]) => Promise<void>;
+ function Harness() {
+ groupCommit = useGsapAwareEditing({
+ domEditSelection: null,
+ selectedGsapAnimations: [],
+ gsapCommitMutation: commitMutation,
+ previewIframeRef: { current: null },
+ showToast: vi.fn(),
+ bumpGsapCache: vi.fn(),
+ makeFetchFallback: () => vi.fn().mockResolvedValue([]),
+ trackGsapInteractionFailure: vi.fn(),
+ handleDomBoxSizeCommit: vi.fn(),
+ addGsapAnimation: vi.fn(),
+ convertToKeyframes: vi.fn(),
+ setArcPath: vi.fn(),
+ updateArcSegment: vi.fn(),
+ }).handleGsapAwareGroupPathOffsetCommit;
+ return null;
+ }
+ const root = mountReactHarness(<Harness />);
+ const updates = [
+ {
+ selection: { element: document.createElement("div"), id: "a", selector: "#a" },
+ next: { x: 10, y: 10 },
+ },
+ {
+ selection: { element: document.createElement("div"), id: "b", selector: "#b" },
+ next: { x: 10, y: 10 },
+ },
+ ] as unknown as DomEditGroupPathOffsetCommit[];
+
+ await act(() => groupCommit(updates));
+
+ expect(capturedKeys).toHaveLength(2);
+ expect(capturedKeys[0]).toMatch(/^group-drag:\d+$/);
+ // Both members share ONE coalesceKey → they fold into a single undo entry.
+ expect(capturedKeys[0]).toBe(capturedKeys[1]);
+ act(() => root.unmount());
+ });
+
+ it("restores once when resize persistence fails", async () => {
+ const error = new Error("resize failed");
+ const restore = vi.fn();
+ mocks.resize.mockRejectedValue(error);
+ const h = mountResizeHandler([]);
+
+ const commit = h.resize(h.selection, { width: 300, height: 200 }, undefined, restore);
+ await expect(commit).rejects.toBe(error);
+ expect(restore).toHaveBeenCalledTimes(1);
+ act(() => h.root.unmount());
+ });
+
+ it("does not apply the anchor twice when scale route already settles the drop point", async () => {
+ mocks.resize.mockResolvedValue(true);
+ const scale = { propertyGroup: "scale" } as GsapAnimation;
+ const h = mountResizeHandler([scale]);
+ await act(() => h.resize(h.selection, { width: 300, height: 200 }, { x: -50, y: -25 }));
+ expect(mocks.drag).not.toHaveBeenCalled();
+ expect(h.fallback).not.toHaveBeenCalled();
+ act(() => h.root.unmount());
+ });
+});
diff --git a/packages/studio/src/hooks/useGsapAwareEditing.ts b/packages/studio/src/hooks/useGsapAwareEditing.ts
index 9e22897a1d..b2071aa693 100644
--- a/packages/studio/src/hooks/useGsapAwareEditing.ts
+++ b/packages/studio/src/hooks/useGsapAwareEditing.ts
@@ -10,15 +10,30 @@
import { useCallback } from "react";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
-import { tryGsapDragIntercept, tryGsapRotationIntercept } from "./gsapRuntimeBridge";
+import {
+ POSITION_CHANNELS,
+ tryGsapDragIntercept,
+ tryGsapRotationIntercept,
+} from "./gsapRuntimeBridge";
import { tryGsapResizeIntercept } from "./gsapResizeIntercept";
+import { computeDraggedGsapPosition } from "./draggedGsapPosition";
+import { readGsapPositionFromIframe } from "./gsapPositionDetection";
+import { selectorFromSelection } from "./gsapShared";
import { useAnimatedPropertyCommit } from "./useAnimatedPropertyCommit";
import {
useGsapSaveFailureTelemetry,
useSafeGsapCommitMutation,
} from "./useSafeGsapCommitMutation";
import type { CommitMutation } from "./gsapScriptCommitTypes";
+import { setElementGsapPosition } from "../utils/elementGsap";
+import { logResize, logResizeSettle } from "../utils/resizeDebug";
import type { DomEditGroupPathOffsetCommit } from "../components/editor/DomEditOverlay";
+import { runGestureTransaction } from "./gestureTransaction";
+import { hasNonHoldTweenForElement } from "./gsapRuntimeKeyframes";
+
+// Distinct coalesceKey per group drag so consecutive group drags don't fold
+// into one another's undo entry (module-local counter, not Date.now()).
+let groupDragCommitCounter = 0;
export interface UseGsapAwareEditingParams {
domEditSelection: DomEditSelection | null;
@@ -38,6 +53,7 @@ export interface UseGsapAwareEditingParams {
handleDomBoxSizeCommit: (
selection: DomEditSelection,
next: { width: number; height: number },
+ offset?: { x: number; y: number },
) => Promise<void>;
// GSAP script commit ops (from useGsapScriptCommits)
addGsapAnimation: (
@@ -127,7 +143,18 @@ export function useGsapAwareEditing({
// composition there's nothing to write (a no-op, exactly like the single-drag path).
const handleGsapAwareGroupPathOffsetCommit = useCallback(
async (updates: DomEditGroupPathOffsetCommit[]) => {
- if (!gsapCommitMutation) return;
+ if (!gsapCommitMutation || updates.length === 0) return;
+ // A group drag is ONE user action: fold every member's position write into
+ // a single undo entry by forcing a shared coalesceKey (infinite window, so
+ // it survives the N sequential server round-trips) onto each commit —
+ // otherwise each member records its own entry and it takes N presses to undo.
+ const coalesceKey = `group-drag:${++groupDragCommitCounter}`;
+ const coalescedCommit: typeof gsapCommitMutation = (selection, mutation, options) =>
+ gsapCommitMutation(selection, mutation, {
+ ...options,
+ coalesceKey,
+ coalesceMs: Number.POSITIVE_INFINITY,
+ });
for (const { selection, next } of updates) {
try {
await tryGsapDragIntercept(
@@ -135,7 +162,7 @@ export function useGsapAwareEditing({
next,
[],
previewIframeRef.current,
- gsapCommitMutation,
+ coalescedCommit,
makeFetchFallback(selection),
);
} catch (error) {
@@ -148,24 +175,92 @@ export function useGsapAwareEditing({
);
const handleGsapAwareBoxSizeCommit = useCallback(
- async (selection: DomEditSelection, next: { width: number; height: number }) => {
- if (gsapCommitMutation) {
- try {
- const handled = await tryGsapResizeIntercept(
- selection,
- next,
- selectedGsapAnimations,
+ async (
+ selection: DomEditSelection,
+ next: { width: number; height: number },
+ offset?: { x: number; y: number },
+ restore: () => void = () => undefined,
+ ) => {
+ const scaleRoute = selectedGsapAnimations.some((anim) => anim.propertyGroup === "scale");
+ const selector = selectorFromSelection(selection);
+ const hasLivePositionTween = selector
+ ? hasNonHoldTweenForElement(
previewIframeRef.current,
- gsapCommitMutation,
- makeFetchFallback(selection),
- );
- if (handled) return;
- } catch (error) {
- trackGsapInteractionFailure(error, selection, "resize", "Resize animated layer");
- throw error;
- }
- }
- return handleDomBoxSizeCommit(selection, next);
+ selector,
+ undefined,
+ POSITION_CHANNELS,
+ )
+ : false;
+ logResize("commit-route", {
+ next,
+ offset: offset ?? null,
+ scaleRoute,
+ animCount: selectedGsapAnimations.length,
+ animGroups: selectedGsapAnimations.map((a) => `${a.propertyGroup}:${a.method}`),
+ });
+ return runGestureTransaction({
+ element: selection.element,
+ label: "Resize layer",
+ settle: () => {
+ // Scale resize settles its center-scale residual after the scale commit
+ // renders. Width/height can settle its anchored position immediately.
+ if (!offset || scaleRoute || !selector) return;
+ const gsapPos = readGsapPositionFromIframe(previewIframeRef.current, selector) ?? {
+ x: 0,
+ y: 0,
+ };
+ const { newX, newY } = computeDraggedGsapPosition(selection.element, offset, gsapPos);
+ logResize("sync-settle", { gsapPos, offset, newX, newY });
+ setElementGsapPosition(selection.element, newX, newY);
+ },
+ persist: async (commit) => {
+ if (gsapCommitMutation) {
+ const commitMutation = commit(gsapCommitMutation);
+ try {
+ const handled = await tryGsapResizeIntercept(
+ selection,
+ next,
+ selectedGsapAnimations,
+ previewIframeRef.current,
+ commitMutation,
+ makeFetchFallback(selection),
+ );
+ if (handled) {
+ logResize("intercept-handled", {
+ scaleRoute,
+ willForwardOffset: !!(offset && !scaleRoute),
+ });
+ // Scale-route resize persists its residual position internally.
+ // Width/height persists the already-settled anchor through drag.
+ if (offset && !scaleRoute) {
+ await tryGsapDragIntercept(
+ selection,
+ offset,
+ selectedGsapAnimations,
+ previewIframeRef.current,
+ commitMutation,
+ makeFetchFallback(selection),
+ );
+ }
+ logResizeSettle(selection.element, scaleRoute ? "gsap-scale" : "gsap-size");
+ return;
+ }
+ } catch (error) {
+ trackGsapInteractionFailure(error, selection, "resize", "Resize animated layer");
+ throw error;
+ }
+ }
+ logResize("dom-route", {
+ next,
+ offset: offset ?? null,
+ hadGsapMutation: !!gsapCommitMutation,
+ });
+ logResizeSettle(selection.element, "dom-route");
+ await handleDomBoxSizeCommit(selection, next, offset);
+ },
+ restore,
+ skipPixelAssert: hasLivePositionTween,
+ });
},
[
handleDomBoxSizeCommit,
diff --git a/packages/studio/src/hooks/useGsapKeyframeOps.test.tsx b/packages/studio/src/hooks/useGsapKeyframeOps.test.tsx
index 2b7b44b4a7..9a965d63db 100644
--- a/packages/studio/src/hooks/useGsapKeyframeOps.test.tsx
+++ b/packages/studio/src/hooks/useGsapKeyframeOps.test.tsx
@@ -99,3 +99,62 @@ describe("useGsapKeyframeOps — resizeKeyframedTween", () => {
expect(labelArg).toBe("Retime keyframe (resize tween)");
});
});
+
+describe("useGsapKeyframeOps — keyframe transaction options", () => {
+ it("soft-reloads a standalone convert when the SDK path is unavailable", async () => {
+ const commitMutation = vi.fn<(...args: unknown[]) => Promise<unknown>>(async () => ({
+ ok: true,
+ }));
+ const api = renderKeyframeOps({ commitMutation, trackGsapSaveFailure: vi.fn() });
+
+ await act(async () => {
+ await api.convertToKeyframes(selection, "box-to-0-opacity");
+ });
+
+ expect(commitMutation).toHaveBeenCalledWith(
+ selection,
+ expect.objectContaining({
+ type: "convert-to-keyframes",
+ animationId: "box-to-0-opacity",
+ }),
+ { label: "Convert to keyframes", softReload: true },
+ );
+ });
+
+ it("threads one coalesce key through skipped convert reload and terminal batch edit", async () => {
+ const commitMutation = vi.fn<(...args: unknown[]) => Promise<unknown>>(async () => ({
+ ok: true,
+ }));
+ const api = renderKeyframeOps({ commitMutation, trackGsapSaveFailure: vi.fn() });
+ const coalesceKey = "enable-keyframes:box-to-0-opacity:1";
+
+ await act(async () => {
+ await api.convertToKeyframes(selection, "box-to-0-opacity", undefined, undefined, {
+ skipReload: true,
+ coalesceKey,
+ coalesceMs: Infinity,
+ });
+ await api.addKeyframeBatch(
+ selection,
+ "box-to-0-opacity",
+ 50,
+ { opacity: 0.5 },
+ {
+ coalesceKey,
+ },
+ );
+ });
+
+ expect(commitMutation.mock.calls[0]?.[2]).toEqual({
+ label: "Convert to keyframes",
+ skipReload: true,
+ coalesceKey,
+ coalesceMs: Infinity,
+ });
+ expect(commitMutation.mock.calls[1]?.[2]).toEqual({
+ label: "Add keyframe at 50%",
+ softReload: true,
+ coalesceKey,
+ });
+ });
+});
diff --git a/packages/studio/src/hooks/useGsapKeyframeOps.ts b/packages/studio/src/hooks/useGsapKeyframeOps.ts
index 9203e935a9..63fa8ca0e4 100644
--- a/packages/studio/src/hooks/useGsapKeyframeOps.ts
+++ b/packages/studio/src/hooks/useGsapKeyframeOps.ts
@@ -19,6 +19,7 @@ import {
} from "./gsapKeyframeCacheHelpers";
import type {
CommitMutation,
+ CommitMutationOptions,
SafeGsapCommitMutation,
TrackGsapSaveFailure,
} from "./gsapScriptCommitTypes";
@@ -54,6 +55,21 @@ interface GsapKeyframeOpsParams extends SdkKeyframeDeps {
trackGsapSaveFailure: TrackGsapSaveFailure;
}
+/**
+ * Translate a gesture's commit overrides into the SDK persist options. The
+ * server path's `softReload`/`skipReload` maps to the SDK's `skipRefresh`, and
+ * `coalesceKey`/`coalesceMs` must ride along so an SDK-routed edit folds into
+ * one undo entry the same way the server path does.
+ */
+function toSdkPersistOptions(label: string, overrides?: Partial<CommitMutationOptions>) {
+ return {
+ label,
+ coalesceKey: overrides?.coalesceKey,
+ coalesceMs: overrides?.coalesceMs,
+ skipRefresh: overrides?.skipReload,
+ };
+}
+
export function useGsapKeyframeOps({
activeCompPath,
commitMutation,
@@ -140,6 +156,7 @@ export function useGsapKeyframeOps({
animationId: string,
percentage: number,
properties: Record<string, number | string>,
+ commitOverrides?: Partial<CommitMutationOptions>,
) => {
if (sdkSession && sdkDeps) {
const sourceFile = selection.sourceFile || activeCompPath || "index.html";
@@ -150,21 +167,30 @@ export function useGsapKeyframeOps({
properties,
sdkSession,
sdkDeps,
- { label: `Add keyframe at ${percentage}%` },
+ toSdkPersistOptions(`Add keyframe at ${percentage}%`, commitOverrides),
);
if (handled) return;
}
return commitMutation(
selection,
{ type: "add-keyframe", animationId, percentage, properties },
- { label: `Add keyframe at ${percentage}%`, softReload: true },
+ {
+ label: `Add keyframe at ${percentage}%`,
+ softReload: true,
+ ...commitOverrides,
+ },
);
},
[commitMutation, activeCompPath, sdkSession, sdkDeps],
);
const removeKeyframe = useCallback(
- (selection: DomEditSelection, animationId: string, percentage: number) => {
+ (
+ selection: DomEditSelection,
+ animationId: string,
+ percentage: number,
+ commitOverrides?: Partial<CommitMutationOptions>,
+ ) => {
const sourceFile = selection.sourceFile || activeCompPath || "index.html";
const mutation = { type: "remove-keyframe", animationId, percentage };
void executeOptimisticKeyframeCacheUpdate({
@@ -182,6 +208,7 @@ export function useGsapKeyframeOps({
),
}),
persist: async () => {
+ const label = `Remove keyframe at ${percentage}%`;
if (sdkSession && sdkDeps) {
const handled = await sdkGsapRemoveKeyframePersist(
sourceFile,
@@ -189,14 +216,14 @@ export function useGsapKeyframeOps({
percentage,
sdkSession,
sdkDeps,
- { label: `Remove keyframe at ${percentage}%` },
+ toSdkPersistOptions(label, commitOverrides),
);
if (handled) return;
}
- await commitMutation(selection, mutation, {
- label: `Remove keyframe at ${percentage}%`,
- softReload: true,
- });
+ const commitOptions = commitOverrides?.skipReload
+ ? { label, ...commitOverrides }
+ : { label, softReload: true, ...commitOverrides };
+ await commitMutation(selection, mutation, commitOptions);
},
}).catch((error) => {
trackGsapSaveFailure(error, selection, mutation, `Remove keyframe at ${percentage}%`);
@@ -261,6 +288,7 @@ export function useGsapKeyframeOps({
animationId: string,
resolvedFromValues?: Record<string, number | string>,
duration?: number,
+ commitOverrides: Partial<CommitMutationOptions> = { softReload: true },
) => {
if (sdkSession && sdkDeps) {
const targetPath = selection.sourceFile || activeCompPath || "index.html";
@@ -270,7 +298,7 @@ export function useGsapKeyframeOps({
resolvedFromValues,
sdkSession,
sdkDeps,
- { label: "Convert to keyframes" },
+ toSdkPersistOptions("Convert to keyframes", commitOverrides),
);
if (handled) return;
}
@@ -279,7 +307,7 @@ export function useGsapKeyframeOps({
// `duration` only applies when the target is a static `set` (which has
// none) — it spans the converted keyframes across the element's clip.
{ type: "convert-to-keyframes", animationId, resolvedFromValues, duration },
- { label: "Convert to keyframes" },
+ { label: "Convert to keyframes", ...commitOverrides },
);
},
[commitMutation, activeCompPath, sdkSession, sdkDeps],
diff --git a/packages/studio/src/hooks/useGsapScriptCommits.test.tsx b/packages/studio/src/hooks/useGsapScriptCommits.test.tsx
index 2e867a4f4c..26ea7aff2e 100644
--- a/packages/studio/src/hooks/useGsapScriptCommits.test.tsx
+++ b/packages/studio/src/hooks/useGsapScriptCommits.test.tsx
@@ -217,6 +217,7 @@ let cleanup: (() => void) | null = null;
function renderCommitHook() {
const reloadPreview = vi.fn();
const onCacheInvalidate = vi.fn();
+ const onFileContentChanged = vi.fn();
const forceReloadSdkSession = vi.fn();
const recordEdit = vi.fn(async () => {});
const showToast = vi.fn();
@@ -231,7 +232,7 @@ function renderCommitHook() {
domEditSaveTimestampRef: { current: 0 },
reloadPreview,
onCacheInvalidate,
- onFileContentChanged: undefined,
+ onFileContentChanged,
showToast,
sdkSession: null,
writeProjectFile: undefined,
@@ -252,6 +253,7 @@ function renderCommitHook() {
api: hookApi,
reloadPreview,
onCacheInvalidate,
+ onFileContentChanged,
forceReloadSdkSession,
recordEdit,
showToast,
@@ -383,4 +385,41 @@ describe("runCommit — instantPatch wiring", () => {
expectSoftReloadedWith(deps.reloadPreview, "AFTER");
expect(deps.reloadPreview).not.toHaveBeenCalled();
});
+
+ it("batch capability posts ordered mutations and finalizes the result once", async () => {
+ applySoftReload.mockReturnValue("applied");
+ mockFetchResult();
+ const deps = renderCommitHook();
+ const firstMutation = { type: "add", value: 1 };
+ const lastMutation = { type: "delete", value: 2 };
+ const batch = deps.api.commitMutation.batch;
+ if (!batch) throw new Error("batch capability missing");
+
+ await act(async () => {
+ await batch(
+ [
+ { selection, mutation: firstMutation, options: { label: "Resize", skipReload: true } },
+ { selection, mutation: lastMutation, options: { label: "Resize", softReload: true } },
+ ],
+ { label: "Resize", coalesceKey: "tx:resize:1", coalesceMs: Infinity, softReload: true },
+ );
+ });
+
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(fetch).toHaveBeenCalledWith(
+ "/api/projects/proj-1/gsap-mutations-batch/index.html",
+ expect.objectContaining({
+ method: "POST",
+ body: JSON.stringify({ mutations: [firstMutation, lastMutation] }),
+ }),
+ );
+ expect(deps.recordEdit).toHaveBeenCalledTimes(1);
+ expect(deps.recordEdit).toHaveBeenCalledWith(
+ expect.objectContaining({ label: "Resize", coalesceKey: "tx:resize:1" }),
+ );
+ expect(deps.onFileContentChanged).toHaveBeenCalledTimes(1);
+ expect(deps.forceReloadSdkSession).toHaveBeenCalledTimes(1);
+ expect(applySoftReload).toHaveBeenCalledTimes(1);
+ expect(deps.onCacheInvalidate).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/packages/studio/src/hooks/useGsapScriptCommits.ts b/packages/studio/src/hooks/useGsapScriptCommits.ts
index cb088e3470..2afe9f27cd 100644
--- a/packages/studio/src/hooks/useGsapScriptCommits.ts
+++ b/packages/studio/src/hooks/useGsapScriptCommits.ts
@@ -1,5 +1,6 @@
import { useCallback, useMemo, useRef } from "react";
import { findUnsafeMutationValues } from "@hyperframes/core/studio-api/finite-mutation";
+import { readProjectFileContent as readSharedProjectFileContent } from "../utils/studioFileHistory";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import { usePlayerStore } from "../player/store/playerStore";
import { applySoftReload, extractGsapScriptText } from "../utils/gsapSoftReload";
@@ -15,6 +16,8 @@ import {
readJsonResponseBody,
} from "./gsapScriptCommitHelpers";
import type {
+ CommitMutation,
+ CommitMutationCall,
CommitMutationOptions,
GsapScriptCommitsParams,
MutationResult,
@@ -47,6 +50,76 @@ async function mutateGsapScript(
return result;
}
+async function mutateGsapScriptBatch(
+ projectId: string,
+ sourceFile: string,
+ mutations: Record<string, unknown>[],
+): Promise<MutationResult> {
+ const res = await fetch(
+ `/api/projects/${encodeURIComponent(projectId)}/gsap-mutations-batch/${encodeURIComponent(sourceFile)}`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ mutations }),
+ },
+ );
+ if (!res.ok) throw new GsapMutationHttpError(res.status, await readJsonResponseBody(res));
+ const result = (await res.json()) as MutationResult;
+ if (!result.ok) throw new Error(`Failed to update GSAP in ${sourceFile}`);
+ return result;
+}
+
+type ShowToast = (message: string, tone?: "error" | "info") => void;
+
+async function runMutationRequest(
+ mutations: Record<string, unknown>[],
+ options: CommitMutationOptions,
+ showToast: ShowToast | undefined,
+ request: () => Promise<MutationResult>,
+): Promise<MutationResult | undefined> {
+ const unsafeFields = mutations.flatMap((mutation) => findUnsafeMutationValues(mutation));
+ if (unsafeFields.length > 0) {
+ showToast?.("Couldn't read element layout — try again at a different playhead time", "error");
+ if (options.skipReload) return;
+ throw new Error(
+ `Mutation contains unsafe values: ${unsafeFields.map((field) => field.path).join(", ")}`,
+ );
+ }
+ try {
+ return await request();
+ } catch (error) {
+ if (error instanceof GsapMutationHttpError)
+ showToast?.(formatGsapMutationRejectionToast(error), "error");
+ if (options.skipReload) return;
+ throw error;
+ }
+}
+
+function finishUnchangedMutation(
+ iframe: HTMLIFrameElement | null,
+ result: MutationResult,
+ options: CommitMutationOptions,
+ reloadPreview: () => void,
+): boolean {
+ if (result.changed !== false) return false;
+ if (!options.skipReload && options.instantPatch) {
+ applyPreviewSync(iframe, result, options, reloadPreview);
+ }
+ return true;
+}
+
+function refreshMutationPreview(
+ iframe: HTMLIFrameElement | null,
+ result: MutationResult,
+ options: CommitMutationOptions,
+ reloadPreview: () => void,
+ onCacheInvalidate: () => void,
+): void {
+ options.beforeReload?.();
+ applyPreviewSync(iframe, result, options, reloadPreview);
+ onCacheInvalidate();
+}
+
/**
* Apply a soft reload and enforce the U4 invariant via the richer
* `SoftReloadResult`, with telemetry on every non-success path so the invariant
@@ -141,63 +214,78 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra
// the same animationId so their POSTs can't interleave. Held in a ref so the
// chain survives re-renders.
const serializerRef = useRef(createKeyedSerializer());
- // fallow-ignore-next-line complexity
- const runCommit = useCallback(async (selection: DomEditSelection, mutation: Record<string, unknown>, options: CommitMutationOptions) => {
- const pid = projectIdRef.current;
- if (!pid) return;
- const unsafeFields = findUnsafeMutationValues(mutation);
- if (unsafeFields.length > 0) {
- showToast?.("Couldn't read element layout — try again at a different playhead time", "error");
- if (options.skipReload) return;
- throw new Error(`Mutation contains unsafe values: ${unsafeFields.map((field) => field.path).join(", ")}`);
- }
- const targetPath = selection.sourceFile || activeCompPath || "index.html";
- let result: MutationResult;
- try {
- result = await mutateGsapScript(pid, targetPath, mutation);
- } catch (error) {
- if (error instanceof GsapMutationHttpError) showToast?.(formatGsapMutationRejectionToast(error), "error");
- if (options.skipReload) return;
- throw error;
- }
- if (result.changed === false) {
- // The FILE already matched, but a deferred instant patch may still be
- // owed to the RUNTIME: paired commits (x with skipReload, then y carrying
- // the patch for both) rely on the SECOND commit to sync the preview — if
- // that half happens to be a no-op (a purely-horizontal drag or resize
- // compensation), returning here would leave the runtime showing the old
- // value while the file holds the new one. Patching in place is idempotent
- // when the values truly match everywhere.
- if (!options.skipReload && options.instantPatch) {
- applyPreviewSync(previewIframeRef.current, result, options, reloadPreview);
- }
- return;
- }
+ const recordMutationEdit = useCallback(async (targetPath: string, result: MutationResult, options: CommitMutationOptions) => {
+ if (result.before == null || result.after == null) return;
+ await editHistory.recordEdit({
+ label: options.label,
+ kind: "manual",
+ coalesceKey: options.coalesceKey,
+ coalesceMs: options.coalesceMs,
+ files: { [targetPath]: { before: result.before, after: result.after } },
+ });
+ }, [editHistory]);
+
+ const finalizeSuccessfulMutation = useCallback(async (selection: DomEditSelection, mutation: Record<string, unknown>, targetPath: string, result: MutationResult, options: CommitMutationOptions) => {
+ // A no-op file write may still owe the runtime a deferred instant patch.
+ if (finishUnchangedMutation(previewIframeRef.current, result, options, reloadPreview)) return;
domEditSaveTimestampRef.current = Date.now();
- if (result.before != null && result.after != null) {
- await editHistory.recordEdit({ label: options.label, kind: "manual", coalesceKey: options.coalesceKey, files: { [targetPath]: { before: result.before, after: result.after } } });
- }
+ await recordMutationEdit(targetPath, result, options);
if (result.after != null) onFileContentChanged?.(targetPath, result.after);
// Server wrote the file; the in-memory SDK doc is now stale. Resync it so a
// later SDK-routed edit doesn't serialize the pre-write doc and revert this.
forceReloadSdkSession?.();
if (options.skipReload) return;
if (result.parsed?.animations) updateKeyframeCacheFromParsed(result.parsed.animations, targetPath, selection.id ?? undefined, mutation);
- options.beforeReload?.();
- applyPreviewSync(previewIframeRef.current, result, options, reloadPreview);
- onCacheInvalidate();
- }, [projectIdRef, activeCompPath, previewIframeRef, editHistory, domEditSaveTimestampRef, reloadPreview, onCacheInvalidate, onFileContentChanged, showToast, forceReloadSdkSession]);
+ refreshMutationPreview(
+ previewIframeRef.current,
+ result,
+ options,
+ reloadPreview,
+ onCacheInvalidate,
+ );
+ }, [previewIframeRef, domEditSaveTimestampRef, reloadPreview, onCacheInvalidate, onFileContentChanged, forceReloadSdkSession, recordMutationEdit]);
+
+ const runCommit = useCallback(async (selection: DomEditSelection, mutation: Record<string, unknown>, options: CommitMutationOptions) => {
+ const pid = projectIdRef.current;
+ if (!pid) return;
+ const targetPath = selection.sourceFile || activeCompPath || "index.html";
+ const result = await runMutationRequest([mutation], options, showToast, () =>
+ mutateGsapScript(pid, targetPath, mutation),
+ );
+ if (!result) return;
+ await finalizeSuccessfulMutation(selection, mutation, targetPath, result, options);
+ }, [projectIdRef, activeCompPath, showToast, finalizeSuccessfulMutation]);
+
+ const runBatchCommit = useCallback(async (calls: CommitMutationCall[], options: CommitMutationOptions) => {
+ const pid = projectIdRef.current;
+ const first = calls[0];
+ const last = calls.at(-1);
+ if (!pid || !first || !last) return;
+ const targetPath = first.selection.sourceFile || activeCompPath || "index.html";
+ const mutations = calls.map(({ mutation }) => mutation);
+ const result = await runMutationRequest(mutations, options, showToast, () =>
+ mutateGsapScriptBatch(pid, targetPath, mutations),
+ );
+ if (!result) return;
+ await finalizeSuccessfulMutation(last.selection, last.mutation, targetPath, result, options);
+ }, [projectIdRef, activeCompPath, showToast, finalizeSuccessfulMutation]);
+
// Every GSAP-script commit is a read-modify-write of one file. Overlapping
// commits to the SAME file (any op type, any animation) interleave server-side,
// so serialize per target file by default; an explicit serializeKey overrides.
- const commitMutation = useCallback(
- (selection: DomEditSelection, mutation: Record<string, unknown>, options: CommitMutationOptions) => {
+ const commitMutation = useMemo<CommitMutation>(() => {
+ const commit: CommitMutation = (selection, mutation, options) => {
const file = selection.sourceFile || activeCompPath || "index.html";
const key = options.serializeKey ?? `gsap-file:${file}`;
return serializerRef.current(key, () => runCommit(selection, mutation, options));
- },
- [runCommit, activeCompPath],
- );
+ };
+ commit.batch = (calls, options) => {
+ const file = calls[0]?.selection.sourceFile || activeCompPath || "index.html";
+ const key = options.serializeKey ?? `gsap-file:${file}`;
+ return serializerRef.current(key, () => runBatchCommit(calls, options));
+ };
+ return commit;
+ }, [runCommit, runBatchCommit, activeCompPath]);
const trackGsapSaveFailure = useGsapSaveFailureTelemetry(activeCompPath);
const commitMutationSafely = useSafeGsapCommitMutation(commitMutation, trackGsapSaveFailure, showToast);
@@ -238,14 +326,10 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra
// exact prior content as its undo `before` (matching the style/delete paths),
// instead of a normalized full-DOM re-emit that would reformat the whole file.
const readProjectFileContent = useCallback(
- async (path: string): Promise<string> => {
+ (path: string): Promise<string> => {
const pid = projectIdRef.current;
if (!pid) throw new Error("No active project");
- const res = await fetch(`/api/projects/${pid}/files/${encodeURIComponent(path)}`);
- if (!res.ok) throw new Error(`Failed to read ${path}`);
- const data = (await res.json()) as { content?: string };
- if (typeof data.content !== "string") throw new Error(`Missing file contents for ${path}`);
- return data.content;
+ return readSharedProjectFileContent(pid, path);
},
[projectIdRef],
);
diff --git a/packages/studio/src/hooks/useGsapSelectionHandlers.ts b/packages/studio/src/hooks/useGsapSelectionHandlers.ts
index 91404017cd..191fd3a64d 100644
--- a/packages/studio/src/hooks/useGsapSelectionHandlers.ts
+++ b/packages/studio/src/hooks/useGsapSelectionHandlers.ts
@@ -5,6 +5,7 @@ import { usePlayerStore } from "../player";
import { computeCurrentPercentage } from "./gsapDragCommit";
import { trackStudioSaveFailure } from "../utils/studioSaveDiagnostics";
import { trackStudioEvent } from "../utils/studioTelemetry";
+import type { CommitMutationOptions } from "./gsapScriptCommitTypes";
/**
* Thin useCallback wrappers that guard on `domEditSelection` before
@@ -75,8 +76,14 @@ export function useGsapSelectionHandlers({
animId: string,
percentage: number,
properties: Record<string, number | string>,
+ commitOverrides?: Partial<CommitMutationOptions>,
) => Promise<void>;
- removeKeyframe: (sel: DomEditSelection, animId: string, percentage: number) => void;
+ removeKeyframe: (
+ sel: DomEditSelection,
+ animId: string,
+ percentage: number,
+ commitOverrides?: Partial<CommitMutationOptions>,
+ ) => void;
moveKeyframe: (
sel: DomEditSelection,
animId: string,
@@ -95,6 +102,7 @@ export function useGsapSelectionHandlers({
animId: string,
resolvedFromValues?: Record<string, number | string>,
duration?: number,
+ commitOverrides?: Partial<CommitMutationOptions>,
) => Promise<void>;
removeAllKeyframes: (sel: DomEditSelection, animId: string) => void;
@@ -232,20 +240,36 @@ export function useGsapSelectionHandlers({
);
const handleGsapAddKeyframeBatch = useCallback(
- (animId: string, percentage: number, properties: Record<string, number | string>) => {
+ (
+ animId: string,
+ percentage: number,
+ properties: Record<string, number | string>,
+ commitOverrides?: Partial<CommitMutationOptions>,
+ ) => {
if (!domEditSelection) return Promise.resolve();
- return addKeyframeBatch(domEditSelection, animId, percentage, properties).catch((error) => {
+ return addKeyframeBatch(
+ domEditSelection,
+ animId,
+ percentage,
+ properties,
+ commitOverrides,
+ ).catch((error) => {
trackGsapHandlerFailure(error, domEditSelection, "add-keyframe", "Add keyframe");
});
},
[domEditSelection, addKeyframeBatch, trackGsapHandlerFailure],
);
const handleGsapRemoveKeyframe = useCallback(
- (animId: string, percentage: number, selectionOverride?: DomEditSelection | null) => {
+ (
+ animId: string,
+ percentage: number,
+ commitOverrides?: Partial<CommitMutationOptions>,
+ selectionOverride?: DomEditSelection | null,
+ ) => {
const sel = selectionOverride ?? domEditSelection ?? lastSelectionRef.current;
if (!sel) return;
trackStudioEvent("keyframe", { action: "remove" });
- removeKeyframe(sel, animId, percentage);
+ removeKeyframe(sel, animId, percentage, commitOverrides);
},
[domEditSelection, removeKeyframe],
);
@@ -302,18 +326,27 @@ export function useGsapSelectionHandlers({
);
const handleGsapConvertToKeyframes = useCallback(
- (animId: string, resolvedFromValues?: Record<string, number | string>, duration?: number) => {
+ (
+ animId: string,
+ resolvedFromValues?: Record<string, number | string>,
+ duration?: number,
+ commitOverrides?: Partial<CommitMutationOptions>,
+ ) => {
if (!domEditSelection) return Promise.resolve();
- return convertToKeyframes(domEditSelection, animId, resolvedFromValues, duration).catch(
- (error) => {
- trackGsapHandlerFailure(
- error,
- domEditSelection,
- "convert-to-keyframes",
- "Convert to keyframes",
- );
- },
- );
+ return convertToKeyframes(
+ domEditSelection,
+ animId,
+ resolvedFromValues,
+ duration,
+ commitOverrides,
+ ).catch((error) => {
+ trackGsapHandlerFailure(
+ error,
+ domEditSelection,
+ "convert-to-keyframes",
+ "Convert to keyframes",
+ );
+ });
},
[domEditSelection, convertToKeyframes, trackGsapHandlerFailure],
);
diff --git a/packages/studio/src/hooks/useMusicBeatAnalysis.ts b/packages/studio/src/hooks/useMusicBeatAnalysis.ts
index da533487e5..078def68f3 100644
--- a/packages/studio/src/hooks/useMusicBeatAnalysis.ts
+++ b/packages/studio/src/hooks/useMusicBeatAnalysis.ts
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useRef } from "react";
import { usePlayerStore } from "../player/store/playerStore";
-import { isMusicTrack } from "../utils/timelineInspector";
+import { resolveBeatSourceTrack } from "../utils/timelineInspector";
import { analyzeMusicFromUrl } from "@hyperframes/core/beats";
import { useFileManagerContextOptional } from "../contexts/FileManagerContext";
import { mergeUserBeats } from "../utils/beatEditing";
@@ -52,6 +52,44 @@ async function resolveBeats(
return { ...detected, hasFile: false };
}
+/** True when the beats file for a track exists and holds at least one beat. */
+async function readHasSavedBeats(io: ProjectIo, beatPath: string): Promise<boolean> {
+ try {
+ const content = await io.readOptionalProjectFile(beatPath);
+ const parsed = content ? parseBeats(content) : null;
+ return !!(parsed && parsed.times.length > 0);
+ } catch {
+ return false;
+ }
+}
+
+type MusicAnalysis = Awaited<ReturnType<typeof analyzeMusicFromUrl>>;
+
+/**
+ * Analyze a track (memoized per URL) and fold in any saved beat edits. Null on
+ * decode/analysis failure — the caller then clears state and drops the cache
+ * entry (only when the effect is still live).
+ */
+async function loadBeatAnalysis(
+ musicSrc: string,
+ beatPath: string,
+ io: ProjectIo,
+): Promise<{ analysis: MusicAnalysis; times: number[]; strengths: number[] } | null> {
+ let promise = analysisCache.get(musicSrc);
+ if (!promise) {
+ promise = analyzeMusicFromUrl(musicSrc);
+ cacheAnalysis(musicSrc, promise);
+ }
+ try {
+ const analysis = await promise;
+ const detected = { times: analysis.beatTimes, strengths: analysis.beatStrengths };
+ const { times, strengths } = await resolveBeats(beatPath, detected, io);
+ return { analysis, times, strengths };
+ } catch {
+ return null;
+ }
+}
+
export function useMusicBeatAnalysis(): void {
const elements = usePlayerStore((s) => s.elements);
const setBeatAnalysis = usePlayerStore((s) => s.setBeatAnalysis);
@@ -71,9 +109,12 @@ export function useMusicBeatAnalysis(): void {
? { readOptionalProjectFile, writeProjectFile }
: null;
- const musicSrc = useMemo(() => {
- const el = elements.find((e) => isMusicTrack(e));
- return el?.src ?? null;
+ const { musicSrc, isFallbackTrack } = useMemo(() => {
+ const resolved = resolveBeatSourceTrack(elements);
+ return {
+ musicSrc: resolved?.element.src ?? null,
+ isFallbackTrack: resolved?.isFallback ?? false,
+ };
}, [elements]);
// ── Load: decode for strength data, then use the saved beat file if present,
@@ -95,50 +136,45 @@ export function useMusicBeatAnalysis(): void {
const beatPath = beatFilePathForSrc(musicSrc);
const io = ioRef.current;
- // Only run expensive audio decode + beat analysis when the user has an
- // explicit beats file saved. Without one, skip entirely — no surprise
- // green lines on the timeline after dragging unrelated assets.
+ // For explicitly tagged/named music tracks: only run expensive audio decode
+ // + beat analysis when the user has an explicit beats file saved. Without
+ // one, skip entirely — no surprise green lines on the timeline after
+ // dragging unrelated assets.
+ //
+ // For fallback tracks (audio dropped from Finder with no role/music-id):
+ // always run analysis so the Beat tool becomes usable immediately.
(async () => {
if (!beatPath || !io) return;
- let hasSavedBeats = false;
- try {
- const content = await io.readOptionalProjectFile(beatPath);
- const parsed = content ? parseBeats(content) : null;
- hasSavedBeats = !!(parsed && parsed.times.length > 0);
- } catch {
- /* no file */
+ if (!isFallbackTrack) {
+ const hasSavedBeats = await readHasSavedBeats(io, beatPath);
+ if (cancelled) return;
+ if (!hasSavedBeats) {
+ setBeatAnalysis(null);
+ return;
+ }
}
if (cancelled) return;
- if (!hasSavedBeats) {
+
+ const result = await loadBeatAnalysis(musicSrc, beatPath, io);
+ if (cancelled) return;
+ if (!result) {
setBeatAnalysis(null);
+ analysisCache.delete(musicSrc);
return;
}
-
- let promise = analysisCache.get(musicSrc);
- if (!promise) {
- promise = analyzeMusicFromUrl(musicSrc);
- cacheAnalysis(musicSrc, promise);
- }
- try {
- const analysis = await promise;
- const detected = { times: analysis.beatTimes, strengths: analysis.beatStrengths };
- const { times, strengths } = await resolveBeats(beatPath, detected, io);
- if (cancelled) return;
- setBeatEdits(null);
- resetBeatHistory();
- setBeatAnalysis({ ...analysis, beatTimes: times, beatStrengths: strengths });
- } catch {
- if (!cancelled) {
- setBeatAnalysis(null);
- analysisCache.delete(musicSrc);
- }
- }
+ setBeatEdits(null);
+ resetBeatHistory();
+ setBeatAnalysis({
+ ...result.analysis,
+ beatTimes: result.times,
+ beatStrengths: result.strengths,
+ });
})();
return () => {
cancelled = true;
};
- }, [musicSrc, setBeatAnalysis, setBeatEdits, resetBeatHistory]);
+ }, [musicSrc, isFallbackTrack, setBeatAnalysis, setBeatEdits, resetBeatHistory]);
// ── Persist: register a debounced writer fired by every beat edit/undo/redo.
// Flushes any pending write on cleanup so the last edit is never lost. ──
diff --git a/packages/studio/src/hooks/usePersistentEditHistory.test.ts b/packages/studio/src/hooks/usePersistentEditHistory.test.ts
index 3128ab0bb1..8b14c4605f 100644
--- a/packages/studio/src/hooks/usePersistentEditHistory.test.ts
+++ b/packages/studio/src/hooks/usePersistentEditHistory.test.ts
@@ -213,6 +213,39 @@ describe("createPersistentEditHistoryController", () => {
expect(store.snapshot().canRedo).toBe(true);
});
+ it("returns per-file restored/previous content so the preview can soft-apply", async () => {
+ const storage = createMemoryEditHistoryStorage();
+ const store = createPersistentEditHistoryStore({
+ projectId: "project-1",
+ storage,
+ initialState: createEmptyEditHistory(),
+ now: () => 100,
+ onChange: () => {},
+ });
+ await store.recordEdit({
+ label: "Move layer",
+ kind: "manual",
+ files: { "index.html": { before: "OLD", after: "NEW" } },
+ });
+ const disk: Record<string, string> = { "index.html": "NEW" };
+ const undo = await store.undo({
+ readFile: async (p) => disk[p],
+ writeFile: async (p, c) => {
+ disk[p] = c;
+ },
+ });
+ // `restored` = bytes written (the undo target), `previous` = the current live bytes.
+ expect(undo.files).toEqual({ "index.html": { previous: "NEW", restored: "OLD" } });
+
+ const redo = await store.redo({
+ readFile: async (p) => disk[p],
+ writeFile: async (p, c) => {
+ disk[p] = c;
+ },
+ });
+ expect(redo.files).toEqual({ "index.html": { previous: "OLD", restored: "NEW" } });
+ });
+
it("rolls back files when an undo write fails partway through", async () => {
const storage = createMemoryEditHistoryStorage();
const store = createPersistentEditHistoryStore({
diff --git a/packages/studio/src/hooks/usePersistentEditHistory.ts b/packages/studio/src/hooks/usePersistentEditHistory.ts
index de1af2867c..61779eddec 100644
--- a/packages/studio/src/hooks/usePersistentEditHistory.ts
+++ b/packages/studio/src/hooks/usePersistentEditHistory.ts
@@ -7,8 +7,10 @@ import {
redoEditHistory,
undoEditHistory,
type BuildEditHistoryEntryInput,
+ type EditHistoryEntry,
type EditHistoryKind,
type EditHistoryState,
+ type EditHistoryTransitionResult,
} from "../utils/editHistory";
import {
createIndexedDbEditHistoryStorage,
@@ -21,6 +23,7 @@ interface RecordEditInput {
label: string;
kind: EditHistoryKind;
coalesceKey?: string;
+ coalesceMs?: number;
files: BuildEditHistoryEntryInput["files"];
}
@@ -35,11 +38,24 @@ interface UsePersistentEditHistoryOptions {
now?: () => number;
}
+/**
+ * Per-file content the restore just applied. `restored` is the bytes written to
+ * disk (the undo/redo target); `previous` is what was on disk immediately before
+ * (the current live preview state). The undo preview-sync diffs these to decide
+ * whether the restore is soft-reloadable (attributes/style/GSAP-script only) or
+ * needs a full iframe reload.
+ */
+interface ApplyRestoredFile {
+ previous: string;
+ restored: string;
+}
+
interface ApplyResult {
ok: boolean;
reason?: "empty" | "content-mismatch";
label?: string;
paths?: string[];
+ files?: Record<string, ApplyRestoredFile>;
}
interface PersistentEditHistoryStoreOptions {
@@ -55,6 +71,18 @@ type EditHistoryMutation<T> = (state: EditHistoryState) => Promise<{
result: T;
}>;
+/** Pair the just-written (`restored`) bytes with the pre-write (`previous`) bytes per path. */
+function restoredFilesMap(
+ filesToWrite: Record<string, string>,
+ currentFiles: Record<string, string>,
+): Record<string, ApplyRestoredFile> {
+ const out: Record<string, ApplyRestoredFile> = {};
+ for (const [path, restored] of Object.entries(filesToWrite)) {
+ out[path] = { previous: currentFiles[path] ?? "", restored };
+ }
+ return out;
+}
+
function createEntryId(now: number): string {
return `edit-${now.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
@@ -120,6 +148,52 @@ async function writeFilesWithRollback({
}
}
+/**
+ * Apply one undo/redo step: read current on-disk hashes, run the direction's
+ * transition, write the restored files with rollback, and shape the ApplyResult.
+ * `entry` is the stack top used to know which paths to hash before applying.
+ */
+async function applyHistoryStep(
+ currentState: EditHistoryState,
+ entry: EditHistoryEntry | undefined,
+ transition: (
+ state: EditHistoryState,
+ currentHashes: Record<string, string>,
+ now: number,
+ ) => EditHistoryTransitionResult,
+ now: () => number,
+ callbacks: ApplyCallbacks,
+): Promise<{ state: EditHistoryState; result: ApplyResult }> {
+ if (!entry) {
+ return { state: currentState, result: { ok: false, reason: "empty" } };
+ }
+ const { currentFiles, currentHashes } = await readCurrentFileHashes(
+ Object.keys(entry.files),
+ callbacks.readFile,
+ );
+ const result = transition(currentState, currentHashes, now());
+ if (!result.ok) {
+ return {
+ state: currentState,
+ result: { ok: false, reason: result.reason },
+ };
+ }
+ await writeFilesWithRollback({
+ files: result.filesToWrite,
+ rollbackFiles: currentFiles,
+ writeFile: callbacks.writeFile,
+ });
+ return {
+ state: result.state,
+ result: {
+ ok: true,
+ label: result.entry.label,
+ paths: Object.keys(result.entry.files),
+ files: restoredFilesMap(result.filesToWrite, currentFiles),
+ },
+ };
+}
+
export function createPersistentEditHistoryStore({
projectId,
storage,
@@ -171,66 +245,26 @@ export function createPersistentEditHistoryStore({
});
},
async undo(callbacks: ApplyCallbacks): Promise<ApplyResult> {
- return mutate<ApplyResult>(async (currentState) => {
- const entry = currentState.undo[currentState.undo.length - 1];
- if (!entry) {
- return {
- state: currentState,
- result: { ok: false, reason: "empty" },
- };
- }
- const { currentFiles, currentHashes } = await readCurrentFileHashes(
- Object.keys(entry.files),
- callbacks.readFile,
- );
- const result = undoEditHistory(currentState, currentHashes, now());
- if (!result.ok) {
- return {
- state: currentState,
- result: { ok: false, reason: result.reason },
- };
- }
- await writeFilesWithRollback({
- files: result.filesToWrite,
- rollbackFiles: currentFiles,
- writeFile: callbacks.writeFile,
- });
- return {
- state: result.state,
- result: { ok: true, label: result.entry.label, paths: Object.keys(result.entry.files) },
- };
- });
+ return mutate<ApplyResult>((currentState) =>
+ applyHistoryStep(
+ currentState,
+ currentState.undo[currentState.undo.length - 1],
+ undoEditHistory,
+ now,
+ callbacks,
+ ),
+ );
},
async redo(callbacks: ApplyCallbacks): Promise<ApplyResult> {
- return mutate<ApplyResult>(async (currentState) => {
- const entry = currentState.redo[currentState.redo.length - 1];
- if (!entry) {
- return {
- state: currentState,
- result: { ok: false, reason: "empty" },
- };
- }
- const { currentFiles, currentHashes } = await readCurrentFileHashes(
- Object.keys(entry.files),
- callbacks.readFile,
- );
- const result = redoEditHistory(currentState, currentHashes, now());
- if (!result.ok) {
- return {
- state: currentState,
- result: { ok: false, reason: result.reason },
- };
- }
- await writeFilesWithRollback({
- files: result.filesToWrite,
- rollbackFiles: currentFiles,
- writeFile: callbacks.writeFile,
- });
- return {
- state: result.state,
- result: { ok: true, label: result.entry.label, paths: Object.keys(result.entry.files) },
- };
- });
+ return mutate<ApplyResult>((currentState) =>
+ applyHistoryStep(
+ currentState,
+ currentState.redo[currentState.redo.length - 1],
+ redoEditHistory,
+ now,
+ callbacks,
+ ),
+ );
},
};
}
diff --git a/packages/studio/src/hooks/usePreviewPersistence.ts b/packages/studio/src/hooks/usePreviewPersistence.ts
index 657fb5dad9..b6759485b9 100644
--- a/packages/studio/src/hooks/usePreviewPersistence.ts
+++ b/packages/studio/src/hooks/usePreviewPersistence.ts
@@ -10,6 +10,14 @@ 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 { usePlayerStore } from "../player";
+
+/** The restore payload the undo/redo preview-sync consumes (from the history store). */
+interface HistoryPreviewRestore {
+ paths?: string[];
+ files?: Record<string, UndoRestoreFile>;
+}
// ── Types ──
@@ -105,13 +113,12 @@ export function usePreviewPersistence({
writeProjectFile: _writeProjectFile,
recordEdit: _recordEdit,
previewIframeRef,
- activeCompPathRef: _activeCompPathRef,
+ activeCompPathRef,
domEditSaveTimestampRef,
reloadPreview,
pendingTimelineEditPathRef,
}: UsePreviewPersistenceParams) {
void _recordEdit;
- void _activeCompPathRef;
const [domEditSaveQueuePaused, setDomEditSaveQueuePaused] = useState<string | null>(null);
@@ -190,12 +197,23 @@ export function usePreviewPersistence({
// ── Sync preview after undo/redo ──
const syncHistoryPreviewAfterApply = useCallback(
- async (_paths: string[] | undefined) => {
- // Motion data is now stored in HTML attributes — any undo/redo that touches HTML
- // files triggers a full reload which picks up the changes automatically.
- reloadPreview();
+ async (restore: HistoryPreviewRestore) => {
+ // Prefer an in-place soft reload for a soft-reloadable restore (the change
+ // is confined to the active comp's element attributes / inline-style and/or
+ // its GSAP script) — a full iframe remount blanks the frame black and
+ // re-flashes the WebGL context. applyUndoRestoreToPreview syncs the reverted
+ // attributes onto the live DOM and re-runs the timeline at the SAME playhead,
+ // falling back to reloadPreview for anything structural (split/delete undo),
+ // multi-file, sub-comp, or a permanent soft-reload failure.
+ applyUndoRestoreToPreview(
+ previewIframeRef.current,
+ activeCompPathRef.current,
+ restore.files,
+ usePlayerStore.getState().currentTime,
+ reloadPreview,
+ );
},
- [reloadPreview],
+ [previewIframeRef, activeCompPathRef, reloadPreview],
);
// ── Migrate legacy studio-motion.json ──
diff --git a/packages/studio/src/hooks/useRazorSplit.history.test.tsx b/packages/studio/src/hooks/useRazorSplit.history.test.tsx
index b543676b61..567aeb16b5 100644
--- a/packages/studio/src/hooks/useRazorSplit.history.test.tsx
+++ b/packages/studio/src/hooks/useRazorSplit.history.test.tsx
@@ -1,20 +1,25 @@
// @vitest-environment happy-dom
-import React, { act } from "react";
-import { createRoot } from "react-dom/client";
+import { act } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
+import { splitElementInHtml } from "@hyperframes/studio-server/source-mutation";
import type { TimelineElement } from "../player";
+import { usePlayerStore } from "../player";
import { useRazorSplit } from "./useRazorSplit";
import { createPersistentEditHistoryStore } from "./usePersistentEditHistory";
import { createMemoryEditHistoryStorage } from "../utils/editHistoryStorage";
-import { createEmptyEditHistory } from "../utils/editHistory";
+import {
+ createEmptyEditHistory,
+ hashEditHistoryContent,
+ undoEditHistory,
+} from "../utils/editHistory";
+import { createSplitFetchMock, mountProbe } from "./useRazorSplit.testHelpers";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-const ORIGINAL = `<div class="clip" id="clip1" data-start="0" data-duration="4">hi</div>`;
-const SPLIT =
- `<div class="clip" id="clip1" data-start="0" data-duration="2">hi</div>` +
- `<div class="clip" id="clip1-split" data-start="2" data-duration="2">hi</div>`;
+const ORIGINAL = `<div class="clip" id="clip1" data-start="0" data-duration="4" data-hf-id="hf-clip">hi</div>`;
+const SPLIT = splitElementInHtml(ORIGINAL, { id: "clip1" }, 2, "clip1-split").html;
const element: TimelineElement = {
id: "clip1",
@@ -28,13 +33,15 @@ const element: TimelineElement = {
};
type Split = (element: TimelineElement, splitTime: number) => Promise<void>;
+type SplitAll = (splitTime: number) => Promise<void>;
interface Harness {
disk: Record<string, string>;
store: ReturnType<typeof createPersistentEditHistoryStore>;
splitRef: { current: Split | undefined };
- root: ReturnType<typeof createRoot>;
+ root: ReturnType<typeof mountProbe>;
expected: string;
+ previewWrites: string[];
}
const SPLIT_GSAP = SPLIT.replace(
@@ -43,9 +50,10 @@ const SPLIT_GSAP = SPLIT.replace(
'tl.set("#clip1-split",{x:0},2);window.__timelines["c"]=tl;</script>',
);
-function mountRazorSplit(opts: { gsap?: boolean } = {}): Harness {
+function mountRazorSplit(opts: { gsap?: boolean; previewStamp?: boolean } = {}): Harness {
const disk: Record<string, string> = { "index.html": ORIGINAL };
const finalContent = opts.gsap ? SPLIT_GSAP : SPLIT;
+ const previewWrites: string[] = [];
const storage = createMemoryEditHistoryStorage();
const store = createPersistentEditHistoryStore({
@@ -109,23 +117,28 @@ function mountRazorSplit(opts: { gsap?: boolean } = {}): Harness {
},
recordEdit: store.recordEdit,
domEditSaveTimestampRef: { current: 0 },
- reloadPreview: () => {},
+ reloadPreview: () => {
+ if (!opts.previewStamp) return;
+ const stamped = ensureHfIds(disk["index.html"]);
+ const idsBefore = (disk["index.html"].match(/\bdata-hf-id=/g) ?? []).length;
+ const idsAfter = (stamped.match(/\bdata-hf-id=/g) ?? []).length;
+ if (idsAfter > idsBefore) {
+ disk["index.html"] = stamped;
+ previewWrites.push(stamped);
+ }
+ },
+ forceReloadSdkSession: () => {},
});
splitRef.current = handleRazorSplit;
return null;
}
- const host = document.createElement("div");
- document.body.append(host);
- const root = createRoot(host);
- act(() => {
- root.render(<Component />);
- });
+ const root = mountProbe(Component);
- return { disk, store, splitRef, root, expected: finalContent };
+ return { disk, store, splitRef, root, expected: finalContent, previewWrites };
}
-async function undoViaDisk(harness: Harness) {
+async function undoViaDisk(harness: Pick<Harness, "disk" | "store">) {
return harness.store.undo({
readFile: async (path) => harness.disk[path],
writeFile: async (path, content) => {
@@ -140,6 +153,26 @@ afterEach(() => {
});
describe("useRazorSplit — split is undoable via edit history", () => {
+ it("keeps history aligned when preview reload checks hf-id persistence", async () => {
+ const harness = mountRazorSplit({ previewStamp: true });
+
+ await act(async () => {
+ await harness.splitRef.current!(element, 2);
+ });
+
+ const snapshot = harness.store.snapshot().state;
+ const entry = snapshot.undo.at(-1)!;
+ const currentHash = hashEditHistoryContent(harness.disk["index.html"]);
+ expect(entry.files["index.html"].afterHash).toBe(currentHash);
+
+ const undo = undoEditHistory(snapshot, { "index.html": currentHash }, 2000);
+ expect(undo.ok).toBe(true);
+ expect(undo.filesToWrite).toEqual({ "index.html": ORIGINAL });
+ expect(harness.previewWrites).toHaveLength(0);
+
+ act(() => harness.root.unmount());
+ });
+
for (const gsap of [false, true]) {
describe(gsap ? "with GSAP rewrite" : "plain HTML split", () => {
let harness: Harness;
@@ -171,3 +204,100 @@ describe("useRazorSplit — split is undoable via edit history", () => {
});
}
});
+
+const BATCH_ORIGINALS = {
+ "index.html": `<div class="clip" id="clip1" data-start="0" data-duration="4">one</div>`,
+ "scenes/two.html": `<div class="clip" id="clip2" data-start="0" data-duration="4">two</div>`,
+};
+
+const batchElements: TimelineElement[] = [
+ element,
+ {
+ ...element,
+ id: "clip2",
+ domId: "clip2",
+ sourceFile: "scenes/two.html",
+ track: 1,
+ },
+];
+
+interface SplitAllHarness {
+ disk: Record<string, string>;
+ store: ReturnType<typeof createPersistentEditHistoryStore>;
+ splitAllRef: { current: SplitAll | undefined };
+ root: ReturnType<typeof mountProbe>;
+}
+
+function mountRazorSplitAll(failOnSplit?: number): SplitAllHarness {
+ const disk: Record<string, string> = { ...BATCH_ORIGINALS };
+ const store = createPersistentEditHistoryStore({
+ projectId: "p1",
+ storage: createMemoryEditHistoryStorage(),
+ initialState: createEmptyEditHistory(),
+ now: () => 1000,
+ onChange: () => {},
+ });
+ let splitCount = 0;
+
+ vi.stubGlobal(
+ "fetch",
+ createSplitFetchMock(disk, () => {
+ splitCount++;
+ if (splitCount === failOnSplit) throw new Error("simulated split failure");
+ }),
+ );
+
+ const splitAllRef: { current: SplitAll | undefined } = { current: undefined };
+ function Component() {
+ const { handleRazorSplitAll } = useRazorSplit({
+ projectId: "p1",
+ activeCompPath: "index.html",
+ showToast: () => {},
+ writeProjectFile: async (path, content) => {
+ disk[path] = content;
+ },
+ recordEdit: store.recordEdit,
+ domEditSaveTimestampRef: { current: 0 },
+ reloadPreview: () => {},
+ });
+ splitAllRef.current = handleRazorSplitAll;
+ return null;
+ }
+
+ const root = mountProbe(Component);
+ usePlayerStore.setState({ elements: batchElements });
+ return { disk, store, splitAllRef, root };
+}
+
+describe("useRazorSplit — split-all batch history", () => {
+ afterEach(() => {
+ usePlayerStore.setState({ elements: [] });
+ });
+
+ async function runSplitAll(failOnSplit?: number) {
+ const harness = mountRazorSplitAll(failOnSplit);
+ await act(async () => {
+ await harness.splitAllRef.current!(2);
+ });
+ return harness;
+ }
+
+ it("records one undo entry that restores every split file", async () => {
+ const harness = await runSplitAll();
+
+ expect(harness.store.snapshot().canUndo).toBe(true);
+ const result = await undoViaDisk(harness);
+ expect(result.ok).toBe(true);
+ expect(harness.disk).toEqual(BATCH_ORIGINALS);
+ expect(harness.store.snapshot().canUndo).toBe(false);
+ act(() => harness.root.unmount());
+ });
+
+ it("restores completed writes and records no undo when a later split fails", async () => {
+ const harness = await runSplitAll(2);
+
+ expect(harness.disk).toEqual(BATCH_ORIGINALS);
+ expect(harness.store.snapshot().canUndo).toBe(false);
+ act(() => harness.root.unmount());
+ });
+});
diff --git a/packages/studio/src/hooks/useRazorSplit.test.ts b/packages/studio/src/hooks/useRazorSplit.test.ts
new file mode 100644
index 0000000000..02a33014a5
--- /dev/null
+++ b/packages/studio/src/hooks/useRazorSplit.test.ts
@@ -0,0 +1,269 @@
+// @vitest-environment happy-dom
+
+import { act } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { TimelineElement } from "../player";
+import { usePlayerStore } from "../player";
+import { useRazorSplit } from "./useRazorSplit";
+import { createPersistentEditHistoryStore } from "./usePersistentEditHistory";
+import { createEmptyEditHistory } from "../utils/editHistory";
+import type { EditHistoryStorageAdapter } from "../utils/editHistoryStorage";
+import { createSplitFetchMock, mountProbe } from "./useRazorSplit.testHelpers";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const ROOT_FILE = "index.html";
+const SUBCOMP_FILE = "scenes/intro.html";
+
+// A root-level clip lives in index.html and is authored in local time already.
+const rootElement: TimelineElement = {
+ id: "root-clip",
+ tag: "div",
+ start: 0,
+ duration: 10,
+ track: 0,
+ domId: "root-clip",
+ sourceFile: ROOT_FILE,
+ timingSource: "authored",
+};
+
+// An expanded sub-comp child: `start` is in MASTER coordinates (offset by the
+// host's master start), `sourceFile` is the sub-comp, and `expandedParentStart`
+// is that host master start. Its authored time in the file is start - basis.
+const expandedChild: TimelineElement = {
+ id: "child-clip",
+ tag: "div",
+ start: 2,
+ duration: 6,
+ track: 1,
+ domId: "child-clip",
+ sourceFile: SUBCOMP_FILE,
+ timingSource: "authored",
+ expandedParentStart: 2,
+};
+
+interface SplitRequest {
+ path: string;
+ splitTime: number;
+ elementStart: number;
+ elementDuration: number;
+}
+
+type SingleSplit = (element: TimelineElement, splitTime: number) => Promise<void>;
+type SplitAll = (splitTime: number) => Promise<void>;
+
+interface Harness {
+ splitRequests: SplitRequest[];
+ singleRef: { current: SingleSplit | undefined };
+ allRef: { current: SplitAll | undefined };
+ root: ReturnType<typeof mountProbe>;
+}
+
+function mountRazorSplit(): Harness {
+ const disk: Record<string, string> = {
+ [ROOT_FILE]: `<div class="clip" id="root-clip" data-start="0" data-duration="10"></div>`,
+ [SUBCOMP_FILE]: `<div class="clip" id="child-clip" data-start="0" data-duration="6"></div>`,
+ };
+ const splitRequests: SplitRequest[] = [];
+
+ const fetchMock = createSplitFetchMock(disk, (path, body) => {
+ splitRequests.push({
+ path,
+ splitTime: body.splitTime,
+ elementStart: body.elementStart,
+ elementDuration: body.elementDuration,
+ });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const singleRef: { current: SingleSplit | undefined } = { current: undefined };
+ const allRef: { current: SplitAll | undefined } = { current: undefined };
+
+ function Component() {
+ const { handleRazorSplit, handleRazorSplitAll } = useRazorSplit({
+ projectId: "p1",
+ activeCompPath: ROOT_FILE,
+ showToast: () => {},
+ writeProjectFile: async (path, content) => {
+ disk[path] = content;
+ },
+ recordEdit: async () => {},
+ domEditSaveTimestampRef: { current: 0 },
+ reloadPreview: () => {},
+ });
+ singleRef.current = handleRazorSplit;
+ allRef.current = handleRazorSplitAll;
+ return null;
+ }
+
+ const root = mountProbe(Component);
+ return { splitRequests, singleRef, allRef, root };
+}
+
+afterEach(() => {
+ document.body.innerHTML = "";
+ usePlayerStore.setState({ elements: [] });
+ vi.unstubAllGlobals();
+});
+
+describe("useRazorSplit — sub-comp coordinate rebasing", () => {
+ let harness: Harness;
+ beforeEach(() => {
+ harness = mountRazorSplit();
+ });
+ afterEach(() => {
+ act(() => harness.root.unmount());
+ });
+
+ it("rebases an expanded sub-comp child split into the sub-comp's local time", async () => {
+ // Master split time T = 5; host starts at 2, so local time is 3.
+ await act(async () => {
+ await harness.singleRef.current!(expandedChild, 5);
+ });
+
+ expect(harness.splitRequests).toHaveLength(1);
+ const req = harness.splitRequests[0];
+ expect(req.path).toBe(SUBCOMP_FILE);
+ expect(req.splitTime).toBe(3); // 5 - expandedParentStart(2), NOT 5
+ expect(req.elementStart).toBe(0); // 2 - 2, NOT the master start 2
+ expect(req.elementDuration).toBe(6);
+ });
+
+ it("leaves a root-level clip's coordinates unchanged", async () => {
+ // Master split time T = 4; no expandedParentStart, so nothing is rebased.
+ await act(async () => {
+ await harness.singleRef.current!(rootElement, 4);
+ });
+
+ expect(harness.splitRequests).toHaveLength(1);
+ const req = harness.splitRequests[0];
+ expect(req.path).toBe(ROOT_FILE);
+ expect(req.splitTime).toBe(4);
+ expect(req.elementStart).toBe(0);
+ expect(req.elementDuration).toBe(10);
+ });
+
+ it("rebases each element individually in a mixed razor-split-all gesture", async () => {
+ usePlayerStore.setState({ elements: [rootElement, expandedChild] });
+
+ // Master split time T = 3 lies inside both clips.
+ await act(async () => {
+ await harness.allRef.current!(3);
+ });
+
+ expect(harness.splitRequests).toHaveLength(2);
+ const rootReq = harness.splitRequests.find((r) => r.path === ROOT_FILE)!;
+ const childReq = harness.splitRequests.find((r) => r.path === SUBCOMP_FILE)!;
+
+ // Root clip: already local — master coordinates pass through untouched.
+ expect(rootReq.splitTime).toBe(3);
+ expect(rootReq.elementStart).toBe(0);
+
+ // Expanded child: rebased by its OWN expandedParentStart, not the root's.
+ expect(childReq.splitTime).toBe(1); // 3 - 2
+ expect(childReq.elementStart).toBe(0); // 2 - 2
+ });
+});
+
+// ── Bug 1: split must resync the SDK session so undo isn't refused ────────────
+
+const memoryStorage = (): EditHistoryStorageAdapter => {
+ const store = new Map<string, string>();
+ return {
+ load: async (k) => store.get(k) ?? null,
+ save: async (k, v) => {
+ store.set(k, v);
+ },
+ } as unknown as EditHistoryStorageAdapter;
+};
+
+interface UndoHarness {
+ singleRef: { current: SingleSplit | undefined };
+ disk: Record<string, string>;
+ store: ReturnType<typeof createPersistentEditHistoryStore>;
+ forceReloadSdkSession: ReturnType<typeof vi.fn>;
+ root: ReturnType<typeof mountProbe>;
+}
+
+function mountRazorSplitWithHistory(): UndoHarness {
+ const disk: Record<string, string> = {
+ [ROOT_FILE]: `<div class="clip" id="root-clip" data-start="0" data-duration="10"></div>`,
+ };
+ const store = createPersistentEditHistoryStore({
+ projectId: "p1",
+ storage: memoryStorage(),
+ initialState: createEmptyEditHistory(),
+ now: () => Date.now(),
+ onChange: () => {},
+ });
+ const forceReloadSdkSession = vi.fn();
+
+ const fetchMock = createSplitFetchMock(disk);
+ vi.stubGlobal("fetch", fetchMock);
+
+ const singleRef: { current: SingleSplit | undefined } = { current: undefined };
+ function Component() {
+ const { handleRazorSplit } = useRazorSplit({
+ projectId: "p1",
+ activeCompPath: ROOT_FILE,
+ showToast: () => {},
+ writeProjectFile: async (path, content) => {
+ disk[path] = content;
+ },
+ recordEdit: (input) => store.recordEdit(input),
+ domEditSaveTimestampRef: { current: 0 },
+ reloadPreview: () => {},
+ forceReloadSdkSession,
+ });
+ singleRef.current = handleRazorSplit;
+ return null;
+ }
+ const root = mountProbe(Component);
+ return { singleRef, disk, store, forceReloadSdkSession, root };
+}
+
+describe("useRazorSplit — undo integrity after split (Bug 1)", () => {
+ let h: UndoHarness;
+ beforeEach(() => {
+ h = mountRazorSplitWithHistory();
+ });
+ afterEach(() => {
+ act(() => h.root.unmount());
+ });
+
+ const readFile = () => ({
+ readFile: async (p: string) => h.disk[p],
+ writeFile: async (p: string, c: string) => {
+ h.disk[p] = c;
+ },
+ });
+
+ it("resyncs the SDK session after a split (matches every other server-write path)", async () => {
+ await act(async () => {
+ await h.singleRef.current!(rootElement, 4);
+ });
+ expect(h.forceReloadSdkSession).toHaveBeenCalledTimes(1);
+ });
+
+ it("applies undo after a split without an external-change refusal", async () => {
+ await act(async () => {
+ await h.singleRef.current!(rootElement, 4);
+ });
+ const result = await h.store.undo(readFile());
+ expect(result.ok).toBe(true);
+ expect(result.reason).toBeUndefined();
+ // The file is restored to its pre-split bytes.
+ expect(h.disk[ROOT_FILE]).not.toContain("<!--split-->");
+ });
+
+ it("still trips the guard when the file is edited externally after a split", async () => {
+ await act(async () => {
+ await h.singleRef.current!(rootElement, 4);
+ });
+ // Simulate the user editing the file in their own editor after the split.
+ h.disk[ROOT_FILE] = `${h.disk[ROOT_FILE]}<!--hand-edit-->`;
+ const result = await h.store.undo(readFile());
+ expect(result.ok).toBe(false);
+ expect(result.reason).toBe("content-mismatch");
+ });
+});
diff --git a/packages/studio/src/hooks/useRazorSplit.testHelpers.ts b/packages/studio/src/hooks/useRazorSplit.testHelpers.ts
new file mode 100644
index 0000000000..52cfa2d16f
--- /dev/null
+++ b/packages/studio/src/hooks/useRazorSplit.testHelpers.ts
@@ -0,0 +1,64 @@
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { vi } from "vitest";
+
+export interface SplitBody {
+ splitTime: number;
+ elementStart: number;
+ elementDuration: number;
+}
+
+function decodePathFromUrl(url: string, marker: string): string {
+ const encoded = url.slice(url.indexOf(marker) + marker.length);
+ return decodeURIComponent(encoded);
+}
+
+/**
+ * Fetch mock shared by both harnesses: GSAP mutations 400 (no script in fixtures),
+ * split-element writes a `<!--split-->` marker so `changed` is true, and file reads
+ * echo the in-memory `disk`. `onSplit` (when set) records each split request's body.
+ */
+export function createSplitFetchMock(
+ disk: Record<string, string>,
+ onSplit?: (path: string, body: SplitBody) => void,
+) {
+ return vi.fn(async (url: string, init?: RequestInit) => {
+ const u = String(url);
+ if (u.includes("/gsap-mutations/")) {
+ // No GSAP script in the fixtures — mirror the server's 400 response.
+ return new Response(JSON.stringify({ error: "no GSAP script found in file" }), {
+ status: 400,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+ if (u.includes("/file-mutations/split-element/")) {
+ const path = decodePathFromUrl(u, "/file-mutations/split-element/");
+ onSplit?.(path, JSON.parse(String(init?.body)) as SplitBody);
+ // Return content that differs from the original so `changed` is true.
+ const after = `${disk[path]}<!--split-->`;
+ disk[path] = after; // server writes the split to disk
+ return new Response(JSON.stringify({ ok: true, changed: true, content: after }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+ if (u.includes("/files/")) {
+ const path = decodePathFromUrl(u, "/files/").replace(/\?.*$/, "");
+ return new Response(JSON.stringify({ content: disk[path] ?? "" }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+ void init;
+ throw new Error(`unexpected fetch: ${u}`);
+ });
+}
+
+/** Mount a render-only probe component into a fresh host and return its root. */
+export function mountProbe(Component: React.ComponentType): ReturnType<typeof createRoot> {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ act(() => root.render(React.createElement(Component)));
+ return root;
+}
diff --git a/packages/studio/src/hooks/useRazorSplit.ts b/packages/studio/src/hooks/useRazorSplit.ts
index 7fd8a72a69..a263cac3b6 100644
--- a/packages/studio/src/hooks/useRazorSplit.ts
+++ b/packages/studio/src/hooks/useRazorSplit.ts
@@ -20,6 +20,14 @@ interface UseRazorSplitOptions {
recordEdit: (input: RecordEditInput) => Promise<void>;
domEditSaveTimestampRef: React.MutableRefObject<number>;
reloadPreview: () => void;
+ /**
+ * Resync the in-memory SDK session after the server-side split write (the
+ * split-element / split-gsap endpoints write the file directly, so the SDK's
+ * linkedom doc is now stale). This reload is read-only; the split endpoint owns
+ * the final on-disk bytes and history baseline. Every other server-side-write
+ * timeline path (move / resize / delete / drop / visibility) also resyncs.
+ */
+ forceReloadSdkSession?: () => void;
isRecordingRef?: React.RefObject<boolean>;
}
@@ -101,6 +109,62 @@ async function splitGsapAnimations(
};
}
+function getOriginalContent(originals: ReadonlyMap<string, string>, path: string): string {
+ const original = originals.get(path);
+ if (original === undefined) {
+ throw new Error(`Missing original contents for ${path}`);
+ }
+ return original;
+}
+
+async function restoreFilesToOriginal(
+ originals: ReadonlyMap<string, string>,
+ paths: Iterable<string>,
+ writeProjectFile: (path: string, content: string) => Promise<void>,
+): Promise<void> {
+ for (const path of paths) {
+ await writeProjectFile(path, getOriginalContent(originals, path));
+ }
+}
+
+async function readOriginalFiles(
+ pid: string,
+ elements: TimelineElement[],
+ activeCompPath: string | null,
+): Promise<Map<string, string>> {
+ const originals = new Map<string, string>();
+ for (const element of elements) {
+ const path = element.sourceFile || activeCompPath || "index.html";
+ if (!originals.has(path)) {
+ originals.set(path, await readFileContent(pid, path));
+ }
+ }
+ return originals;
+}
+
+async function splitElementsAtTime(
+ pid: string,
+ elements: TimelineElement[],
+ splitTime: number,
+ activeCompPath: string | null,
+ originals: ReadonlyMap<string, string>,
+ snapshots: Map<string, { before: string; after: string }>,
+ writeProjectFile: (path: string, content: string) => Promise<void>,
+): Promise<number> {
+ let count = 0;
+ for (const element of elements) {
+ const result = await executeSplit(pid, element, splitTime, activeCompPath, writeProjectFile);
+ if (!result.changed) continue;
+ snapshots.set(result.targetPath, {
+ before: getOriginalContent(originals, result.targetPath),
+ after: result.patchedContent,
+ });
+ await writeProjectFile(result.targetPath, result.patchedContent);
+ count++;
+ }
+ return count;
+}
+
// fallow-ignore-next-line complexity
async function executeSplit(
pid: string,
@@ -122,13 +186,23 @@ async function executeSplit(
const originalContent = await readFileContent(pid, targetPath);
const newId = generateSplitId(collectHtmlIds(originalContent), element.domId || "clip");
+ // An expanded sub-comp child arrives in MASTER-timeline coordinates — both its
+ // `start` and the incoming `splitTime` are offset by the host's master start
+ // (expandedParentStart) — but its `sourceFile` is the sub-comp, whose clips are
+ // authored in LOCAL time. Rebase both onto local time before the server patches
+ // the file, exactly as TimelinePane.handleSplitElement does for non-razor edits.
+ // Root-level clips (no expandedParentStart) are already local, so pass through.
+ const basis = element.expandedParentStart;
+ const localSplitTime = basis === undefined ? splitTime : Math.max(0, splitTime - basis);
+ const localElementStart = basis === undefined ? element.start : element.start - basis;
+
const splitResult = await splitHtmlElement(
pid,
targetPath,
patchTarget,
- splitTime,
+ localSplitTime,
newId,
- element.start,
+ localElementStart,
element.duration,
);
if (!splitResult.ok) throw new Error("Failed to split clip.");
@@ -147,8 +221,8 @@ async function executeSplit(
targetPath,
element.domId,
newId,
- splitTime,
- element.start,
+ localSplitTime,
+ localElementStart,
element.duration,
);
if (gsapResult.content) patchedContent = gsapResult.content;
@@ -172,6 +246,7 @@ export function useRazorSplit({
recordEdit,
domEditSaveTimestampRef,
reloadPreview,
+ forceReloadSdkSession,
isRecordingRef,
}: UseRazorSplitOptions) {
const projectIdRef = useRef(projectId);
@@ -208,6 +283,9 @@ export function useRazorSplit({
recordEdit,
});
+ // Server writes bypass the SDK session, so reopen it before refreshing
+ // the preview. The split response already owns the final persisted bytes.
+ forceReloadSdkSession?.();
reloadPreview();
trackStudioRazorSplit({ mode: "single", count: 1 });
showToast(`Split ${getTimelineElementLabel(element)} at ${splitTime.toFixed(2)}s`, "info");
@@ -229,6 +307,7 @@ export function useRazorSplit({
writeProjectFile,
domEditSaveTimestampRef,
reloadPreview,
+ forceReloadSdkSession,
isRecordingRef,
],
);
@@ -247,51 +326,42 @@ export function useRazorSplit({
const splittable = selectSplittableElements(elements, splitTime);
if (splittable.length === 0) return;
+ let originals = new Map<string, string>();
+ const finalSnapshots = new Map<string, { before: string; after: string }>();
try {
- const originals = new Map<string, string>();
- for (const el of splittable) {
- const path = el.sourceFile || activeCompPath || "index.html";
- if (!originals.has(path)) {
- originals.set(path, await readFileContent(pid, path));
- }
- }
-
- let splitCount = 0;
- const finalContent = new Map<string, string>();
-
- for (const element of splittable) {
- const result = await executeSplit(
- pid,
- element,
- splitTime,
- activeCompPath,
- writeProjectFile,
- );
- if (result.changed) {
- finalContent.set(result.targetPath, result.patchedContent);
- await writeProjectFile(result.targetPath, result.patchedContent);
- splitCount++;
- }
- }
-
+ originals = await readOriginalFiles(pid, splittable, activeCompPath);
+ const splitCount = await splitElementsAtTime(
+ pid,
+ splittable,
+ splitTime,
+ activeCompPath,
+ originals,
+ finalSnapshots,
+ writeProjectFile,
+ );
if (splitCount === 0) return;
domEditSaveTimestampRef.current = Date.now();
await recordEdit({
label: `Split ${splitCount} clips at ${splitTime.toFixed(2)}s`,
kind: "timeline",
- files: Object.fromEntries(
- [...finalContent].map(([path, after]) => [
- path,
- { before: originals.get(path) ?? "", after },
- ]),
- ),
+ files: Object.fromEntries(finalSnapshots),
});
+ // Resync the stale SDK doc after the batched server write (see the
+ // single-split path above for why this precedes the reload).
+ forceReloadSdkSession?.();
reloadPreview();
trackStudioRazorSplit({ mode: "all", count: splitCount });
showToast(`Split ${splitCount} clips at ${splitTime.toFixed(2)}s`, "info");
} catch (error) {
+ // Best-effort rollback — a failing restore write must not swallow the
+ // original error's toast, which is what tells the user the split failed.
+ try {
+ await restoreFilesToOriginal(originals, finalSnapshots.keys(), writeProjectFile);
+ } catch {
+ /* leave disk as-is; the original failure is reported below */
+ }
const message = error instanceof Error ? error.message : "Failed to split clips";
showToast(message, "error");
}
@@ -303,6 +373,7 @@ export function useRazorSplit({
writeProjectFile,
domEditSaveTimestampRef,
reloadPreview,
+ forceReloadSdkSession,
isRecordingRef,
],
);
diff --git a/packages/studio/src/hooks/useRenderClipContent.ts b/packages/studio/src/hooks/useRenderClipContent.ts
index dbe43dd99b..0e01c381fa 100644
--- a/packages/studio/src/hooks/useRenderClipContent.ts
+++ b/packages/studio/src/hooks/useRenderClipContent.ts
@@ -3,6 +3,8 @@ import { createElement } from "react";
import { CompositionThumbnail, VideoThumbnail } from "../player";
import type { TimelineElement } from "../player";
import { AudioWaveform } from "../player/components/AudioWaveform";
+import { ImageThumbnail } from "../player/components/ImageThumbnail";
+import { encodePreviewPath, resolveMediaPreviewUrl } from "../player/components/thumbnailUtils";
export function normalizeCompositionSrc(
compSrc: string,
@@ -51,8 +53,16 @@ function trimFractions(el: TimelineElement): { start?: number; end?: number } {
*/
function renderAudioClip(el: TimelineElement, pid: string, labelColor: string): ReactNode {
const srcRelative = resolvePreviewRelative(el.src, pid);
- const audioUrl = srcRelative ? `/api/projects/${pid}/preview/${srcRelative}` : (el.src ?? "");
- const waveformUrl = srcRelative ? `/api/projects/${pid}/waveform/${srcRelative}` : undefined;
+ // Encode each path segment (spaces, parens, U+202F, unicode) so the URL matches
+ // what the assets panel loads — a raw segment 404s. resolvePreviewRelative
+ // returns the DECODED path, so it must be re-encoded here.
+ const encodedRelative = srcRelative ? encodePreviewPath(srcRelative) : null;
+ const audioUrl = encodedRelative
+ ? `/api/projects/${pid}/preview/${encodedRelative}`
+ : (el.src ?? "");
+ const waveformUrl = encodedRelative
+ ? `/api/projects/${pid}/waveform/${encodedRelative}`
+ : undefined;
const { start, end } = trimFractions(el);
return createElement(AudioWaveform, {
audioUrl,
@@ -100,7 +110,7 @@ export function useRenderClipContent({
// instead of capturing the master at a time when the comp is fading in.
if (compSrc) {
return createElement(CompositionThumbnail, {
- previewUrl: `/api/projects/${pid}/preview/comp/${compSrc}`,
+ previewUrl: `/api/projects/${pid}/preview/comp/${encodePreviewPath(compSrc)}`,
label: "",
labelColor: style.label,
@@ -138,9 +148,17 @@ export function useRenderClipContent({
!/(backdrop|background|overlay|scrim|mask)/i.test(el.id);
if ((el.tag === "video" || el.tag === "img") && el.src) {
- const mediaSrc = el.src.startsWith("http")
- ? el.src
- : `/api/projects/${pid}/preview/${el.src}`;
+ const mediaSrc = resolveMediaPreviewUrl(el.src, pid);
+ // Still images can't be decoded by VideoThumbnail's <video> extractor
+ // (the error event fires and the shimmer never resolves) — render the
+ // image itself as the strip.
+ if (el.tag === "img") {
+ return createElement(ImageThumbnail, {
+ imageSrc: mediaSrc,
+ label: "",
+ labelColor: style.label,
+ });
+ }
return createElement(VideoThumbnail, {
videoSrc: mediaSrc,
label: "",
diff --git a/packages/studio/src/hooks/useStudioContextValue.ts b/packages/studio/src/hooks/useStudioContextValue.ts
index a8c5d0e0b8..460028bdfb 100644
--- a/packages/studio/src/hooks/useStudioContextValue.ts
+++ b/packages/studio/src/hooks/useStudioContextValue.ts
@@ -2,6 +2,8 @@ import { useCallback, useMemo, useRef, useState, type DragEvent } from "react";
import { STUDIO_INSPECTOR_PANELS_ENABLED } from "../components/editor/manualEditingAvailability";
import type { StudioContextValue } from "../contexts/StudioContext";
import type { RightInspectorPanes } from "../utils/studioHelpers";
+import type { TimelineFileDropHandler } from "./useTimelineEditingTypes";
+import { usePlayerStore } from "../player";
interface StudioContextInput {
projectId: string;
@@ -34,8 +36,6 @@ interface StudioContextInput {
waitForPendingDomEditSaves: () => Promise<void>;
handlePreviewIframeRef: (iframe: HTMLIFrameElement | null) => void;
refreshPreviewDocumentVersion: () => void;
- timelineVisible: boolean;
- toggleTimelineVisibility: () => void;
}
// fallow-ignore-next-line complexity
@@ -61,8 +61,6 @@ export function buildStudioContextValue(input: StudioContextInput): StudioContex
waitForPendingDomEditSaves: input.waitForPendingDomEditSaves,
handlePreviewIframeRef: input.handlePreviewIframeRef,
refreshPreviewDocumentVersion: input.refreshPreviewDocumentVersion,
- timelineVisible: input.timelineVisible,
- toggleTimelineVisibility: input.toggleTimelineVisibility,
};
}
@@ -108,7 +106,7 @@ export function useInspectorState(
}
// fallow-ignore-next-line complexity
-export function useDragOverlay(onImportFiles: (files: FileList) => void) {
+function useDragOverlay(onImportFiles: (files: FileList) => void) {
const [active, setActive] = useState(false);
const counterRef = useRef(0);
const onDragOver = useCallback((e: DragEvent) => {
@@ -137,3 +135,15 @@ export function useDragOverlay(onImportFiles: (files: FileList) => void) {
);
return { active, onDragOver, onDragEnter, onDragLeave, onDrop };
}
+
+/** Global OS file drop: imports and places at the playhead position. */
+export function useGlobalFileDrop(handleTimelineFileDrop: TimelineFileDropHandler) {
+ const onDrop = useCallback(
+ (files: FileList) => {
+ const start = usePlayerStore.getState().currentTime;
+ void handleTimelineFileDrop(Array.from(files), { start, track: 0 });
+ },
+ [handleTimelineFileDrop],
+ );
+ return useDragOverlay(onDrop);
+}
diff --git a/packages/studio/src/hooks/useStudioUrlState.ts b/packages/studio/src/hooks/useStudioUrlState.ts
index 7407c38e92..e67e6d346a 100644
--- a/packages/studio/src/hooks/useStudioUrlState.ts
+++ b/packages/studio/src/hooks/useStudioUrlState.ts
@@ -20,7 +20,6 @@ interface UseStudioUrlStateParams {
previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>;
rightPanelTab: RightPanelTab;
rightCollapsed: boolean;
- timelineVisible: boolean;
activeCompPathHydrated: boolean;
domEditSelection: DomEditSelection | null;
buildDomSelectionFromTarget: (
@@ -66,7 +65,6 @@ export function useStudioUrlState({
previewIframeRef,
rightPanelTab,
rightCollapsed,
- timelineVisible,
activeCompPathHydrated,
domEditSelection,
buildDomSelectionFromTarget,
@@ -91,12 +89,12 @@ export function useStudioUrlState({
currentTime: stableTimeRef.current,
rightPanelTab,
rightCollapsed,
- timelineVisible,
+ timelineVisible: null,
selection: hydratedSelectionRef.current
? toPersistedSelection(domEditSelection)
: pendingSelectionRef.current,
}),
- [activeCompPath, domEditSelection, rightCollapsed, rightPanelTab, timelineVisible],
+ [activeCompPath, domEditSelection, rightCollapsed, rightPanelTab],
);
// Resolve a URL selection to a live element and apply it. Shared by the initial
diff --git a/packages/studio/src/hooks/useTimelineEditing.test.tsx b/packages/studio/src/hooks/useTimelineEditing.test.tsx
index cd3f88fdc6..cb4466f88a 100644
--- a/packages/studio/src/hooks/useTimelineEditing.test.tsx
+++ b/packages/studio/src/hooks/useTimelineEditing.test.tsx
@@ -159,7 +159,7 @@ type TimelineRecordEdit = NonNullable<
function renderTimelineEditingHookWithLifecycle(input: {
timelineElements: TimelineElement[];
iframe: HTMLIFrameElement;
- commitPositionPatchToHtml: ReturnType<typeof vi.fn<(...args: unknown[]) => Promise<void>>>;
+ commitDomEditPatchBatches: ReturnType<typeof vi.fn<(...args: unknown[]) => Promise<void>>>;
}): {
move: ReturnType<typeof useTimelineEditing>["handleTimelineElementMove"];
unmount: () => void;
@@ -176,7 +176,7 @@ function renderTimelineEditingHookWithLifecycle(input: {
projectIdRef: { current: "p1" },
reloadPreview: vi.fn(),
clearDomSelection: vi.fn(),
- commitPositionPatchToHtml: input.commitPositionPatchToHtml,
+ commitDomEditPatchBatches: input.commitDomEditPatchBatches,
});
const commitRef = useRef(lifecycle.handleDomZIndexReorderCommit);
commitRef.current = lifecycle.handleDomZIndexReorderCommit;
@@ -481,11 +481,11 @@ 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 commitPositionPatchToHtml = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
+ const commitDomEditPatchBatches = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});
const { move, unmount } = renderTimelineEditingHookWithLifecycle({
timelineElements: [front, back],
iframe,
- commitPositionPatchToHtml,
+ commitDomEditPatchBatches,
});
await act(async () => {
@@ -501,8 +501,11 @@ describe("useTimelineEditing timeline z-index reorder", () => {
await flushAsyncWork();
});
- expect(commitPositionPatchToHtml).toHaveBeenCalled();
- expect(commitPositionPatchToHtml.mock.calls[0]![1]).toEqual([
+ expect(commitDomEditPatchBatches).toHaveBeenCalled();
+ const batch = commitDomEditPatchBatches.mock.calls[0]![0] as Array<{
+ patches: Array<{ operations: unknown[] }>;
+ }>;
+ expect(batch[0]?.patches[0]?.operations).toEqual([
{ type: "inline-style", property: "z-index", value: "2" },
{ type: "inline-style", property: "position", value: "relative" },
]);
@@ -522,14 +525,13 @@ describe("useTimelineEditing timeline z-index reorder", () => {
{ ...back, hasExplicitZIndex: false },
]);
const saveError = new Error("save failed");
- const commitPositionPatchToHtml = vi
+ const commitDomEditPatchBatches = vi
.fn<(...args: unknown[]) => Promise<void>>()
- .mockResolvedValueOnce(undefined)
.mockRejectedValueOnce(saveError);
const { move, unmount } = renderTimelineEditingHookWithLifecycle({
timelineElements: [front, back],
iframe,
- commitPositionPatchToHtml,
+ commitDomEditPatchBatches,
});
const doc = iframe.contentDocument;
if (!doc) throw new Error("Expected iframe document");
@@ -576,29 +578,24 @@ describe("useTimelineEditing timeline z-index reorder", () => {
unmount();
});
- it("waits for every lifecycle z-index save before resolving a reorder", async () => {
+ it("waits for the lifecycle z-index batch before resolving a reorder", async () => {
const iframe = createPreviewIframe([
{ id: "front", track: 0, style: "position: relative; z-index: 1" },
{ id: "back", track: 1, style: "position: relative; z-index: 0" },
]);
const front = timelineElement({ id: "front", track: 0, zIndex: 1 });
const back = timelineElement({ id: "back", track: 1, zIndex: 0 });
- let releaseFirst!: () => void;
- let releaseSecond!: () => void;
- const firstSave = new Promise<void>((resolve) => {
- releaseFirst = resolve;
+ let releaseBatch!: () => void;
+ const batchSave = new Promise<void>((resolve) => {
+ releaseBatch = resolve;
});
- const secondSave = new Promise<void>((resolve) => {
- releaseSecond = resolve;
- });
- const commitPositionPatchToHtml = vi
+ const commitDomEditPatchBatches = vi
.fn<(...args: unknown[]) => Promise<void>>()
- .mockReturnValueOnce(firstSave)
- .mockReturnValueOnce(secondSave);
+ .mockReturnValueOnce(batchSave);
const { move, unmount } = renderTimelineEditingHookWithLifecycle({
timelineElements: [front, back],
iframe,
- commitPositionPatchToHtml,
+ commitDomEditPatchBatches,
});
let settled = false;
@@ -621,17 +618,11 @@ describe("useTimelineEditing timeline z-index reorder", () => {
await flushAsyncWork();
});
- expect(commitPositionPatchToHtml).toHaveBeenCalledTimes(2);
- expect(settled).toBe(false);
-
- await act(async () => {
- releaseFirst();
- await flushAsyncWork();
- });
+ expect(commitDomEditPatchBatches).toHaveBeenCalledTimes(1);
expect(settled).toBe(false);
await act(async () => {
- releaseSecond();
+ releaseBatch();
await movePromise;
await flushAsyncWork();
});
diff --git a/packages/studio/src/hooks/useTimelineEditingTypes.ts b/packages/studio/src/hooks/useTimelineEditingTypes.ts
index b8cc2c7538..6689169a8d 100644
--- a/packages/studio/src/hooks/useTimelineEditingTypes.ts
+++ b/packages/studio/src/hooks/useTimelineEditingTypes.ts
@@ -22,6 +22,7 @@ export type TimelineZIndexReorderCommit = (
sourceFile: string;
key?: string;
}>,
+ coalesceKey?: string,
) => Promise<void>;
export interface UseTimelineEditingOptions {
@@ -43,3 +44,8 @@ export interface UseTimelineEditingOptions {
forceReloadSdkSession?: () => void;
handleDomZIndexReorderCommitRef?: MutableRefObject<TimelineZIndexReorderCommit | null>;
}
+
+export type TimelineFileDropHandler = (
+ files: File[],
+ placement?: { start: number; track: number },
+) => Promise<void>;
diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.ts
index 0ad9d365d7..7225b50d59 100644
--- a/packages/studio/src/hooks/useTimelineGroupEditing.ts
+++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts
@@ -21,6 +21,7 @@ import {
export interface TimelineGroupMoveChange {
element: TimelineElement;
start: number;
+ track?: number;
}
export interface TimelineGroupResizeChange {
@@ -152,9 +153,13 @@ export function useTimelineGroupEditing({
(changes: TimelineGroupMoveChange[], options?: TimelineGroupCommitOptions) => {
if (changes.length === 0) return Promise.resolve();
for (const change of changes) {
- patchIframeDomTiming(previewIframeRef.current, change.element, [
+ const attrs: Array<[string, string]> = [
["data-start", formatTimelineAttributeNumber(change.start)],
- ]);
+ ];
+ if (change.track != null) {
+ attrs.push(["data-track-index", formatTimelineAttributeNumber(change.track)]);
+ }
+ patchIframeDomTiming(previewIframeRef.current, change.element, attrs);
}
const maxEnd = Math.max(...changes.map((change) => change.start + change.element.duration));
@@ -169,7 +174,10 @@ export function useTimelineGroupEditing({
: null,
);
const canUseSdk =
- !needsExtension && sharedPath !== null && sdkChanges.every((change) => change !== null);
+ !needsExtension &&
+ sharedPath !== null &&
+ changes.every((change) => change.track == null) &&
+ sdkChanges.every((change) => change !== null);
if (canUseSdk) {
const handled = await sdkTimingBatchPersist(
sdkChanges.filter((change): change is NonNullable<typeof change> => change !== null),
@@ -194,7 +202,13 @@ export function useTimelineGroupEditing({
changes.map((change) => ({
element: change.element,
buildPatches: (original, target) =>
- buildTimelineMoveTimingPatch(original, target, change.start, change.element.duration),
+ buildTimelineMoveTimingPatch(
+ original,
+ target,
+ change.start,
+ change.element.duration,
+ change.track,
+ ),
})),
coalesceKey,
);
diff --git a/packages/studio/src/index.ts b/packages/studio/src/index.ts
index b9a08e6628..1da7407a66 100644
--- a/packages/studio/src/index.ts
+++ b/packages/studio/src/index.ts
@@ -1,5 +1,5 @@
// NLE Layout
-export { NLELayout } from "./components/nle/NLELayout";
+export { EditorShell } from "./components/EditorShell";
export { NLEPreview } from "./components/nle/NLEPreview";
export { CompositionBreadcrumb } from "./components/nle/CompositionBreadcrumb";
export type { CompositionLevel } from "./components/nle/CompositionBreadcrumb";
diff --git a/packages/studio/src/player/components/ImageThumbnail.test.tsx b/packages/studio/src/player/components/ImageThumbnail.test.tsx
new file mode 100644
index 0000000000..f1463a9b40
--- /dev/null
+++ b/packages/studio/src/player/components/ImageThumbnail.test.tsx
@@ -0,0 +1,173 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { ImageThumbnail } from "./ImageThumbnail";
+
+Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
+ configurable: true,
+ value: true,
+});
+
+// --- Observer stubs: fire "intersecting" immediately on observe ---
+class MockIntersectionObserver {
+ private cb: IntersectionObserverCallback;
+ constructor(cb: IntersectionObserverCallback) {
+ this.cb = cb;
+ }
+ observe() {
+ this.cb(
+ [{ isIntersecting: true } as IntersectionObserverEntry],
+ this as unknown as IntersectionObserver,
+ );
+ }
+ disconnect() {}
+ unobserve() {}
+ takeRecords(): IntersectionObserverEntry[] {
+ return [];
+ }
+}
+
+class MockResizeObserver {
+ observe() {}
+ disconnect() {}
+ unobserve() {}
+}
+
+// --- Image stub: captures instances so tests fire load/error deterministically ---
+class MockImage {
+ static instances: MockImage[] = [];
+ onload: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ naturalWidth = 0;
+ naturalHeight = 0;
+ src = "";
+ constructor() {
+ MockImage.instances.push(this);
+ }
+}
+
+const originalIO = globalThis.IntersectionObserver;
+const originalRO = globalThis.ResizeObserver;
+const originalImage = globalThis.Image;
+
+let host: HTMLDivElement;
+let root: Root | null = null;
+
+beforeEach(() => {
+ globalThis.IntersectionObserver =
+ MockIntersectionObserver as unknown as typeof IntersectionObserver;
+ globalThis.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver;
+ globalThis.Image = MockImage as unknown as typeof Image;
+ MockImage.instances = [];
+ host = document.createElement("div");
+ document.body.append(host);
+});
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ globalThis.IntersectionObserver = originalIO;
+ globalThis.ResizeObserver = originalRO;
+ globalThis.Image = originalImage;
+ document.body.innerHTML = "";
+});
+
+function render(props: { imageSrc: string; label?: string; labelColor?: string }) {
+ root = createRoot(host);
+ act(() => {
+ root!.render(
+ <ImageThumbnail
+ imageSrc={props.imageSrc}
+ label={props.label ?? ""}
+ labelColor={props.labelColor ?? "#fff"}
+ />,
+ );
+ });
+}
+
+function lastProbe(): MockImage {
+ const probe = MockImage.instances.at(-1);
+ expect(probe).toBeDefined();
+ return probe!;
+}
+
+/** Assert at least one tile rendered and the first tile serves `expectedSrc`. */
+function expectFirstTileSrc(expectedSrc: string): void {
+ const imgs = [...host.querySelectorAll("img")];
+ expect(imgs.length).toBeGreaterThanOrEqual(1);
+ expect(imgs[0].getAttribute("src")).toBe(expectedSrc);
+}
+
+describe("ImageThumbnail", () => {
+ it("shows the loading shimmer before the image resolves", () => {
+ render({ imageSrc: "/api/projects/p/preview/assets/pic.png" });
+ expect(host.querySelector(".animate-pulse")).not.toBeNull();
+ expect(host.querySelectorAll("img").length).toBe(0);
+ });
+
+ it("probes the resolved src and renders repeated object-cover tiles on load", () => {
+ render({ imageSrc: "/api/projects/p/preview/assets/pic.png" });
+ const probe = lastProbe();
+ expect(probe.src).toBe("/api/projects/p/preview/assets/pic.png");
+
+ act(() => {
+ probe.naturalWidth = 1920;
+ probe.naturalHeight = 1080;
+ probe.onload?.();
+ });
+
+ const imgs = [...host.querySelectorAll("img")];
+ expect(imgs.length).toBeGreaterThanOrEqual(1);
+ for (const img of imgs) {
+ expect(img.getAttribute("src")).toBe("/api/projects/p/preview/assets/pic.png");
+ expect(img.className).toContain("object-cover");
+ }
+ expect(host.querySelector(".animate-pulse")).toBeNull();
+ });
+
+ it("drops the shimmer and renders no tiles when a raster image fails to load", () => {
+ render({ imageSrc: "/api/projects/p/preview/assets/missing.png" });
+ act(() => lastProbe().onerror?.());
+ expect(host.querySelectorAll("img").length).toBe(0);
+ expect(host.querySelector(".animate-pulse")).toBeNull();
+ });
+
+ it("renders tiles at 16:9 when an SVG has no intrinsic dimensions (naturalWidth=0)", () => {
+ render({ imageSrc: "/api/projects/p/preview/assets/logo.svg" });
+ const probe = lastProbe();
+
+ act(() => {
+ // naturalWidth stays 0 — SVG with no width/height attribute
+ probe.onload?.();
+ });
+
+ expectFirstTileSrc("/api/projects/p/preview/assets/logo.svg");
+ expect(host.querySelector(".animate-pulse")).toBeNull();
+ });
+
+ it("renders SVG tiles at 16:9 fallback even when the probe fires onerror", () => {
+ // Some browser/sandbox environments fire onerror for SVGs even though the
+ // <img> element itself can render the file — we must not blank the strip.
+ render({ imageSrc: "/api/projects/p/preview/assets/icon.svg" });
+
+ act(() => lastProbe().onerror?.());
+
+ expectFirstTileSrc("/api/projects/p/preview/assets/icon.svg");
+ expect(host.querySelector(".animate-pulse")).toBeNull();
+ });
+
+ it("renders the label above the strip when provided", () => {
+ render({ imageSrc: "/x.png", label: "hero", labelColor: "#abc" });
+ act(() => {
+ const probe = lastProbe();
+ probe.naturalWidth = 100;
+ probe.naturalHeight = 100;
+ probe.onload?.();
+ });
+ const label = [...host.querySelectorAll("span")].find((s) => s.textContent === "hero");
+ expect(label).toBeDefined();
+ expect(label!.closest(".z-10")).not.toBeNull();
+ });
+});
diff --git a/packages/studio/src/player/components/ImageThumbnail.tsx b/packages/studio/src/player/components/ImageThumbnail.tsx
new file mode 100644
index 0000000000..33914ae2c1
--- /dev/null
+++ b/packages/studio/src/player/components/ImageThumbnail.tsx
@@ -0,0 +1,160 @@
+import { memo, useRef, useState, useCallback, useEffect } from "react";
+import { useMountEffect } from "../../hooks/useMountEffect";
+import { computeThumbnailStrip } from "./thumbnailUtils";
+
+interface ImageThumbnailProps {
+ imageSrc: string;
+ label: string;
+ labelColor: string;
+}
+
+/**
+ * Renders a film-strip of a still image for a timeline clip. The image is a
+ * fixed-width tile (sized by its natural aspect ratio) repeated to fill the
+ * clip width — matching VideoThumbnail's visual pattern. Loading is lazy
+ * (IntersectionObserver) with the same shimmer fallback while decoding.
+ */
+export const ImageThumbnail = memo(function ImageThumbnail({
+ imageSrc,
+ label,
+ labelColor,
+}: ImageThumbnailProps) {
+ const [containerWidth, setContainerWidth] = useState(0);
+ const [visible, setVisible] = useState(false);
+ const [status, setStatus] = useState<"loading" | "loaded" | "error">("loading");
+ const [aspect, setAspect] = useState(16 / 9);
+ const ioRef = useRef<IntersectionObserver | null>(null);
+ const roRef = useRef<ResizeObserver | null>(null);
+
+ const setContainerRef = useCallback((el: HTMLDivElement | null) => {
+ ioRef.current?.disconnect();
+ roRef.current?.disconnect();
+ if (!el) return;
+
+ const measured = el.parentElement?.clientWidth || el.clientWidth;
+ setContainerWidth(measured);
+
+ ioRef.current = new IntersectionObserver(
+ ([entry]) => {
+ if (entry.isIntersecting) {
+ setVisible(true);
+ ioRef.current?.disconnect();
+ }
+ },
+ { rootMargin: "200px" },
+ );
+ // fallow-ignore-next-line code-duplication
+ ioRef.current.observe(el);
+
+ const target = el.parentElement || el;
+ roRef.current = new ResizeObserver(([entry]) => {
+ setContainerWidth(entry.contentRect.width);
+ });
+ roRef.current.observe(target);
+ }, []);
+
+ useMountEffect(() => () => {
+ ioRef.current?.disconnect();
+ roRef.current?.disconnect();
+ });
+
+ // Probe the image once visible — measures the natural aspect ratio so the
+ // tile width matches, and flips to the error state (plain clip background)
+ // if the src can't load. The browser cache makes the tile <img>s free.
+ //
+ // SVG handling: SVGs without intrinsic width/height report naturalWidth=0 on
+ // load (treat as success with the 16:9 default aspect) and may fire onerror
+ // in some environments even though the file is valid and can be displayed —
+ // fall back to loaded-at-16:9 rather than hiding the strip entirely.
+ // eslint-disable-next-line no-restricted-syntax
+ useEffect(() => {
+ if (!visible) return;
+ let cancelled = false;
+ setStatus("loading");
+
+ const isSvg = /\.svg($|\?)/i.test(imageSrc);
+
+ const probe = new Image();
+ probe.onload = () => {
+ if (cancelled) return;
+ if (probe.naturalWidth > 0 && probe.naturalHeight > 0) {
+ setAspect(probe.naturalWidth / probe.naturalHeight);
+ }
+ // naturalWidth===0 (e.g. SVG with no intrinsic dimensions) falls through
+ // to "loaded" with the default 16:9 aspect already set in state.
+ setStatus("loaded");
+ };
+ probe.onerror = () => {
+ if (cancelled) return;
+ // SVGs can fail the probe in certain browser/sandbox environments even
+ // though the <img> tiles themselves render fine (different security
+ // context). Show the strip at the 16:9 fallback rather than blanking.
+ if (isSvg) {
+ setStatus("loaded");
+ } else {
+ setStatus("error");
+ }
+ };
+ probe.src = imageSrc;
+
+ return () => {
+ cancelled = true;
+ probe.onload = null;
+ probe.onerror = null;
+ probe.src = "";
+ };
+ }, [visible, imageSrc]);
+
+ const { frameW, frameCount } = computeThumbnailStrip(containerWidth, aspect);
+
+ return (
+ <div ref={setContainerRef} className="absolute inset-0 overflow-hidden">
+ {visible && status === "loaded" && (
+ <div className="absolute inset-0 flex">
+ {Array.from({ length: frameCount }).map((_, i) => (
+ <div
+ key={i}
+ className="flex-shrink-0 h-full relative overflow-hidden bg-neutral-900"
+ style={{ width: frameW }}
+ >
+ <img
+ src={imageSrc}
+ alt=""
+ draggable={false}
+ loading="lazy"
+ className="absolute inset-0 w-full h-full object-cover"
+ />
+ </div>
+ ))}
+ </div>
+ )}
+
+ {visible && status === "loading" && (
+ <div
+ className="absolute inset-0 animate-pulse"
+ style={{
+ background:
+ "linear-gradient(90deg, rgba(255,255,255,0.02) 0%, rgba(255,255,255,0.05) 50%, rgba(255,255,255,0.02) 100%)",
+ }}
+ />
+ )}
+
+ {label && (
+ <div
+ className="absolute bottom-0 left-0 right-0 z-10 px-1.5 pb-0.5 pt-3"
+ style={{
+ background:
+ "linear-gradient(to top, rgba(0,0,0,0.85) 0%, rgba(0,0,0,0.4) 60%, transparent 100%)",
+ }}
+ >
+ <span
+ className="text-[9px] font-semibold truncate block leading-tight"
+ style={{ color: labelColor, textShadow: "0 1px 2px rgba(0,0,0,0.9)" }}
+ >
+ {label}
+ </span>
+ </div>
+ )}
+ </div>
+ );
+});
diff --git a/packages/studio/src/player/components/PlayheadIndicator.tsx b/packages/studio/src/player/components/PlayheadIndicator.tsx
index 85a0457913..d2b8a7f690 100644
--- a/packages/studio/src/player/components/PlayheadIndicator.tsx
+++ b/packages/studio/src/player/components/PlayheadIndicator.tsx
@@ -2,20 +2,44 @@
/**
* Shared playhead visual used by TimelineCanvas (real playhead) and
* TimelineEditorNotice (animated illustration).
+ *
+ * The vertical line + glow span the full track height; the grab-handle HEAD is
+ * `position: sticky; top: 0` so it pins to the top of the (vertically) scrolling
+ * track area — the ruler is sticky too, so the head stays visible and grabbable
+ * no matter how far the tracks are scrolled. The head is OUTLINE-only at rest and
+ * FILLED while the playhead is actively held/scrubbed (`scrubbing`).
*/
interface PlayheadIndicatorProps {
/** CSS color, defaults to the HF accent variable */
color?: string;
/** Glow shadow color, defaults to translucent accent */
glowColor?: string;
+ /** Whether the playhead is being actively scrubbed — fills the head. */
+ scrubbing?: boolean;
+ /**
+ * When false, the head chip is rendered in normal flow (top:1) instead of the
+ * sticky pin — used by the static illustration where there is no scroll area.
+ */
+ stickyHead?: boolean;
}
export function PlayheadIndicator({
color = "var(--hf-accent, #3CE6AC)",
glowColor = "rgba(60,230,172,0.14)",
+ scrubbing = false,
+ stickyHead = true,
}: PlayheadIndicatorProps) {
+ // Head chip dimensions — used to compute the centering offset and the
+ // point where the vertical line starts (so it begins at the head's bottom
+ // edge rather than running through the hollow diamond center).
+ const HEAD_W = 9;
+ const HEAD_H = 9;
+ // marginTop(1) + HEAD_H = where the line should start.
+ const HEAD_TOTAL_H = 1 + HEAD_H;
+
return (
<>
+ {/* Glow — spans full height, centered on the line. */}
<div
aria-hidden="true"
className="absolute top-0 bottom-0"
@@ -26,23 +50,44 @@ export function PlayheadIndicator({
background: `radial-gradient(closest-side, ${glowColor}, transparent)`,
}}
/>
+ {/* Vertical line — starts at the bottom edge of the head chip so nothing
+ shows through the hollow diamond center. */}
<div
- className="absolute top-0 bottom-0"
+ className="absolute bottom-0"
style={{
left: "50%",
+ top: HEAD_TOTAL_H,
width: 1,
marginLeft: -0.5,
background: color,
boxShadow: `0 0 6px ${glowColor}`,
}}
/>
- <div className="absolute" style={{ left: "50%", top: 1, transform: "translateX(-50%)" }}>
+ {/* Head chip — sticky so it pins to the ruler while tracks scroll.
+ Centering logic: wrapper width = HEAD_W (chip forces it). The line sits
+ at wrapper.left + HEAD_W/2 (left:"50%" of wrapper). The sticky element's
+ natural flow position is wrapper.left; so placing it there with no
+ horizontal translate puts its LEFT edge at wrapper.left and its CENTER
+ at wrapper.left + HEAD_W/2 — exactly on the line. */}
+ <div
+ className={stickyHead ? "sticky" : "absolute"}
+ style={{
+ left: 0,
+ top: stickyHead ? 0 : 1,
+ // Zero height keeps it from covering rows (sticky strip trick).
+ height: stickyHead ? 0 : undefined,
+ }}
+ >
<div
style={{
- width: 9,
- height: 9,
+ width: HEAD_W,
+ height: HEAD_H,
borderRadius: 2,
- background: color,
+ marginTop: 1,
+ // Outline-only at rest, filled while scrubbing.
+ background: scrubbing ? color : "transparent",
+ border: `1.5px solid ${color}`,
+ boxSizing: "border-box",
boxShadow: `0 1px 3px rgba(0,0,0,0.55), 0 0 5px ${glowColor}`,
transform: "rotate(45deg)",
}}
diff --git a/packages/studio/src/player/components/Timeline.test.ts b/packages/studio/src/player/components/Timeline.test.ts
index f6f5258391..600e054250 100644
--- a/packages/studio/src/player/components/Timeline.test.ts
+++ b/packages/studio/src/player/components/Timeline.test.ts
@@ -18,7 +18,14 @@ import {
shouldHandleTimelineDeleteKey,
shouldAutoScrollTimeline,
} from "./Timeline";
-import { RULER_H, TRACK_H } from "./timelineLayout";
+import {
+ GUTTER,
+ MIN_TIMELINE_EXTENT_S,
+ RULER_H,
+ TRACK_H,
+ getTimelineDisplayContentWidth,
+ getTimelineFitPps,
+} from "./timelineLayout";
import { formatTime } from "../lib/time";
import { usePlayerStore } from "../store/playerStore";
import { TimelineEditProvider } from "../../contexts/TimelineEditContext";
@@ -323,30 +330,30 @@ describe("generateTicks", () => {
});
describe("formatTime", () => {
- it("formats 0 seconds as 0:00", () => {
- expect(formatTime(0)).toBe("0:00");
+ it("formats 0 seconds as 00:00", () => {
+ expect(formatTime(0)).toBe("00:00");
});
// fallow-ignore-next-line code-duplication
it("formats seconds below a minute", () => {
- expect(formatTime(5)).toBe("0:05");
- expect(formatTime(30)).toBe("0:30");
- expect(formatTime(59)).toBe("0:59");
+ expect(formatTime(5)).toBe("00:05");
+ expect(formatTime(30)).toBe("00:30");
+ expect(formatTime(59)).toBe("00:59");
});
it("formats exactly one minute", () => {
- expect(formatTime(60)).toBe("1:00");
+ expect(formatTime(60)).toBe("01:00");
});
it("formats minutes and seconds", () => {
- expect(formatTime(90)).toBe("1:30");
- expect(formatTime(125)).toBe("2:05");
+ expect(formatTime(90)).toBe("01:30");
+ expect(formatTime(125)).toBe("02:05");
});
it("floors fractional seconds", () => {
- expect(formatTime(5.7)).toBe("0:05");
- expect(formatTime(59.9)).toBe("0:59");
- expect(formatTime(90.5)).toBe("1:30");
+ expect(formatTime(5.7)).toBe("00:05");
+ expect(formatTime(59.9)).toBe("00:59");
+ expect(formatTime(90.5)).toBe("01:30");
});
it("handles large values", () => {
@@ -354,16 +361,16 @@ describe("formatTime", () => {
expect(formatTime(3661)).toBe("61:01");
});
- it("zero-pads seconds to two digits", () => {
- expect(formatTime(1)).toBe("0:01");
- expect(formatTime(9)).toBe("0:09");
- expect(formatTime(61)).toBe("1:01");
+ it("zero-pads minutes and seconds to two digits", () => {
+ expect(formatTime(1)).toBe("00:01");
+ expect(formatTime(9)).toBe("00:09");
+ expect(formatTime(61)).toBe("01:01");
});
});
describe("formatTimelineTickLabel", () => {
it("uses minute-second labels for normal timeline intervals", () => {
- expect(formatTimelineTickLabel(90, 180, 5)).toBe("1:30");
+ expect(formatTimelineTickLabel(90, 180, 5)).toBe("01:30");
});
it("uses hour labels for long timelines", () => {
@@ -371,7 +378,7 @@ describe("formatTimelineTickLabel", () => {
});
it("shows subsecond labels when the major ruler interval is below one second", () => {
- expect(formatTimelineTickLabel(1.5, 3, 0.5)).toBe("0:01.5");
+ expect(formatTimelineTickLabel(1.5, 3, 0.5)).toBe("00:01.5");
});
});
@@ -390,6 +397,80 @@ describe("shouldAutoScrollTimeline", () => {
});
});
+describe("getTimelineFitPps (min 60s extent)", () => {
+ const viewport = 632; // usable width = 632 - GUTTER - 2 = 598
+
+ 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.
+ const pps = getTimelineFitPps(viewport, 10);
+ expect(pps).toBeCloseTo((viewport - GUTTER - 2) / MIN_TIMELINE_EXTENT_S);
+ expect(10 * pps).toBeCloseTo((viewport - GUTTER - 2) / 6);
+ });
+
+ it("keeps filling the viewport with the composition when it is 60s or longer", () => {
+ expect(getTimelineFitPps(viewport, 60)).toBeCloseTo((viewport - GUTTER - 2) / 60);
+ expect(getTimelineFitPps(viewport, 120)).toBeCloseTo((viewport - GUTTER - 2) / 120);
+ });
+
+ 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(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,
+ );
+ expect(getTimelineFitPps(viewport, Number.NaN)).toBeCloseTo(
+ (viewport - GUTTER - 2) / MIN_TIMELINE_EXTENT_S,
+ );
+ });
+});
+
+describe("getTimelineDisplayContentWidth", () => {
+ it("always spans at least MIN_TIMELINE_EXTENT_S seconds of content", () => {
+ // 10s of content at 20 pps = 200px; the floor keeps 60s (1200px) rendered.
+ expect(
+ getTimelineDisplayContentWidth({ trackContentWidth: 200, viewportWidth: 400, pps: 20 }),
+ ).toBe(MIN_TIMELINE_EXTENT_S * 20);
+ });
+
+ 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);
+ });
+
+ it("tracks a drag ghost past every other bound (drag-to-extend)", () => {
+ expect(
+ getTimelineDisplayContentWidth({
+ trackContentWidth: 500,
+ viewportWidth: 400,
+ pps: 5,
+ dragGhostEndPx: 5000,
+ }),
+ ).toBe(5000);
+ });
+
+ it("tracks a resize (trim) ghost past every other bound (trim-to-extend)", () => {
+ expect(
+ getTimelineDisplayContentWidth({
+ trackContentWidth: 500,
+ viewportWidth: 400,
+ pps: 5,
+ resizeGhostEndPx: 4200,
+ }),
+ ).toBe(4200);
+ });
+
+ it("keeps long content authoritative", () => {
+ expect(
+ getTimelineDisplayContentWidth({ trackContentWidth: 9000, viewportWidth: 400, pps: 50 }),
+ ).toBe(9000);
+ });
+});
+
describe("getTimelineScrollLeftForZoomTransition", () => {
it("resets horizontal scroll when switching from manual zoom back to fit", () => {
expect(getTimelineScrollLeftForZoomTransition("manual", "fit", 480)).toBe(0);
@@ -524,7 +605,9 @@ describe("resolveTimelineAssetDrop", () => {
trackOrder: [0, 3, 7],
},
432,
- 310,
+ // 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,
),
).toEqual({ start: 3, track: 3 });
});
diff --git a/packages/studio/src/player/components/Timeline.tsx b/packages/studio/src/player/components/Timeline.tsx
index 7557b22345..e9568f131f 100644
--- a/packages/studio/src/player/components/Timeline.tsx
+++ b/packages/studio/src/player/components/Timeline.tsx
@@ -5,39 +5,31 @@ import { remapBeatAnalysisToComposition } from "../../utils/beatEditActions";
import { usePlayerStore, type TimelineElement } from "../store/playerStore";
import { useExpandedTimelineElements } from "../hooks/useExpandedTimelineElements";
import { useMountEffect } from "../../hooks/useMountEffect";
-import { EditPopover } from "./EditModal";
import { defaultTimelineTheme } from "./timelineTheme";
import { useTimelineRangeSelection } from "./useTimelineRangeSelection";
-import { useTimelineMarqueeSelection } from "./useTimelineMarqueeSelection";
import { useTimelinePlayhead } from "./useTimelinePlayhead";
import { useTimelineActiveClips } from "./useTimelineActiveClips";
import { type TrackVisualStyle, getTrackStyle } from "./timelineIcons";
-import { getTimelinePixelsPerSecond } from "./timelineZoom";
import { useTimelineZoom } from "./useTimelineZoom";
import { useTimelineAssetDrop } from "./timelineDragDrop";
import { TimelineEmptyState } from "./TimelineEmptyState";
import { TimelineCanvas } from "./TimelineCanvas";
-import {
- KeyframeDiamondContextMenu,
- type KeyframeDiamondContextMenuState,
-} from "./KeyframeDiamondContextMenu";
+import { type KeyframeDiamondContextMenuState } from "./KeyframeDiamondContextMenu";
import { useTimelineClipDrag } from "./useTimelineClipDrag";
-import { useTimelineKeyframeHandlers } from "./useTimelineKeyframeHandlers";
-import { ClipContextMenu } from "./ClipContextMenu";
-import { TimelineShortcutHint } from "./TimelineShortcutHint";
-import { buildStackingTimelineLayers, insertPreviewTrackOrder } from "./timelineTrackOrder";
-import { getTimelineLayerGroupHeaderTotalHeight } from "./TimelineLayerGroupHeader";
+import { TimelineOverlays } from "./TimelineOverlays";
+import { useTimelineEditPinning } from "./useTimelineEditPinning";
+import { useTimelineStackingSync } from "./useTimelineStackingSync";
+import { useTimelineGeometry } from "./useTimelineGeometry";
import {
GUTTER,
- generateVisibleTicks,
+ generateTicks,
getTimelineCanvasHeight,
shouldShowTimelineShortcutHint,
- computeTimelineBasisDuration,
- computeTimelineEffectiveDuration,
} from "./timelineLayout";
import { useResolvedTimelineEditCallbacks } from "./useResolvedTimelineEditCallbacks";
import type { TimelineProps } from "./TimelineTypes";
+// Re-export pure utilities so existing imports from "./Timeline" still resolve.
export {
generateTicks,
formatTimelineTickLabel,
@@ -62,7 +54,9 @@ export const Timeline = memo(function Timeline({
onBlockDrop,
onDeleteElement: _onDeleteElement,
onMoveElement: onMoveElementOverride,
+ onMoveElements: onMoveElementsOverride,
onResizeElement: onResizeElementOverride,
+ onResizeElements: onResizeElementsOverride,
onBlockedEditAttempt: onBlockedEditAttemptOverride,
onSplitElement: onSplitElementOverride,
onSelectElement,
@@ -70,11 +64,9 @@ export const Timeline = memo(function Timeline({
}: TimelineProps = {}) {
const {
onMoveElement,
- onResizeElement,
onMoveElements,
+ onResizeElement,
onResizeElements,
- onPreviewMoveElements,
- onPreviewResizeElements,
onBlockedEditAttempt,
onSplitElement,
onRazorSplitAll,
@@ -85,7 +77,9 @@ export const Timeline = memo(function Timeline({
onMoveKeyframe,
} = useResolvedTimelineEditCallbacks({
onMoveElement: onMoveElementOverride,
+ onMoveElements: onMoveElementsOverride,
onResizeElement: onResizeElementOverride,
+ onResizeElements: onResizeElementsOverride,
onBlockedEditAttempt: onBlockedEditAttemptOverride,
onSplitElement: onSplitElementOverride,
});
@@ -103,17 +97,20 @@ export const Timeline = memo(function Timeline({
const duration = usePlayerStore((s) => s.duration);
const timelineReady = usePlayerStore((s) => s.timelineReady);
const selectedElementId = usePlayerStore((s) => s.selectedElementId);
+ const selectedElementIds = usePlayerStore((s) => s.selectedElementIds);
const setSelectedElementId = usePlayerStore((s) => s.setSelectedElementId);
const currentTime = usePlayerStore((s) => s.currentTime);
const { zoomMode, manualZoomPercent, setZoomMode, setManualZoomPercent } = useTimelineZoom();
const playheadRef = useRef<HTMLDivElement>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const activeTool = usePlayerStore((s) => s.activeTool);
const [hoveredClip, setHoveredClip] = useState<string | null>(null);
const isDragging = useRef(false);
const [shiftHeld, setShiftHeld] = useState(false);
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);
@@ -139,6 +136,7 @@ export const Timeline = memo(function Timeline({
const [viewportWidth, setViewportWidth] = useState(0);
const roRef = useRef<ResizeObserver | null>(null);
const shortcutHintRafRef = useRef(0);
+
const syncShortcutHintVisibility = useCallback(() => {
const scroll = scrollRef.current;
setShowShortcutHint(
@@ -154,6 +152,16 @@ export const Timeline = memo(function Timeline({
});
}, [syncShortcutHintVisibility]);
+ const setContainerRef = useCallback((el: HTMLDivElement | null) => {
+ containerRef.current = el;
+ }, []);
+
+ // Last horizontal scroll offset, tracked so it can be RESTORED across the
+ // post-edit iframe reload: an edit re-derives elements (and may shrink the
+ // content width), which the browser clamps into a scroll jump. Paired with the
+ // pinned zoom (which keeps pps constant so the pixel offset stays meaningful),
+ // restoring this keeps the user parked at the same spot after any edit.
+ const lastScrollLeftRef = useRef(0);
const setScrollRef = useCallback(
(el: HTMLDivElement | null) => {
if (roRef.current) {
@@ -180,31 +188,70 @@ export const Timeline = memo(function Timeline({
if (shortcutHintRafRef.current) cancelAnimationFrame(shortcutHintRafRef.current);
});
- const tracks = useMemo(
- () => buildStackingTimelineLayers(expandedElements).rows,
- [expandedElements],
- );
+ 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);
+ 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<string, TrackVisualStyle>();
- for (const layer of tracks) {
- map.set(layer.id, getTrackStyle(layer.elements[0]?.tag ?? ""));
+ 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((layer) => layer.id), [tracks]);
+ const trackOrder = useMemo(() => tracks.map(([trackNum]) => trackNum), [tracks]);
const trackOrderRef = useRef(trackOrder);
trackOrderRef.current = trackOrder;
- const timelineLayersRef = useRef(tracks);
- timelineLayersRef.current = tracks;
const expandedElementsRef = useRef(expandedElements);
expandedElementsRef.current = expandedElements;
const ppsRef = useRef(100);
- const durationRef = useRef(Number.isFinite(duration) ? duration : 0);
+ 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.
+ const fitPpsRef = useRef(100);
- const setRangeSelectionRef = useRef<((sel: null) => void) | null>(null);
+ const {
+ pinZoomBeforeEdit,
+ setRangeSelectionRef,
+ pinnedOnMoveElement,
+ pinnedOnMoveElements,
+ pinnedOnResizeElement,
+ pinnedOnResizeElements,
+ pinnedOnFileDrop,
+ pinnedOnAssetDrop,
+ pinnedOnBlockDrop,
+ } = useTimelineEditPinning({
+ ppsRef,
+ fitPpsRef,
+ onMoveElement,
+ onMoveElements,
+ onResizeElement,
+ onResizeElements,
+ onFileDrop,
+ onAssetDrop,
+ onBlockDrop,
+ });
+
+ const { readClipZIndex, applyStackingPatches, zSyncEnabled } = useTimelineStackingSync({
+ expandedElementsRef,
+ });
const {
draggedClip,
@@ -217,67 +264,39 @@ export const Timeline = memo(function Timeline({
} = useTimelineClipDrag({
scrollRef,
ppsRef,
+ durationRef,
trackOrderRef,
- timelineLayersRef,
- timelineElementsRef: expandedElementsRef,
- onMoveElement,
- onResizeElement,
- onMoveElements,
- onResizeElements,
- onPreviewMoveElements,
- onPreviewResizeElements,
+ onMoveElement: pinnedOnMoveElement,
+ onMoveElements: pinnedOnMoveElements,
+ onResizeElement: pinnedOnResizeElement,
+ onResizeElements: pinnedOnResizeElements,
onBlockedEditAttempt,
setShowPopover,
setRangeSelectionRef,
+ readZIndex: zSyncEnabled ? readClipZIndex : undefined,
+ onStackingPatches: zSyncEnabled ? applyStackingPatches : undefined,
});
- const basisDuration = useMemo(
- () =>
- computeTimelineBasisDuration(
- duration,
- rawElements.map((el) => el.start + el.duration),
- ),
- [rawElements, duration],
- );
- const effectiveDuration = useMemo(
- () =>
- computeTimelineEffectiveDuration(basisDuration, [
- draggedClip?.started ? draggedClip.previewStart + draggedClip.element.duration : null,
- resizingClip?.started ? resizingClip.previewStart + resizingClip.previewDuration : null,
- ]),
- [basisDuration, draggedClip, resizingClip],
- );
- durationRef.current = effectiveDuration;
+ const { isDragOver, handleAssetDragOver, handleAssetDrop, clearDropPreview } =
+ useTimelineAssetDrop({
+ scrollRef,
+ ppsRef,
+ durationRef,
+ trackOrderRef,
+ onFileDrop: pinnedOnFileDrop,
+ onAssetDrop: pinnedOnAssetDrop,
+ onBlockDrop: pinnedOnBlockDrop,
+ });
const displayTrackOrder = useMemo(() => {
- if (
- !draggedClip?.started ||
- trackOrder.length === 0 ||
- trackOrder.includes(draggedClip.previewLayerId)
- )
- return trackOrder;
- return insertPreviewTrackOrder(
- trackOrder,
- draggedClip.previewLayerId,
- draggedClip.previewLayerIndex,
- );
+ if (!draggedClip?.started || trackOrder.includes(draggedClip.previewTrack)) return trackOrder;
+ return [...trackOrder, draggedClip.previewTrack].sort((a, b) => a - b);
}, [draggedClip, trackOrder]);
- const totalH =
- getTimelineCanvasHeight(displayTrackOrder.length) +
- getTimelineLayerGroupHeaderTotalHeight(displayTrackOrder, tracks);
+ const totalH = getTimelineCanvasHeight(displayTrackOrder.length);
const keyframeCache = usePlayerStore((s) => s.keyframeCache);
const selectedKeyframes = usePlayerStore((s) => s.selectedKeyframes);
const toggleSelectedKeyframe = usePlayerStore((s) => s.toggleSelectedKeyframe);
- const keyframeHandlers = useTimelineKeyframeHandlers({
- expandedElements,
- keyframeCache,
- onSelectElement,
- onSeek,
- setSelectedElementId,
- setKfContextMenu,
- toggleSelectedKeyframe,
- });
const selectedElement = useMemo(
() =>
@@ -287,26 +306,28 @@ export const Timeline = memo(function Timeline({
const selectedElementRef = useRef<TimelineElement | null>(selectedElement);
selectedElementRef.current = selectedElement;
- const fitPps =
- viewportWidth > GUTTER && basisDuration > 0
- ? (viewportWidth - GUTTER - 2) / basisDuration
- : 100;
- const pps = getTimelinePixelsPerSecond(fitPps, zoomMode, manualZoomPercent);
- ppsRef.current = pps;
- const trackContentWidth = Math.max(0, effectiveDuration * pps);
- const clipStateVersion = useMemo(
- () =>
- expandedElements
- .map((el) => `${el.key ?? el.id}:${el.start}:${el.duration}:${el.track}`)
- .join("|"),
- [expandedElements],
- );
- const zoomModeRef = useRef(zoomMode);
- zoomModeRef.current = zoomMode;
- const manualZoomPercentRef = useRef(manualZoomPercent);
- manualZoomPercentRef.current = manualZoomPercent;
- const fitPpsRef = useRef(fitPps);
- fitPpsRef.current = fitPps;
+ const {
+ pps,
+ fitPps,
+ displayContentWidth,
+ displayDuration,
+ clipStateVersion,
+ zoomModeRef,
+ manualZoomPercentRef,
+ } = useTimelineGeometry({
+ viewportWidth,
+ effectiveDuration,
+ zoomMode,
+ manualZoomPercent,
+ ppsRef,
+ fitPpsRef,
+ draggedClip,
+ resizingClip,
+ expandedElements,
+ isDragging,
+ scrollRef,
+ lastScrollLeftRef,
+ });
const { seekFromX, autoScrollDuringDrag, dragScrollRaf } = useTimelinePlayhead({
playheadRef,
@@ -339,6 +360,8 @@ export const Timeline = memo(function Timeline({
rangeSelection,
setRangeSelection,
shiftClickClipRef,
+ marqueeRect,
+ isScrubbing,
handlePointerDown,
handlePointerMove,
handlePointerUp,
@@ -353,28 +376,12 @@ export const Timeline = memo(function Timeline({
dragScrollRaf,
isDragging,
setShowPopover,
- });
- const {
- marqueeRect,
- handlePointerDown: handleMarqueePointerDown,
- handlePointerMove: handleMarqueePointerMove,
- handlePointerUp: handleMarqueePointerUp,
- } = useTimelineMarqueeSelection({
- scrollRef,
- ppsRef,
+ elementsRef: expandedElementsRef,
trackOrderRef,
- timelineLayersRef,
- disabled: activeTool === "razor",
- setShowPopover,
- setRangeSelectionRef,
- seekFromX,
+ onSelectElement,
});
+ // Wire setRangeSelection into the stable ref consumed by useTimelineClipDrag
setRangeSelectionRef.current = setRangeSelection;
- // Pointer-up and lost-capture end a gesture identically (marquee-claims-first).
- const releasePointer = (event: Parameters<typeof handleMarqueePointerUp>[0]) => {
- if (handleMarqueePointerUp(event)) return;
- handlePointerUp();
- };
const prevSelectedRef = useRef(selectedElementRef.current);
// eslint-disable-next-line no-restricted-syntax, react-hooks/exhaustive-deps
@@ -389,8 +396,8 @@ export const Timeline = memo(function Timeline({
});
const { major, minor } = useMemo(
- () => generateVisibleTicks(effectiveDuration, pps, viewportWidth, GUTTER),
- [effectiveDuration, pps, viewportWidth],
+ () => generateTicks(displayDuration, pps),
+ [displayDuration, pps],
);
const majorTickInterval = major.length >= 2 ? major[1] - major[0] : effectiveDuration;
@@ -416,24 +423,13 @@ export const Timeline = memo(function Timeline({
[resizingClip],
);
- const { isDragOver, setIsDragOver, handleAssetDragOver, handleAssetDrop } = useTimelineAssetDrop({
- scrollRef,
- ppsRef,
- durationRef,
- trackOrderRef,
- timelineLayersRef,
- onFileDrop,
- onAssetDrop,
- onBlockDrop,
- });
-
if (!timelineReady || expandedElements.length === 0) {
return (
<TimelineEmptyState
isDragOver={isDragOver}
onFileDrop={!!onFileDrop}
onDragOver={handleAssetDragOver}
- onDragLeave={() => setIsDragOver(false)}
+ onDragLeave={() => clearDropPreview()}
onDrop={handleAssetDrop}
/>
);
@@ -441,6 +437,7 @@ export const Timeline = memo(function Timeline({
return (
<div
+ ref={setContainerRef}
aria-label="Timeline"
className={`relative border-t select-none h-full overflow-hidden ${activeTool === "razor" ? "cursor-crosshair" : shiftHeld ? "cursor-crosshair" : "cursor-default"}`}
onMouseMove={(e) => {
@@ -460,8 +457,12 @@ export const Timeline = memo(function Timeline({
ref={setScrollRef}
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;
+ }}
onDragOver={handleAssetDragOver}
- onDragLeave={() => setIsDragOver(false)}
+ onDragLeave={() => clearDropPreview()}
onDrop={handleAssetDrop}
onPointerDown={(e) => {
if (activeTool === "razor" && e.shiftKey && e.button === 0 && scrollRef.current) {
@@ -471,21 +472,17 @@ export const Timeline = memo(function Timeline({
onRazorSplitAll?.(splitTime);
return;
}
- if (handleMarqueePointerDown(e)) return;
handlePointerDown(e);
}}
- onPointerMove={(e) => {
- if (handleMarqueePointerMove(e)) return;
- handlePointerMove(e);
- }}
- onPointerUp={releasePointer}
- onLostPointerCapture={releasePointer}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ onLostPointerCapture={handlePointerUp}
>
<TimelineCanvas
major={major}
minor={minor}
pps={pps}
- trackContentWidth={trackContentWidth}
+ trackContentWidth={displayContentWidth}
totalH={totalH}
effectiveDuration={effectiveDuration}
majorTickInterval={majorTickInterval}
@@ -497,9 +494,11 @@ export const Timeline = memo(function Timeline({
tracks={tracks}
trackStyles={trackStyles}
selectedElementId={selectedElementId}
+ selectedElementIds={selectedElementIds}
hoveredClip={hoveredClip}
draggedClip={draggedClip}
resizingClip={resizingClip}
+ isScrubbing={isScrubbing}
blockedClipRef={blockedClipRef}
suppressClickRef={suppressClickRef}
scrollRef={scrollRef}
@@ -522,10 +521,41 @@ export const Timeline = memo(function Timeline({
selectedKeyframes={selectedKeyframes}
currentTime={currentTime}
beatAnalysis={adjustedBeatAnalysis}
- onClickKeyframe={keyframeHandlers.onClickKeyframe}
- onShiftClickKeyframe={keyframeHandlers.onShiftClickKeyframe}
+ onClickKeyframe={(el, pct) => {
+ usePlayerStore.getState().clearSelectedKeyframes();
+ const elKey = el.key ?? el.id;
+ setSelectedElementId(elKey);
+ onSelectElement?.(el);
+ // Visually select the clicked diamond (matches shift-click / motion-path
+ // selection); cleared above so this single-selects it.
+ toggleSelectedKeyframe(`${elKey}:${pct}`);
+ const absTime = el.start + (pct / 100) * el.duration;
+ onSeek?.(absTime);
+ const kfData = keyframeCache?.get(elKey);
+ const kf = kfData?.keyframes.find((k) => Math.abs(k.percentage - pct) < 0.5);
+ usePlayerStore.getState().setActiveKeyframePct(kf?.tweenPercentage ?? null);
+ }}
+ onShiftClickKeyframe={(elId, pct) => {
+ toggleSelectedKeyframe(`${elId}:${pct}`);
+ }}
onMoveKeyframe={onMoveKeyframe}
- onContextMenuKeyframe={keyframeHandlers.onContextMenuKeyframe}
+ onContextMenuKeyframe={(e, elId, pct) => {
+ const el = expandedElements.find((x) => (x.key ?? x.id) === elId);
+ if (el) {
+ setSelectedElementId(elId);
+ onSelectElement?.(el);
+ }
+ const kfData = keyframeCache.get(elId);
+ const kf = kfData?.keyframes.find((k) => Math.abs(k.percentage - pct) < 0.2);
+ setKfContextMenu({
+ x: e.clientX + 4,
+ y: e.clientY + 2,
+ elementId: elId,
+ percentage: pct,
+ tweenPercentage: kf?.tweenPercentage,
+ currentEase: kf?.ease ?? kfData?.ease,
+ });
+ }}
onContextMenuClip={(e, el) => {
e.preventDefault();
setSelectedElementId(el.key ?? el.id);
@@ -544,57 +574,27 @@ export const Timeline = memo(function Timeline({
/>
)}
</div>
-
- {showShortcutHint && !showPopover && !rangeSelection && (
- <TimelineShortcutHint theme={theme} />
- )}
-
- {showPopover && rangeSelection && (
- <EditPopover
- rangeStart={rangeSelection.start}
- rangeEnd={rangeSelection.end}
- anchorX={rangeSelection.anchorX}
- anchorY={rangeSelection.anchorY}
- onClose={() => {
- setShowPopover(false);
- setRangeSelection(null);
- }}
- />
- )}
-
- {kfContextMenu && (
- <KeyframeDiamondContextMenu
- state={kfContextMenu}
- onClose={() => setKfContextMenu(null)}
- onDelete={(elId, pct) => onDeleteKeyframe?.(elId, pct)}
- onDeleteAll={(elId) => onDeleteAllKeyframes?.(elId)}
- onChangeEase={(elId, pct, ease) => onChangeKeyframeEase?.(elId, pct, ease)}
- onMoveToPlayhead={
- onMoveKeyframeToPlayhead
- ? (elId, pct) => onMoveKeyframeToPlayhead(elId, pct)
- : undefined
- }
- onCopyProperties={(elId, pct) => {
- const kfData = keyframeCache.get(elId);
- const kf = kfData?.keyframes.find((k) => k.percentage === pct);
- if (kf) {
- void navigator.clipboard.writeText(JSON.stringify(kf.properties, null, 2));
- }
- }}
- />
- )}
-
- {clipContextMenu && (
- <ClipContextMenu
- x={clipContextMenu.x}
- y={clipContextMenu.y}
- element={clipContextMenu.element}
- currentTime={currentTime}
- onClose={() => setClipContextMenu(null)}
- onSplit={(el, time) => onSplitElement?.(el, time)}
- onDelete={(el) => _onDeleteElement?.(el)}
- />
- )}
+ <TimelineOverlays
+ theme={theme}
+ showShortcutHint={showShortcutHint}
+ showPopover={showPopover}
+ rangeSelection={rangeSelection}
+ setShowPopover={setShowPopover}
+ setRangeSelection={setRangeSelection}
+ kfContextMenu={kfContextMenu}
+ setKfContextMenu={setKfContextMenu}
+ onDeleteKeyframe={onDeleteKeyframe}
+ onDeleteAllKeyframes={onDeleteAllKeyframes}
+ onChangeKeyframeEase={onChangeKeyframeEase}
+ onMoveKeyframeToPlayhead={onMoveKeyframeToPlayhead}
+ keyframeCache={keyframeCache}
+ clipContextMenu={clipContextMenu}
+ setClipContextMenu={setClipContextMenu}
+ currentTime={currentTime}
+ onSplitElement={onSplitElement}
+ pinZoomBeforeEdit={pinZoomBeforeEdit}
+ onDeleteElement={_onDeleteElement}
+ />
</div>
);
});
diff --git a/packages/studio/src/player/components/TimelineCanvas.tsx b/packages/studio/src/player/components/TimelineCanvas.tsx
index 55bb299bf2..d4ae3b75f4 100644
--- a/packages/studio/src/player/components/TimelineCanvas.tsx
+++ b/packages/studio/src/player/components/TimelineCanvas.tsx
@@ -1,173 +1,46 @@
-import { Fragment, memo, type ReactNode } from "react";
-import { BeatStrip, BeatBackgroundLines } from "./BeatStrip";
-import { TimelineClip } from "./TimelineClip";
-import { TimelineClipDiamonds } from "./TimelineClipDiamonds";
+import { memo } from "react";
import { TimelineRuler } from "./TimelineRuler";
-import type { MusicBeatAnalysis } from "@hyperframes/core/beats";
import { PlayheadIndicator } from "./PlayheadIndicator";
+import { getTimelineEditCapabilities, type TimelineRangeSelection } from "./timelineEditing";
+import { getRenderedTimelineElement } from "./timelineTheme";
import {
- getTimelineEditCapabilities,
- resolveBlockedTimelineEditIntent,
- type TimelineRangeSelection,
-} from "./timelineEditing";
-import { getRenderedTimelineElement, type TimelineTheme } from "./timelineTheme";
-import { GUTTER, TRACK_H, CLIP_Y, CLIP_HANDLE_W } from "./timelineLayout";
-import {
- usePlayerStore,
- type TimelineElement,
- type KeyframeCacheEntry,
-} from "../store/playerStore";
-import type { DraggedClipState, ResizingClipState, BlockedClipState } from "./useTimelineClipDrag";
-import type { TrackVisualStyle } from "./timelineIcons";
-import type { StackingTimelineLayer, TimelineLayerId } from "./timelineTrackOrder";
-import { STUDIO_KEYFRAMES_ENABLED } from "../../components/editor/manualEditingAvailability";
-import { SPLIT_BOUNDARY_EPSILON_S } from "../../utils/timelineElementSplit";
+ GUTTER,
+ TRACK_H,
+ RULER_H,
+ CLIP_Y,
+ TRACKS_TOP_PAD,
+ TRACKS_BOTTOM_PAD,
+ getTimelineRowTop,
+} from "./timelineLayout";
+import { usePlayerStore } from "../store/playerStore";
+import type { ResizingClipState } from "./useTimelineClipDrag";
+import { type MultiDragPreviewInput } from "./timelineMultiDragPreview";
import { useTimelineEditContextOptional } from "../../contexts/TimelineEditContext";
-import { isMusicTrack } from "../../utils/timelineInspector";
-import { TimelineLayerGutter } from "./TimelineLayerGutter";
-import {
- shouldShowTimelineLayerGroupHeader,
- TimelineLayerGroupHeader,
-} from "./TimelineLayerGroupHeader";
-import { resolveTimelineDropIndicator } from "./timelineDropIndicator";
-import { TimelineDropInsertionLine } from "./TimelineDropInsertionLine";
-import { TimelineDragGhost } from "./TimelineDragGhost";
-import { TimelineSelectionOverlays } from "./TimelineSelectionOverlays";
-import type { TimelineMarqueeOverlayRect } from "./useTimelineMarqueeSelection";
-
-function ClipLintDot({ element }: { element: TimelineElement }) {
- const lint = usePlayerStore((s) => s.lintFindingsByElement.get(element.key ?? element.id));
- if (!lint || lint.count === 0) return null;
- return (
- <span
- className="absolute w-1.5 h-1.5 rounded-full bg-amber-400"
- style={{ top: 7, right: 7 }}
- title={lint.messages.join("\n")}
- />
- );
-}
+import type { Rect } from "../../utils/marqueeGeometry";
+import { TimelineClip } from "./TimelineClip";
+import { TimelineLanes, type TimelineLaneBaseProps } from "./TimelineLanes";
+import { renderClipChildren } from "./timelineClipChildren";
-interface TimelineCanvasProps {
+interface TimelineCanvasProps extends TimelineLaneBaseProps {
major: number[];
minor: number[];
- pps: number;
- trackContentWidth: number;
totalH: number;
effectiveDuration: number;
majorTickInterval: number;
rangeSelection: TimelineRangeSelection | null;
- marqueeRect: TimelineMarqueeOverlayRect | null;
- theme: TimelineTheme;
- displayTrackOrder: TimelineLayerId[];
- trackOrder: TimelineLayerId[];
- tracks: StackingTimelineLayer[];
- trackStyles: Map<TimelineLayerId, TrackVisualStyle>;
- selectedElementId: string | null;
- hoveredClip: string | null;
- draggedClip: DraggedClipState | null;
+ /** Live rubber-band multi-select rectangle (canvas coordinates), or null. */
+ marqueeRect: Rect | null;
resizingClip: ResizingClipState | null;
- blockedClipRef: React.RefObject<BlockedClipState | null>;
- suppressClickRef: React.RefObject<boolean>;
- scrollRef: React.RefObject<HTMLDivElement | null>;
- renderClipContent?: (
- element: TimelineElement,
- style: { clip: string; label: string },
- ) => ReactNode;
- renderClipOverlay?: (element: TimelineElement) => ReactNode;
+ /** Playhead is being actively scrubbed — fills the grab-handle head. */
+ isScrubbing: boolean;
playheadRef: React.RefObject<HTMLDivElement | null>;
- onDrillDown?: (element: TimelineElement) => void;
- onSelectElement?: (element: TimelineElement | null) => void;
- setHoveredClip: (key: string | null) => void;
- setShowPopover: (v: boolean) => void;
- setRangeSelection: (v: null) => void;
- setResizingClip: (v: ResizingClipState | null) => void;
- setDraggedClip: (v: DraggedClipState | null) => void;
- setSelectedElementId: (id: string | null) => void;
- syncClipDragAutoScroll: (x: number, y: number) => void;
- shiftClickClipRef: React.RefObject<{
- element: TimelineElement;
- anchorX: number;
- anchorY: number;
- } | null>;
- getPreviewElement: (element: TimelineElement) => TimelineElement;
- getTrackStyle: (tag: string) => TrackVisualStyle;
- keyframeCache?: Map<string, KeyframeCacheEntry>;
- selectedKeyframes: Set<string>;
- currentTime: number;
- onClickKeyframe?: (element: TimelineElement, percentage: number) => void;
- onShiftClickKeyframe?: (elementId: string, percentage: number) => void;
- onContextMenuKeyframe?: (e: React.MouseEvent, elementId: string, percentage: number) => void;
- onMoveKeyframe?: (
- elementId: string,
- fromClipPercentage: number,
- toClipPercentage: number,
- ) => void;
- onContextMenuClip?: (e: React.MouseEvent, element: TimelineElement) => void;
- beatAnalysis?: MusicBeatAnalysis | null;
}
-export const TimelineCanvas = memo(function TimelineCanvas({
- major,
- minor,
- pps,
- trackContentWidth,
- totalH,
- effectiveDuration,
- majorTickInterval,
- rangeSelection,
- marqueeRect,
- theme,
- displayTrackOrder,
- trackOrder,
- tracks,
- trackStyles,
- selectedElementId,
- hoveredClip,
- draggedClip,
- resizingClip,
- blockedClipRef,
- suppressClickRef,
- scrollRef,
- renderClipContent,
- renderClipOverlay,
- playheadRef,
- onDrillDown,
- onSelectElement,
- setHoveredClip,
- setShowPopover,
- setRangeSelection,
- setResizingClip,
- setDraggedClip,
- setSelectedElementId,
- syncClipDragAutoScroll,
- shiftClickClipRef,
- getPreviewElement,
- getTrackStyle,
- keyframeCache,
- selectedKeyframes,
- currentTime,
- onClickKeyframe,
- onShiftClickKeyframe,
- onContextMenuKeyframe,
- onMoveKeyframe,
- onContextMenuClip,
- beatAnalysis,
-}: TimelineCanvasProps) {
- const {
- onResizeElement,
- onMoveElement,
- onToggleTrackHidden,
- onToggleElementHidden,
- onRazorSplit,
- onRazorSplitAll,
- } = useTimelineEditContextOptional();
+export const TimelineCanvas = memo(function TimelineCanvas(props: TimelineCanvasProps) {
+ const { draggedClip, scrollRef, selectedElementIds, displayTrackOrder } = props;
+ const { onResizeElement, onMoveElement, onToggleTrackHidden, onRazorSplit, onRazorSplitAll } =
+ useTimelineEditContextOptional();
const beatDragging = usePlayerStore((s) => s.beatDragging);
- const selectedElementIds = usePlayerStore((s) => s.selectedElementIds);
- const activeSnapGuideTime = draggedClip?.started
- ? (draggedClip.snapBeatTime ?? draggedClip.snapGuideTime)
- : resizingClip?.started
- ? resizingClip.snapGuideTime
- : null;
const draggedElement = draggedClip?.element ?? null;
const activeDraggedElement =
draggedClip?.started === true && draggedElement
@@ -178,6 +51,28 @@ export const TimelineCanvas = memo(function TimelineCanvas({
previewTrack: draggedClip.previewTrack,
})
: null;
+ // The drag ghost follows the cursor freely (both axes) — CapCut-style. The
+ // "magnetic" affordance is a highlight on the destination lane (draggedRowIndex),
+ // which flips at the MAGNETIC_TRACK_THRESHOLD point; the clip drops into it.
+ const draggedRowIndex =
+ draggedClip?.started === true ? displayTrackOrder.indexOf(draggedClip.previewTrack) : -1;
+ // Live multi-selection drag: while a selected clip is dragged, ALL selected
+ // clips move together as one rigid formation. The GRABBED clip is the free
+ // ghost below; its co-selected "passengers" slide by the SAME group-clamped
+ // delta (cheap translateX, no re-layout) — the delta is derived from the
+ // grabbed clip's ALREADY-clamped previewStart, so the whole formation stops at
+ // the wall together and never deforms. Matches what the commit will do — see
+ // timelineMultiDragPreview + commit.
+ const multiDragPreview: MultiDragPreviewInput | null =
+ draggedClip?.started === true && draggedElement
+ ? {
+ dragStarted: true,
+ draggedKey: draggedElement.key ?? draggedElement.id,
+ draggedOriginStart: draggedElement.start,
+ draggedPreviewStart: draggedClip.previewStart,
+ selectedKeys: selectedElementIds,
+ }
+ : null;
const activeDraggedPosition =
draggedClip?.started === true && activeDraggedElement && scrollRef.current
? {
@@ -194,388 +89,179 @@ export const TimelineCanvas = memo(function TimelineCanvas({
}
: null;
- const renderClipChildren = (element: TimelineElement, clipStyle: TrackVisualStyle) => (
- <>
- {renderClipOverlay?.(element)}
- {!renderClipContent && <ClipLintDot element={element} />}
- {renderClipContent && (
- <div className="absolute inset-0 overflow-hidden">
- {renderClipContent(element, clipStyle)}
- </div>
- )}
- </>
- );
- const activeDropPlacement =
- draggedClip?.started === true ? (draggedClip.previewStackingReorder?.placement ?? null) : null;
-
return (
- // minWidth:100% makes the lanes and ruler fill the panel when the composition
- // is narrower than the viewport (zoomed out); content stays in time coords.
<div
className="relative"
- style={{ height: totalH, width: GUTTER + trackContentWidth, minWidth: "100%" }}
+ style={{ height: props.totalH, width: GUTTER + props.trackContentWidth }}
>
<TimelineRuler
- major={major}
- minor={minor}
- pps={pps}
- trackContentWidth={trackContentWidth}
- totalH={totalH}
- effectiveDuration={effectiveDuration}
- majorTickInterval={majorTickInterval}
- theme={theme}
- beatAnalysis={beatAnalysis}
+ major={props.major}
+ minor={props.minor}
+ pps={props.pps}
+ trackContentWidth={props.trackContentWidth}
+ totalH={props.totalH}
+ effectiveDuration={props.effectiveDuration}
+ majorTickInterval={props.majorTickInterval}
+ theme={props.theme}
+ beatAnalysis={props.beatAnalysis}
/>
- {
- // fallow-ignore-next-line complexity
- displayTrackOrder.map((layerId, rowIndex) => {
- const layer = tracks.find((item) => item.id === layerId) ?? null;
- const previousLayerId = displayTrackOrder[rowIndex - 1];
- const previousLayer = previousLayerId
- ? (tracks.find((item) => item.id === previousLayerId) ?? null)
- : null;
- const els = layer?.elements ?? [];
- const ts = trackStyles.get(layerId) ?? getTrackStyle("");
- const isAudioLayer = layer?.kind === "audio";
- const isFirstAudioLayer = isAudioLayer && previousLayer?.kind !== "audio";
- const isPendingTrack =
- draggedClip?.started === true && !trackOrder.includes(layerId) && els.length === 0;
- const baseRowBackground = rowIndex % 2 === 0 ? theme.rowBackground : "#0D0E12";
- const dropIndicator = resolveTimelineDropIndicator({
- placement: activeDropPlacement,
- layerId,
- layerOrder: displayTrackOrder,
- });
- const rowBackground =
- dropIndicator?.kind === "onto"
- ? theme.clipBackgroundActive
- : isAudioLayer
- ? `linear-gradient(90deg, ${theme.gutterBackground} 0, ${baseRowBackground} 74px)`
- : baseRowBackground;
- const showGroupHeader = shouldShowTimelineLayerGroupHeader(
- layer?.contextKey ?? "",
- previousLayer?.contextKey ?? "",
- );
- const rowTrack = layer?.placementTrack ?? els[0]?.track ?? 0;
- // The beat-dot strip occupies the top of this track's lane (active track,
- // or the music track when nothing is selected). When shown, keyframe
- // diamonds shrink + drop to the bottom half so they don't collide with it.
- const beatStripOnTrack =
- (beatAnalysis?.beatTimes?.length ?? 0) >= 2 &&
- (selectedElementId
- ? els.some((e) => (e.key ?? e.id) === selectedElementId)
- : els.some(isMusicTrack));
- const isTrackHidden = els.length > 0 && els.every((element) => element.hidden === true);
- return (
- <Fragment key={layerId}>
- {showGroupHeader && layer && (
- <TimelineLayerGroupHeader
- contextKey={layer.contextKey}
- trackContentWidth={trackContentWidth}
- theme={theme}
- accentColor={ts.accent}
- />
- )}
- <div
- className="relative flex"
- style={{
- height: TRACK_H,
- background: rowBackground,
- borderTop: isFirstAudioLayer ? `2px solid ${theme.rulerBorder}` : undefined,
- borderBottom: `1px solid ${theme.rowBorder}`,
- boxShadow:
- dropIndicator?.kind === "onto" ? `inset 0 0 0 1px ${ts.accent}` : undefined,
- }}
- >
- <TimelineLayerGutter
- isAudio={isAudioLayer}
- isTrackHidden={isTrackHidden}
- rowTrack={rowTrack}
- theme={theme}
- onToggleHidden={() => {
- if (onToggleElementHidden && els.length > 0) {
- for (const element of els) {
- void onToggleElementHidden(element.key ?? element.id, !isTrackHidden);
- }
- return;
- }
- void onToggleTrackHidden?.(rowTrack, !isTrackHidden);
- }}
- />
- <div
- style={{
- width: trackContentWidth,
- opacity: isTrackHidden ? 0.35 : 1,
- transition: "opacity 120ms ease",
- }}
- className="relative"
- >
- {layer?.contextKey && (
- <span
- className="absolute bottom-0 top-0 pointer-events-none"
- style={{
- left: 0,
- width: 2,
- background: ts.accent,
- opacity: 0.45,
- zIndex: 2,
- }}
- />
- )}
- {dropIndicator?.kind === "line" && (
- <TimelineDropInsertionLine edge={dropIndicator.edge} accentColor={ts.accent} />
- )}
- {/* Faint beat lines in every track's background (behind the clips);
- the active snap target is highlighted. */}
- <BeatBackgroundLines
- beatTimes={beatAnalysis?.beatTimes}
- beatStrengths={beatAnalysis?.beatStrengths}
- pps={pps}
- highlightTime={activeSnapGuideTime}
- />
- {/* Beat dots on the active track (the one holding the selection),
- falling back to the music track when nothing is selected. */}
- {beatStripOnTrack && (
- <BeatStrip
- beatTimes={beatAnalysis?.beatTimes}
- beatStrengths={beatAnalysis?.beatStrengths}
- pps={pps}
- />
- )}
- {isPendingTrack && (
- <div
- className="absolute inset-0 flex items-center"
- style={{
- paddingLeft: 16,
- color: ts.label,
- fontSize: 11,
- letterSpacing: 0,
- textTransform: "uppercase",
- opacity: 0.5,
- }}
- >
- New track
- </div>
- )}
- {
- // fallow-ignore-next-line complexity
- els.map((el) => {
- const clipStyle = getTrackStyle(el.tag);
- const elementKey = el.key ?? el.id;
- const capabilities = getTimelineEditCapabilities(el);
- const isSelected = selectedElementIds.has(elementKey);
- const isComposition = !!el.compositionSrc;
- // elementKey (el.key ?? el.id) is already unique per clip; do NOT
- // fold in the map index, or a splice/reorder remounts every clip
- // at/after the change (DOM flash, drag interruption).
- const clipKey = elementKey;
- const isDraggingClip =
- draggedClip?.started === true &&
- (draggedElement?.key ?? draggedElement?.id) === elementKey;
- if (isDraggingClip) return null;
- const previewElement = getPreviewElement(el);
- return (
- <TimelineClip
- key={clipKey}
- onContextMenu={(e: React.MouseEvent) => {
- e.preventDefault();
- onContextMenuClip?.(e, el);
- }}
- el={previewElement}
- pps={pps}
- clipY={CLIP_Y}
- isSelected={isSelected}
- isHovered={hoveredClip === clipKey}
- isDragging={false}
- hasCustomContent={!!renderClipContent}
- capabilities={capabilities}
- theme={theme}
- isComposition={isComposition}
- onHoverStart={() => setHoveredClip(clipKey)}
- onHoverEnd={() => setHoveredClip(null)}
- onResizeStart={(edge, e) => {
- if (e.button !== 0 || e.shiftKey || !onResizeElement) return;
- if (edge === "start" && !capabilities.canTrimStart) return;
- if (edge === "end" && !capabilities.canTrimEnd) return;
- e.stopPropagation();
- blockedClipRef.current = null;
- setShowPopover(false);
- setRangeSelection(null);
- setResizingClip({
- element: el,
- edge,
- originClientX: e.clientX,
- previewStart: el.start,
- previewDuration: el.duration,
- previewPlaybackStart: el.playbackStart,
- snapGuideTime: null,
- snapGuideKind: null,
- started: false,
- });
- }}
- onPointerDown={
- // fallow-ignore-next-line complexity
- (e) => {
- if (e.button !== 0) return;
- if (usePlayerStore.getState().activeTool === "razor") return;
- if (e.shiftKey) {
- shiftClickClipRef.current = {
- element: el,
- anchorX: e.clientX,
- anchorY: e.clientY,
- };
- return;
- }
- const target = e.currentTarget as HTMLElement;
- const rect = target.getBoundingClientRect();
- const blockedIntent = resolveBlockedTimelineEditIntent({
- width: rect.width,
- offsetX: e.clientX - rect.left,
- handleWidth: CLIP_HANDLE_W,
- capabilities,
- });
- if (
- blockedIntent &&
- ((blockedIntent === "move" && onMoveElement) ||
- (blockedIntent !== "move" && onResizeElement))
- ) {
- blockedClipRef.current = {
- element: el,
- intent: blockedIntent,
- originClientX: e.clientX,
- originClientY: e.clientY,
- started: false,
- };
- return;
- }
- if (!onMoveElement || !capabilities.canMove) return;
- blockedClipRef.current = null;
- setShowPopover(false);
- setRangeSelection(null);
- setDraggedClip({
- element: el,
- originClientX: e.clientX,
- originClientY: e.clientY,
- originScrollLeft: scrollRef.current?.scrollLeft ?? 0,
- originScrollTop: scrollRef.current?.scrollTop ?? 0,
- pointerClientX: e.clientX,
- pointerClientY: e.clientY,
- pointerOffsetX: e.clientX - rect.left,
- pointerOffsetY: e.clientY - rect.top,
- previewStart: el.start,
- previewTrack: el.track,
- previewLayerId: layerId,
- previewLayerIndex: rowIndex,
- previewStackingReorder: null,
- snapBeatTime: null,
- snapGuideTime: null,
- snapGuideKind: null,
- started: false,
- });
- syncClipDragAutoScroll(e.clientX, e.clientY);
- }
- }
- onClick={(e) => {
- e.stopPropagation();
- if (suppressClickRef.current) return;
- const { activeTool } = usePlayerStore.getState();
- if (activeTool === "razor" && onRazorSplit) {
- const clipRect = (
- e.currentTarget as HTMLElement
- ).getBoundingClientRect();
- const clickOffsetX = e.clientX - clipRect.left;
- const splitTime = previewElement.start + clickOffsetX / pps;
- const clampedTime = Math.max(
- previewElement.start + SPLIT_BOUNDARY_EPSILON_S,
- Math.min(
- previewElement.start +
- previewElement.duration -
- SPLIT_BOUNDARY_EPSILON_S,
- splitTime,
- ),
- );
- if (e.shiftKey && onRazorSplitAll) {
- onRazorSplitAll(clampedTime);
- } else {
- onRazorSplit(el, clampedTime);
- }
- return;
- }
- const nextElement = isSelected ? null : el;
- setSelectedElementId(nextElement ? elementKey : null);
- onSelectElement?.(nextElement);
- }}
- onDoubleClick={(e) => {
- e.stopPropagation();
- if (suppressClickRef.current) return;
- if (isComposition && onDrillDown) onDrillDown(el);
- }}
- >
- {renderClipChildren(previewElement, clipStyle)}
- {STUDIO_KEYFRAMES_ENABLED && keyframeCache?.get(elementKey) && (
- <TimelineClipDiamonds
- keyframesData={keyframeCache.get(elementKey)!}
- clipWidthPx={Math.max(previewElement.duration * pps, 4)}
- clipHeightPx={TRACK_H - 2 * CLIP_Y}
- beatsActive={beatStripOnTrack}
- beatTimes={beatAnalysis?.beatTimes}
- clipStart={previewElement.start}
- clipDurationSeconds={previewElement.duration}
- pixelsPerSecond={pps}
- accentColor={clipStyle.accent}
- isSelected={isSelected}
- currentPercentage={
- previewElement.duration > 0
- ? ((currentTime - previewElement.start) /
- previewElement.duration) *
- 100
- : 0
- }
- elementId={elementKey}
- selectedKeyframes={selectedKeyframes}
- onClickKeyframe={(pct) => onClickKeyframe?.(previewElement, pct)}
- onShiftClickKeyframe={onShiftClickKeyframe}
- onContextMenuKeyframe={onContextMenuKeyframe}
- onMoveKeyframe={onMoveKeyframe}
- suppressClickRef={suppressClickRef}
- />
- )}
- </TimelineClip>
- );
- })
- }
- </div>
- </div>
- </Fragment>
- );
- })
- }
+ {/* Breathing room between the sticky ruler and the first track lane — the
+ top half of the CapCut-style padding (see TRACKS_TOP_PAD). */}
+ <div aria-hidden="true" style={{ height: TRACKS_TOP_PAD }} />
+
+ <TimelineLanes
+ {...props}
+ draggedElement={draggedElement}
+ multiDragPreview={multiDragPreview}
+ onToggleTrackHidden={onToggleTrackHidden}
+ onResizeElement={onResizeElement}
+ onMoveElement={onMoveElement}
+ onRazorSplit={onRazorSplit}
+ onRazorSplitAll={onRazorSplitAll}
+ />
+
+ {/* Breathing room below the last track lane (~1.5 track heights) — a real
+ scrollable surface, so a clip can be dragged into the void to create a
+ new bottom track comfortably (see TRACKS_BOTTOM_PAD / getTimelineCanvasHeight). */}
+ <div aria-hidden="true" style={{ height: TRACKS_BOTTOM_PAD }} />
+
+ {/* 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 && (
+ <div
+ className="absolute pointer-events-none"
+ style={{
+ top: getTimelineRowTop(draggedRowIndex) + CLIP_Y,
+ left: GUTTER + 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)",
+ background: "rgba(60,230,172,0.12)",
+ borderRadius: 4,
+ zIndex: 30,
+ }}
+ />
+ )}
+
+ {/* Insertion line — a new track will be inserted at this boundary on drop.
+ Shown while the pointer is near a lane boundary (insert mode). */}
+ {draggedClip?.started && draggedClip.insertRow != null && (
+ <div
+ className="absolute pointer-events-none"
+ style={{
+ top: getTimelineRowTop(draggedClip.insertRow) - 0.5,
+ left: GUTTER,
+ width: props.trackContentWidth,
+ height: 1,
+ background: "#3CE6AC",
+ boxShadow: "0 0 3px rgba(60,230,172,0.5)",
+ zIndex: 55,
+ }}
+ />
+ )}
+
+ {/* Snap guide for non-beat targets during clip drag */}
+ {draggedClip?.started && draggedClip.snapTime != null && draggedClip.snapType !== "beat" && (
+ <div
+ className="absolute pointer-events-none"
+ style={{
+ left: GUTTER + draggedClip.snapTime * props.pps,
+ top: RULER_H,
+ bottom: 0,
+ width: 1,
+ background: draggedClip.snapType === "playhead" ? "#3CE6AC" : "rgba(255,255,255,0.6)",
+ boxShadow:
+ draggedClip.snapType === "playhead"
+ ? "0 0 6px rgba(60,230,172,0.5)"
+ : "0 0 6px rgba(255,255,255,0.4)",
+ zIndex: 60,
+ }}
+ />
+ )}
+ {/* Drag ghost */}
{activeDraggedElement && activeDraggedPosition && (
- <TimelineDragGhost
- element={activeDraggedElement}
- position={activeDraggedPosition}
- pps={pps}
- selectedElementId={selectedElementId}
- hasCustomContent={!!renderClipContent}
- theme={theme}
+ <div
+ className="absolute pointer-events-none"
+ style={{
+ top: activeDraggedPosition.top,
+ left: activeDraggedPosition.left,
+ width: Math.max(activeDraggedElement.duration * props.pps, 4),
+ height: TRACK_H - CLIP_Y * 2,
+ zIndex: 40,
+ }}
>
- {renderClipChildren(activeDraggedElement, getTrackStyle(activeDraggedElement.tag))}
- </TimelineDragGhost>
+ <TimelineClip
+ el={{ ...activeDraggedElement, start: 0 }}
+ pps={props.pps}
+ clipY={0}
+ isSelected={
+ props.selectedElementId === (activeDraggedElement.key ?? activeDraggedElement.id)
+ }
+ isHovered={false}
+ isDragging={true}
+ hasCustomContent={!!props.renderClipContent}
+ capabilities={getTimelineEditCapabilities(activeDraggedElement)}
+ theme={props.theme}
+ isComposition={!!activeDraggedElement.compositionSrc}
+ onHoverStart={() => {}}
+ onHoverEnd={() => {}}
+ onResizeStart={() => {}}
+ onClick={() => {}}
+ onDoubleClick={() => {}}
+ >
+ {renderClipChildren(
+ activeDraggedElement,
+ props.getTrackStyle(activeDraggedElement.tag),
+ props.renderClipContent,
+ props.renderClipOverlay,
+ )}
+ </TimelineClip>
+ </div>
)}
- <TimelineSelectionOverlays
- rangeSelection={rangeSelection}
- marqueeRect={marqueeRect}
- pps={pps}
- accentColor={getTrackStyle("").accent}
- />
+ {/* Marquee (rubber-band) multi-select rectangle — mirrors the canvas
+ MarqueeOverlay look: semi-transparent accent fill + dashed border. */}
+ {props.marqueeRect && (
+ <div
+ aria-hidden="true"
+ className="absolute pointer-events-none"
+ style={{
+ left: props.marqueeRect.left,
+ top: props.marqueeRect.top,
+ width: props.marqueeRect.width,
+ height: props.marqueeRect.height,
+ background: "rgba(60,230,172,0.10)",
+ border: "1px dashed rgba(60,230,172,0.7)",
+ borderRadius: 2,
+ zIndex: 70,
+ }}
+ />
+ )}
+
+ {/* Range highlight */}
+ {props.rangeSelection && (
+ <div
+ className="absolute pointer-events-none"
+ style={{
+ left:
+ GUTTER + 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,
+ backgroundColor: "rgba(59, 130, 246, 0.12)",
+ borderLeft: "1px solid rgba(59, 130, 246, 0.4)",
+ borderRight: "1px solid rgba(59, 130, 246, 0.4)",
+ zIndex: 50,
+ }}
+ />
+ )}
{/* Playhead — hidden while dragging a beat so its guideline doesn't
track the scrub and clutter the beat being moved. */}
<div
- ref={playheadRef}
+ ref={props.playheadRef}
className="absolute top-0 bottom-0 pointer-events-none"
style={{
left: `${GUTTER}px`,
@@ -583,7 +269,7 @@ export const TimelineCanvas = memo(function TimelineCanvas({
display: beatDragging ? "none" : undefined,
}}
>
- <PlayheadIndicator />
+ <PlayheadIndicator scrubbing={props.isScrubbing} />
</div>
</div>
);
diff --git a/packages/studio/src/player/components/TimelineClip.tsx b/packages/studio/src/player/components/TimelineClip.tsx
index 4fc3b8a4fe..79abf1c39b 100644
--- a/packages/studio/src/player/components/TimelineClip.tsx
+++ b/packages/studio/src/player/components/TimelineClip.tsx
@@ -2,6 +2,7 @@ import { memo, type CSSProperties, type ReactNode } from "react";
import type { TimelineElement } from "../store/playerStore";
import { defaultTimelineTheme, getClipHandleOpacity, type TimelineTheme } from "./timelineTheme";
import type { TimelineEditCapabilities } from "./timelineEditing";
+import { isAudioTimelineElement } from "../../utils/timelineInspector";
interface TimelineClipProps {
el: TimelineElement;
@@ -62,6 +63,7 @@ export const TimelineClip = memo(function TimelineClip({
isHovered ? "is-hovered" : "",
isDragging ? "is-dragging" : "",
showDefaultText ? "" : "is-micro",
+ isAudioTimelineElement(el) ? "is-audio" : "",
]
.filter((className) => className.length > 0)
.join(" ");
@@ -72,7 +74,8 @@ export const TimelineClip = memo(function TimelineClip({
bottom: clipY,
borderRadius: theme.clipRadius,
zIndex: isDragging ? 20 : isSelected ? 10 : isHovered ? 5 : 1,
- cursor: capabilities.canMove ? "grab" : "default",
+ // Regular cursor over clips (CapCut-style, user preference) — no grab hand.
+ cursor: "default",
transform: isDragging ? "translateY(-1px)" : undefined,
};
diff --git a/packages/studio/src/player/components/TimelineClipDiamonds.tsx b/packages/studio/src/player/components/TimelineClipDiamonds.tsx
index 2fc295ad47..129104dfb8 100644
--- a/packages/studio/src/player/components/TimelineClipDiamonds.tsx
+++ b/packages/studio/src/player/components/TimelineClipDiamonds.tsx
@@ -1,12 +1,10 @@
import { memo, useRef, useState } from "react";
import { BEAT_BAND_H } from "./BeatStrip";
import {
- clampToNeighbors,
KEYFRAME_DRAG_THRESHOLD_PX,
previewClipPct,
resolveKeyframeDrag,
} from "../../components/editor/keyframeDrag";
-import { snapKeyframePctToBeat } from "./timelineEditing";
interface KeyframeEntry {
percentage: number;
@@ -30,14 +28,6 @@ interface TimelineClipDiamondsProps {
/** Beat-dot strip is shown on this track → shrink diamonds + drop them into
* the bottom half so they clear the strip at the top. */
beatsActive?: boolean;
- /** Composition-time beat positions (same source the beat strip renders from).
- * When present and `beatsActive`, a dragged keyframe snaps to the nearest beat. */
- beatTimes?: number[];
- /** Clip start / duration (seconds) + pixels-per-second, needed to map a
- * dragged keyframe's clip-% to composition time for beat snapping. */
- clipStart?: number;
- clipDurationSeconds?: number;
- pixelsPerSecond?: number;
accentColor: string;
isSelected: boolean;
currentPercentage: number;
@@ -81,10 +71,6 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({
clipWidthPx,
clipHeightPx,
beatsActive,
- beatTimes,
- clipStart = 0,
- clipDurationSeconds = 0,
- pixelsPerSecond = 1,
accentColor,
isSelected,
currentPercentage,
@@ -135,20 +121,6 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({
const baseOpacity = isSelected ? 0.4 : 0.25;
const canDrag = isSelected && !!onMoveKeyframe;
- // Snap a dragged keyframe's clip-% to the nearest beat (within ~8px), then
- // re-clamp to neighbours so the snap can't cross a sibling keyframe. No-op
- // when the beat strip isn't active for this track or no beats are loaded.
- const snapClipPctToBeat = (clipPct: number, draggedIndex: number): number => {
- if (!beatsActive || !beatTimes || beatTimes.length === 0) return clipPct;
- const snapped = snapKeyframePctToBeat(
- { start: clipStart, duration: clipDurationSeconds },
- clipPct,
- beatTimes,
- pixelsPerSecond,
- );
- return clampToNeighbors(snapped, sortedClipPcts, draggedIndex);
- };
-
return (
<div
className="absolute inset-0"
@@ -223,17 +195,14 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({
if (d.moved) {
setPreview({
kfKey,
- clipPct: snapClipPctToBeat(
- previewClipPct({
- pointerDownX: d.startX,
- pointerMoveX: e.clientX,
- clipWidthPx,
- draggedClipPct: d.fromClipPct,
- draggedIndex: i,
- sortedClipPcts,
- }),
- i,
- ),
+ clipPct: previewClipPct({
+ pointerDownX: d.startX,
+ pointerMoveX: e.clientX,
+ clipWidthPx,
+ draggedClipPct: d.fromClipPct,
+ draggedIndex: i,
+ sortedClipPcts,
+ }),
});
}
};
@@ -269,7 +238,7 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({
if (e.shiftKey) onShiftClickKeyframe?.(elementId, kf.percentage);
else onClickKeyframe?.(kf.percentage);
} else if (res.kind === "move" && res.toClipPct != null) {
- onMoveKeyframe?.(elementId, d.fromClipPct, snapClipPctToBeat(res.toClipPct, i));
+ onMoveKeyframe?.(elementId, d.fromClipPct, res.toClipPct);
// A retime still targeted this exact diamond — park/select it at its
// new position, same as a plain click, or a drag that actually moved
// something looks identical to one that silently did nothing.
diff --git a/packages/studio/src/player/components/TimelineEmptyState.tsx b/packages/studio/src/player/components/TimelineEmptyState.tsx
index 64d0d33b30..2f0a8acf8e 100644
--- a/packages/studio/src/player/components/TimelineEmptyState.tsx
+++ b/packages/studio/src/player/components/TimelineEmptyState.tsx
@@ -37,7 +37,9 @@ export function TimelineEmptyState({
style={{ position: "absolute", left: GUTTER + s * 14 }}
>
<span className="text-[9px] text-neutral-600 font-mono tabular-nums leading-none mb-0.5">
- {`${Math.floor(s / 60)}:${(s % 60).toString().padStart(2, "0")}`}
+ {`${Math.floor(s / 60)
+ .toString()
+ .padStart(2, "0")}:${(s % 60).toString().padStart(2, "0")}`}
</span>
<div className="w-px h-[5px] bg-neutral-700/40" />
</div>
diff --git a/packages/studio/src/player/components/TimelineLanes.tsx b/packages/studio/src/player/components/TimelineLanes.tsx
new file mode 100644
index 0000000000..9a2078a48b
--- /dev/null
+++ b/packages/studio/src/player/components/TimelineLanes.tsx
@@ -0,0 +1,487 @@
+import { type ReactNode } from "react";
+import { Eye, EyeSlash } from "@phosphor-icons/react";
+import { BeatStrip, BeatBackgroundLines } from "./BeatStrip";
+import { TimelineClip } from "./TimelineClip";
+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 {
+ usePlayerStore,
+ type TimelineElement,
+ type KeyframeCacheEntry,
+} from "../store/playerStore";
+import type { DraggedClipState, ResizingClipState, BlockedClipState } from "./useTimelineClipDrag";
+import {
+ isMultiDragPassenger,
+ multiDragPassengerOffsetPx,
+ type MultiDragPreviewInput,
+} from "./timelineMultiDragPreview";
+import type { TrackVisualStyle } from "./timelineIcons";
+import type { TimelineEditCallbacks } from "./timelineCallbacks";
+import { STUDIO_KEYFRAMES_ENABLED } from "../../components/editor/manualEditingAvailability";
+import { SPLIT_BOUNDARY_EPSILON_S } from "../../utils/timelineElementSplit";
+import { isAudioTimelineElement, isMusicTrack } from "../../utils/timelineInspector";
+import { Music } from "../../icons/SystemIcons";
+import { renderClipChildren } from "./timelineClipChildren";
+
+/**
+ * Props shared by the scroll container ({@link TimelineCanvas}) and the lane
+ * renderer below. TimelineCanvas passes these straight through via spread, so
+ * they are declared once here and both prop types compose from this base — no
+ * duplicated prop list.
+ */
+export interface TimelineLaneBaseProps {
+ pps: number;
+ trackContentWidth: number;
+ theme: TimelineTheme;
+ displayTrackOrder: number[];
+ trackOrder: number[];
+ tracks: [number, TimelineElement[]][];
+ trackStyles: Map<number, TrackVisualStyle>;
+ selectedElementId: string | null;
+ selectedElementIds: Set<string>;
+ hoveredClip: string | null;
+ draggedClip: DraggedClipState | null;
+ blockedClipRef: React.RefObject<BlockedClipState | null>;
+ suppressClickRef: React.RefObject<boolean>;
+ scrollRef: React.RefObject<HTMLDivElement | null>;
+ renderClipContent?: (
+ element: TimelineElement,
+ style: { clip: string; label: string },
+ ) => ReactNode;
+ renderClipOverlay?: (element: TimelineElement) => ReactNode;
+ onDrillDown?: (element: TimelineElement) => void;
+ onSelectElement?: (element: TimelineElement | null) => void;
+ setHoveredClip: (key: string | null) => void;
+ setShowPopover: (v: boolean) => void;
+ setRangeSelection: (v: null) => void;
+ setResizingClip: (v: ResizingClipState | null) => void;
+ setDraggedClip: (v: DraggedClipState | null) => void;
+ setSelectedElementId: (id: string | null) => void;
+ syncClipDragAutoScroll: (x: number, y: number) => void;
+ shiftClickClipRef: React.RefObject<{
+ element: TimelineElement;
+ anchorX: number;
+ anchorY: number;
+ } | null>;
+ getPreviewElement: (element: TimelineElement) => TimelineElement;
+ getTrackStyle: (tag: string) => TrackVisualStyle;
+ keyframeCache?: Map<string, KeyframeCacheEntry>;
+ selectedKeyframes: Set<string>;
+ currentTime: number;
+ onClickKeyframe?: (element: TimelineElement, percentage: number) => void;
+ onShiftClickKeyframe?: (elementId: string, percentage: number) => void;
+ onContextMenuKeyframe?: (e: React.MouseEvent, elementId: string, percentage: number) => void;
+ onMoveKeyframe?: (
+ elementId: string,
+ fromClipPercentage: number,
+ toClipPercentage: number,
+ ) => void;
+ onContextMenuClip?: (e: React.MouseEvent, element: TimelineElement) => void;
+ beatAnalysis?: MusicBeatAnalysis | null;
+}
+
+interface TimelineLanesProps extends TimelineLaneBaseProps {
+ /** Live-derived by TimelineCanvas from {@link TimelineLaneBaseProps.draggedClip}. */
+ draggedElement: TimelineElement | null;
+ multiDragPreview: MultiDragPreviewInput | null;
+ onToggleTrackHidden: TimelineEditCallbacks["onToggleTrackHidden"];
+ onResizeElement: TimelineEditCallbacks["onResizeElement"];
+ onMoveElement: TimelineEditCallbacks["onMoveElement"];
+ onRazorSplit: TimelineEditCallbacks["onRazorSplit"];
+ onRazorSplitAll: TimelineEditCallbacks["onRazorSplitAll"];
+}
+
+export function TimelineLanes({
+ pps,
+ trackContentWidth,
+ theme,
+ displayTrackOrder,
+ trackOrder,
+ tracks,
+ trackStyles,
+ selectedElementId,
+ selectedElementIds,
+ hoveredClip,
+ draggedClip,
+ draggedElement,
+ multiDragPreview,
+ blockedClipRef,
+ suppressClickRef,
+ scrollRef,
+ renderClipContent,
+ renderClipOverlay,
+ onDrillDown,
+ onSelectElement,
+ setHoveredClip,
+ setShowPopover,
+ setRangeSelection,
+ setResizingClip,
+ setDraggedClip,
+ setSelectedElementId,
+ syncClipDragAutoScroll,
+ shiftClickClipRef,
+ getPreviewElement,
+ getTrackStyle,
+ keyframeCache,
+ selectedKeyframes,
+ currentTime,
+ onClickKeyframe,
+ onShiftClickKeyframe,
+ onContextMenuKeyframe,
+ onMoveKeyframe,
+ onContextMenuClip,
+ beatAnalysis,
+ onToggleTrackHidden,
+ onResizeElement,
+ onMoveElement,
+ onRazorSplit,
+ onRazorSplitAll,
+}: TimelineLanesProps) {
+ return (
+ <>
+ {
+ // NOTE (deliberate no-virtualization): lanes and their clips render via a
+ // plain `.map()` inside the scroll container rather than a windowing/virtualized
+ // list. NLE clip counts are small (dozens to low hundreds), so the DOM cost is
+ // bounded and virtualization's complexity isn't worth it. TODO: revisit and swap
+ // in a virtualizer if editorial workflows ever push very high clip counts.
+ // fallow-ignore-next-line complexity
+ displayTrackOrder.map((trackNum) => {
+ const els = tracks.find(([t]) => t === trackNum)?.[1] ?? [];
+ const ts = trackStyles.get(trackNum) ?? getTrackStyle("");
+ const isPendingTrack =
+ draggedClip?.started === true && !trackOrder.includes(trackNum) && els.length === 0;
+ // All lanes use the same uniform color — no alternating stripes.
+ const rowBackground = theme.rowBackground;
+ // The beat-dot strip occupies the top of this track's lane (active track,
+ // or the music track when nothing is selected). When shown, keyframe
+ // diamonds shrink + drop to the bottom half so they don't collide with it.
+ const beatStripOnTrack =
+ (beatAnalysis?.beatTimes?.length ?? 0) >= 2 &&
+ (selectedElementId
+ ? els.some((e) => (e.key ?? e.id) === selectedElementId)
+ : els.some(isMusicTrack));
+ 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
+ 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}`,
+ }}
+ >
+ {isAudioTrack && (
+ <Music size={12} weight="fill" aria-hidden="true" className="text-white/35" />
+ )}
+ <button
+ type="button"
+ aria-label={isTrackHidden ? `Show track ${trackNum}` : `Hide track ${trackNum}`}
+ title={isTrackHidden ? `Show track ${trackNum}` : `Hide track ${trackNum}`}
+ className={`flex h-6 w-6 items-center justify-center rounded border-0 bg-transparent p-0 transition-colors focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-[-1px] focus-visible:outline-[#3CE6AC] ${
+ isTrackHidden
+ ? "text-[#3CE6AC] hover:text-white"
+ : "text-white/35 hover:text-white/75"
+ }`}
+ onPointerDown={(e) => {
+ e.stopPropagation();
+ }}
+ onClick={(e) => {
+ e.stopPropagation();
+ void onToggleTrackHidden?.(trackNum, !isTrackHidden);
+ }}
+ >
+ {isTrackHidden ? (
+ <EyeSlash size={14} weight="bold" aria-hidden="true" />
+ ) : (
+ <Eye size={14} weight="bold" aria-hidden="true" />
+ )}
+ </button>
+ </div>
+ <div
+ style={{
+ width: trackContentWidth,
+ opacity: isTrackHidden ? 0.35 : 1,
+ transition: "opacity 120ms ease",
+ }}
+ className="relative"
+ >
+ {/* Faint beat lines in every track's background (behind the clips);
+ the active move-snap target is highlighted. */}
+ <BeatBackgroundLines
+ beatTimes={beatAnalysis?.beatTimes}
+ beatStrengths={beatAnalysis?.beatStrengths}
+ pps={pps}
+ highlightTime={
+ draggedClip?.started && draggedClip.snapType === "beat"
+ ? draggedClip.snapTime
+ : null
+ }
+ />
+ {/* Beat dots on the active track (the one holding the selection),
+ falling back to the music track when nothing is selected. */}
+ {beatStripOnTrack && (
+ <BeatStrip
+ beatTimes={beatAnalysis?.beatTimes}
+ beatStrengths={beatAnalysis?.beatStrengths}
+ pps={pps}
+ />
+ )}
+ {isPendingTrack && (
+ <div
+ className="absolute inset-0 flex items-center"
+ style={{
+ paddingLeft: 16,
+ color: ts.label,
+ fontSize: 11,
+ letterSpacing: "0.06em",
+ textTransform: "uppercase",
+ opacity: 0.5,
+ }}
+ >
+ New track
+ </div>
+ )}
+ {
+ // fallow-ignore-next-line complexity
+ els.map((el) => {
+ const clipStyle = getTrackStyle(el.tag);
+ const elementKey = el.key ?? el.id;
+ const capabilities = getTimelineEditCapabilities(el);
+ const isSelected =
+ selectedElementId === elementKey || selectedElementIds.has(elementKey);
+ const isComposition = !!el.compositionSrc;
+ // elementKey (el.key ?? el.id) is already unique per clip; do NOT
+ // fold in the map index, or a splice/reorder remounts every clip
+ // at/after the change (DOM flash, drag interruption).
+ const clipKey = elementKey;
+ const isDraggingClip =
+ draggedClip?.started === true &&
+ (draggedElement?.key ?? draggedElement?.id) === elementKey;
+ if (isDraggingClip) return null;
+ const previewElement = getPreviewElement(el);
+ // Passenger of a live multi-drag: slide by the SAME formation
+ // delta (the grabbed clip's group-clamped delta) via a
+ // compositor transform on a same-geometry wrapper (absolute
+ // inset-0 → identical offset parent, so the clip's own
+ // left/top are preserved), plus the ghost's elevated z/opacity.
+ const isPassenger =
+ multiDragPreview != null && isMultiDragPassenger(clipKey, multiDragPreview);
+ const passengerOffsetPx = isPassenger
+ ? multiDragPassengerOffsetPx(clipKey, pps, multiDragPreview)
+ : 0;
+ const clip = (
+ <TimelineClip
+ key={clipKey}
+ onContextMenu={(e: React.MouseEvent) => {
+ e.preventDefault();
+ onContextMenuClip?.(e, el);
+ }}
+ el={previewElement}
+ pps={pps}
+ clipY={CLIP_Y}
+ isSelected={isSelected}
+ isHovered={hoveredClip === clipKey}
+ isDragging={false}
+ hasCustomContent={!!renderClipContent}
+ capabilities={capabilities}
+ theme={theme}
+ isComposition={isComposition}
+ onHoverStart={() => setHoveredClip(clipKey)}
+ onHoverEnd={() => setHoveredClip(null)}
+ onResizeStart={
+ // fallow-ignore-next-line complexity
+ (edge, e) => {
+ if (e.button !== 0 || e.shiftKey || !onResizeElement) return;
+ if (edge === "start" && !capabilities.canTrimStart) return;
+ if (edge === "end" && !capabilities.canTrimEnd) return;
+ e.stopPropagation();
+ blockedClipRef.current = null;
+ setShowPopover(false);
+ setRangeSelection(null);
+ setResizingClip({
+ element: el,
+ edge,
+ originClientX: e.clientX,
+ originScrollLeft: scrollRef.current?.scrollLeft ?? 0,
+ previewStart: el.start,
+ previewDuration: el.duration,
+ previewPlaybackStart: el.playbackStart,
+ started: false,
+ });
+ }
+ }
+ onPointerDown={
+ // fallow-ignore-next-line complexity
+ (e) => {
+ if (e.button !== 0) return;
+ if (usePlayerStore.getState().activeTool === "razor") return;
+ if (e.shiftKey) {
+ shiftClickClipRef.current = {
+ element: el,
+ anchorX: e.clientX,
+ anchorY: e.clientY,
+ };
+ return;
+ }
+ const target = e.currentTarget as HTMLElement;
+ const rect = target.getBoundingClientRect();
+ const blockedIntent = resolveBlockedTimelineEditIntent({
+ width: rect.width,
+ offsetX: e.clientX - rect.left,
+ handleWidth: CLIP_HANDLE_W,
+ capabilities,
+ });
+ if (
+ blockedIntent &&
+ ((blockedIntent === "move" && onMoveElement) ||
+ (blockedIntent !== "move" && onResizeElement))
+ ) {
+ blockedClipRef.current = {
+ element: el,
+ intent: blockedIntent,
+ originClientX: e.clientX,
+ originClientY: e.clientY,
+ started: false,
+ };
+ return;
+ }
+ if (!onMoveElement || !capabilities.canMove) return;
+ blockedClipRef.current = null;
+ setShowPopover(false);
+ setRangeSelection(null);
+ setDraggedClip({
+ element: el,
+ originClientX: e.clientX,
+ originClientY: e.clientY,
+ originScrollLeft: scrollRef.current?.scrollLeft ?? 0,
+ originScrollTop: scrollRef.current?.scrollTop ?? 0,
+ pointerClientX: e.clientX,
+ pointerClientY: e.clientY,
+ pointerOffsetX: e.clientX - rect.left,
+ pointerOffsetY: e.clientY - rect.top,
+ previewStart: el.start,
+ previewTrack: el.track,
+ desiredTrack: el.track,
+ insertRow: null,
+ snapTime: null,
+ snapType: null,
+ started: false,
+ });
+ syncClipDragAutoScroll(e.clientX, e.clientY);
+ }
+ }
+ onClick={
+ // fallow-ignore-next-line complexity
+ (e) => {
+ e.stopPropagation();
+ if (suppressClickRef.current) return;
+ const { activeTool } = usePlayerStore.getState();
+ if (activeTool === "razor" && onRazorSplit) {
+ const clipRect = (
+ e.currentTarget as HTMLElement
+ ).getBoundingClientRect();
+ const clickOffsetX = e.clientX - clipRect.left;
+ const splitTime = previewElement.start + clickOffsetX / pps;
+ const clampedTime = Math.max(
+ previewElement.start + SPLIT_BOUNDARY_EPSILON_S,
+ Math.min(
+ previewElement.start +
+ previewElement.duration -
+ SPLIT_BOUNDARY_EPSILON_S,
+ splitTime,
+ ),
+ );
+ if (e.shiftKey && onRazorSplitAll) {
+ onRazorSplitAll(clampedTime);
+ } else {
+ onRazorSplit(el, clampedTime);
+ }
+ return;
+ }
+ // Plain click single-selects: drop any marquee multi-selection.
+ // Only a click on the PRIMARY selection toggles it off — a click
+ // on a marquee-selected clip narrows the selection to that clip.
+ const hadMultiSelection = selectedElementIds.size > 0;
+ usePlayerStore.getState().clearSelectedElementIds();
+ const nextElement =
+ selectedElementId === elementKey && !hadMultiSelection ? null : el;
+ setSelectedElementId(nextElement ? elementKey : null);
+ onSelectElement?.(nextElement);
+ }
+ }
+ onDoubleClick={(e) => {
+ e.stopPropagation();
+ if (suppressClickRef.current) return;
+ if (isComposition && onDrillDown) onDrillDown(el);
+ }}
+ >
+ {renderClipChildren(
+ previewElement,
+ clipStyle,
+ renderClipContent,
+ renderClipOverlay,
+ )}
+ {STUDIO_KEYFRAMES_ENABLED && keyframeCache?.get(elementKey) && (
+ <TimelineClipDiamonds
+ keyframesData={keyframeCache.get(elementKey)!}
+ clipWidthPx={Math.max(previewElement.duration * pps, 4)}
+ clipHeightPx={TRACK_H - 2 * CLIP_Y}
+ beatsActive={beatStripOnTrack}
+ accentColor={clipStyle.accent}
+ isSelected={isSelected}
+ currentPercentage={
+ previewElement.duration > 0
+ ? ((currentTime - previewElement.start) / previewElement.duration) *
+ 100
+ : 0
+ }
+ elementId={elementKey}
+ selectedKeyframes={selectedKeyframes}
+ onClickKeyframe={(pct) => onClickKeyframe?.(previewElement, pct)}
+ onShiftClickKeyframe={onShiftClickKeyframe}
+ onContextMenuKeyframe={onContextMenuKeyframe}
+ onMoveKeyframe={onMoveKeyframe}
+ suppressClickRef={suppressClickRef}
+ />
+ )}
+ </TimelineClip>
+ );
+ if (!isPassenger) return clip;
+ return (
+ <div
+ key={clipKey}
+ className="absolute inset-0"
+ style={{
+ transform: `translateX(${passengerOffsetPx}px)`,
+ opacity: 0.85,
+ zIndex: 20,
+ pointerEvents: "none",
+ }}
+ >
+ {clip}
+ </div>
+ );
+ })
+ }
+ </div>
+ </div>
+ );
+ })
+ }
+ </>
+ );
+}
diff --git a/packages/studio/src/player/components/TimelineLayerGutter.tsx b/packages/studio/src/player/components/TimelineLayerGutter.tsx
deleted file mode 100644
index 435df303fd..0000000000
--- a/packages/studio/src/player/components/TimelineLayerGutter.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import { Eye, EyeSlash } from "@phosphor-icons/react";
-import { Music } from "../../icons/SystemIcons";
-import type { TimelineTheme } from "./timelineTheme";
-import { GUTTER } from "./timelineLayout";
-
-interface TimelineLayerGutterProps {
- isAudio: boolean;
- isTrackHidden: boolean;
- rowTrack: number;
- theme: TimelineTheme;
- onToggleHidden: () => void;
-}
-
-export function TimelineLayerGutter({
- isAudio,
- isTrackHidden,
- rowTrack,
- theme,
- onToggleHidden,
-}: TimelineLayerGutterProps) {
- return (
- <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}`,
- }}
- >
- {isAudio && (
- <Music
- size={12}
- weight="fill"
- aria-hidden="true"
- style={{ color: theme.textSecondary, opacity: 0.7 }}
- />
- )}
- <button
- type="button"
- aria-label={isTrackHidden ? `Show track ${rowTrack}` : `Hide track ${rowTrack}`}
- title={isTrackHidden ? `Show track ${rowTrack}` : `Hide track ${rowTrack}`}
- className={`flex h-6 w-6 items-center justify-center rounded border-0 bg-transparent p-0 transition-colors focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-[-1px] focus-visible:outline-[#3CE6AC] ${
- isTrackHidden ? "text-[#3CE6AC] hover:text-white" : "text-white/35 hover:text-white/75"
- }`}
- onPointerDown={(e) => {
- e.stopPropagation();
- }}
- onClick={(e) => {
- e.stopPropagation();
- onToggleHidden();
- }}
- >
- {isTrackHidden ? (
- <EyeSlash size={14} weight="bold" aria-hidden="true" />
- ) : (
- <Eye size={14} weight="bold" aria-hidden="true" />
- )}
- </button>
- </div>
- );
-}
diff --git a/packages/studio/src/player/components/TimelineOverlays.tsx b/packages/studio/src/player/components/TimelineOverlays.tsx
new file mode 100644
index 0000000000..0f0efcb73d
--- /dev/null
+++ b/packages/studio/src/player/components/TimelineOverlays.tsx
@@ -0,0 +1,122 @@
+import type { KeyframeCacheEntry, TimelineElement } from "../store/playerStore";
+import type { TimelineTheme } from "./timelineTheme";
+import type { TimelineRangeSelection } from "./timelineEditing";
+import type { TimelineEditCallbacks } from "./timelineCallbacks";
+import { EditPopover } from "./EditModal";
+import {
+ KeyframeDiamondContextMenu,
+ type KeyframeDiamondContextMenuState,
+} from "./KeyframeDiamondContextMenu";
+import { ClipContextMenu } from "./ClipContextMenu";
+import { TimelineShortcutHint } from "./TimelineShortcutHint";
+
+interface ClipContextMenuState {
+ x: number;
+ y: number;
+ element: TimelineElement;
+}
+
+interface TimelineOverlaysProps {
+ theme: TimelineTheme;
+ showShortcutHint: boolean;
+ showPopover: boolean;
+ rangeSelection: TimelineRangeSelection | null;
+ setShowPopover: (value: boolean) => void;
+ setRangeSelection: (value: TimelineRangeSelection | null) => void;
+ kfContextMenu: KeyframeDiamondContextMenuState | null;
+ setKfContextMenu: (value: KeyframeDiamondContextMenuState | null) => void;
+ onDeleteKeyframe: TimelineEditCallbacks["onDeleteKeyframe"];
+ onDeleteAllKeyframes: TimelineEditCallbacks["onDeleteAllKeyframes"];
+ onChangeKeyframeEase: TimelineEditCallbacks["onChangeKeyframeEase"];
+ onMoveKeyframeToPlayhead: TimelineEditCallbacks["onMoveKeyframeToPlayhead"];
+ keyframeCache: Map<string, KeyframeCacheEntry>;
+ clipContextMenu: ClipContextMenuState | null;
+ setClipContextMenu: (value: ClipContextMenuState | null) => void;
+ currentTime: number;
+ onSplitElement: TimelineEditCallbacks["onSplitElement"];
+ pinZoomBeforeEdit: () => void;
+ onDeleteElement?: (element: TimelineElement) => Promise<void> | void;
+}
+
+// The timeline's floating overlays, rendered as siblings above the scroll area:
+// the shortcut hint, the range-edit popover, the keyframe-diamond context menu,
+// and the clip context menu.
+export function TimelineOverlays({
+ theme,
+ showShortcutHint,
+ showPopover,
+ rangeSelection,
+ setShowPopover,
+ setRangeSelection,
+ kfContextMenu,
+ setKfContextMenu,
+ onDeleteKeyframe,
+ onDeleteAllKeyframes,
+ onChangeKeyframeEase,
+ onMoveKeyframeToPlayhead,
+ keyframeCache,
+ clipContextMenu,
+ setClipContextMenu,
+ currentTime,
+ onSplitElement,
+ pinZoomBeforeEdit,
+ onDeleteElement,
+}: TimelineOverlaysProps) {
+ return (
+ <>
+ {showShortcutHint && !showPopover && !rangeSelection && (
+ <TimelineShortcutHint theme={theme} />
+ )}
+
+ {showPopover && rangeSelection && (
+ <EditPopover
+ rangeStart={rangeSelection.start}
+ rangeEnd={rangeSelection.end}
+ anchorX={rangeSelection.anchorX}
+ anchorY={rangeSelection.anchorY}
+ onClose={() => {
+ setShowPopover(false);
+ setRangeSelection(null);
+ }}
+ />
+ )}
+
+ {kfContextMenu && (
+ <KeyframeDiamondContextMenu
+ state={kfContextMenu}
+ onClose={() => setKfContextMenu(null)}
+ onDelete={(elId, pct) => onDeleteKeyframe?.(elId, pct)}
+ onDeleteAll={(elId) => onDeleteAllKeyframes?.(elId)}
+ onChangeEase={(elId, pct, ease) => onChangeKeyframeEase?.(elId, pct, ease)}
+ onMoveToPlayhead={
+ onMoveKeyframeToPlayhead
+ ? (elId, pct) => onMoveKeyframeToPlayhead(elId, pct)
+ : undefined
+ }
+ onCopyProperties={(elId, pct) => {
+ const kfData = keyframeCache.get(elId);
+ const kf = kfData?.keyframes.find((k) => k.percentage === pct);
+ if (kf) {
+ void navigator.clipboard.writeText(JSON.stringify(kf.properties, null, 2));
+ }
+ }}
+ />
+ )}
+
+ {clipContextMenu && (
+ <ClipContextMenu
+ x={clipContextMenu.x}
+ y={clipContextMenu.y}
+ element={clipContextMenu.element}
+ currentTime={currentTime}
+ onClose={() => setClipContextMenu(null)}
+ onSplit={(el, time) => onSplitElement?.(el, time)}
+ onDelete={(el) => {
+ pinZoomBeforeEdit();
+ onDeleteElement?.(el);
+ }}
+ />
+ )}
+ </>
+ );
+}
diff --git a/packages/studio/src/player/components/TimelineSelectionOverlays.tsx b/packages/studio/src/player/components/TimelineSelectionOverlays.tsx
deleted file mode 100644
index 249b92edea..0000000000
--- a/packages/studio/src/player/components/TimelineSelectionOverlays.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import type { TimelineRangeSelection } from "./timelineEditing";
-import { GUTTER, RULER_H } from "./timelineLayout";
-import type { TimelineMarqueeOverlayRect } from "./useTimelineMarqueeSelection";
-
-interface TimelineSelectionOverlaysProps {
- rangeSelection: TimelineRangeSelection | null;
- marqueeRect: TimelineMarqueeOverlayRect | null;
- pps: number;
- /** Primary/accent color (hex) shared with the rest of the timeline chrome. */
- accentColor: string;
-}
-
-export function TimelineSelectionOverlays({
- rangeSelection,
- marqueeRect,
- pps,
- accentColor,
-}: TimelineSelectionOverlaysProps) {
- return (
- <>
- {rangeSelection && (
- <div
- className="absolute pointer-events-none"
- style={{
- left: GUTTER + Math.min(rangeSelection.start, rangeSelection.end) * pps,
- width: Math.abs(rangeSelection.end - rangeSelection.start) * pps,
- top: RULER_H,
- bottom: 0,
- backgroundColor: `${accentColor}1f`,
- borderLeft: `1px solid ${accentColor}`,
- borderRight: `1px solid ${accentColor}`,
- zIndex: 50,
- }}
- />
- )}
- {marqueeRect && (
- <div
- aria-hidden="true"
- className="absolute pointer-events-none"
- data-timeline-marquee="true"
- style={{
- left: marqueeRect.left,
- top: marqueeRect.top,
- width: marqueeRect.width,
- height: marqueeRect.height,
- backgroundColor: `${accentColor}29`,
- border: `1px solid ${accentColor}`,
- boxShadow: "0 0 0 1px rgba(15, 23, 42, 0.35)",
- zIndex: 60,
- }}
- />
- )}
- </>
- );
-}
diff --git a/packages/studio/src/player/components/VideoThumbnail.test.tsx b/packages/studio/src/player/components/VideoThumbnail.test.tsx
new file mode 100644
index 0000000000..82f49d8966
--- /dev/null
+++ b/packages/studio/src/player/components/VideoThumbnail.test.tsx
@@ -0,0 +1,152 @@
+// @vitest-environment happy-dom
+import React, { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { VideoThumbnail } from "./VideoThumbnail";
+
+Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
+ configurable: true,
+ value: true,
+});
+
+// Fire "intersecting" immediately on observe so the extraction effect runs.
+class MockIntersectionObserver {
+ private cb: IntersectionObserverCallback;
+ constructor(cb: IntersectionObserverCallback) {
+ this.cb = cb;
+ }
+ observe() {
+ this.cb(
+ [{ isIntersecting: true } as IntersectionObserverEntry],
+ this as unknown as IntersectionObserver,
+ );
+ }
+ disconnect() {}
+ unobserve() {}
+ takeRecords(): IntersectionObserverEntry[] {
+ return [];
+ }
+}
+
+class MockResizeObserver {
+ observe() {}
+ disconnect() {}
+ unobserve() {}
+}
+
+const originalIO = globalThis.IntersectionObserver;
+const originalRO = globalThis.ResizeObserver;
+
+let host: HTMLDivElement;
+let root: Root | null = null;
+let createdVideos: HTMLVideoElement[];
+
+beforeEach(() => {
+ globalThis.IntersectionObserver =
+ MockIntersectionObserver as unknown as typeof IntersectionObserver;
+ globalThis.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver;
+
+ createdVideos = [];
+ const origCreate = document.createElement.bind(document);
+ vi.spyOn(document, "createElement").mockImplementation((tag: string) => {
+ const el = origCreate(tag);
+ if (tag === "video") createdVideos.push(el as HTMLVideoElement);
+ return el;
+ });
+
+ // happy-dom's <video>/<canvas> don't decode media; stub the seam the
+ // extractor depends on so the effect can run deterministically.
+ vi.spyOn(HTMLMediaElement.prototype, "load").mockImplementation(() => {});
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({
+ drawImage: () => {},
+ } as unknown as CanvasRenderingContext2D);
+
+ host = document.createElement("div");
+ document.body.append(host);
+});
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ vi.restoreAllMocks();
+ globalThis.IntersectionObserver = originalIO;
+ globalThis.ResizeObserver = originalRO;
+ document.body.innerHTML = "";
+});
+
+function render(videoSrc: string) {
+ root = createRoot(host);
+ act(() => {
+ root!.render(React.createElement(VideoThumbnail, { videoSrc, label: "", labelColor: "#fff" }));
+ });
+}
+
+function lastVideo(): HTMLVideoElement {
+ const v = createdVideos.at(-1);
+ expect(v).toBeDefined();
+ return v!;
+}
+
+describe("VideoThumbnail — tainted-canvas fallback", () => {
+ it("stops the extractor and drops the shimmer when toDataURL throws a SecurityError", () => {
+ vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockImplementation(() => {
+ throw new DOMException("Tainted canvases may not be exported.", "SecurityError");
+ });
+
+ render("https://cdn.example.com/no-cors.mp4");
+
+ // The effect ran once visible → a hidden <video> was created.
+ const video = lastVideo();
+
+ act(() => {
+ video.dispatchEvent(new Event("loadedmetadata"));
+ });
+ act(() => {
+ video.dispatchEvent(new Event("seeked"));
+ });
+
+ // No frame captured, and crucially the shimmer is gone (not spinning
+ // forever) — the clip falls back to its plain background.
+ expect(host.querySelectorAll("img").length).toBe(0);
+ expect(host.querySelector(".animate-pulse")).toBeNull();
+ });
+
+ it("drops the shimmer when a no-CORS load fires the video error event (0 frames) (#2214)", () => {
+ render("https://cdn.example.com/no-cors.mp4");
+ // Before the load resolves, the shimmer placeholder is up.
+ expect(host.querySelector(".animate-pulse")).not.toBeNull();
+
+ const video = lastVideo();
+ // crossOrigin="anonymous" against a CORS-less server fails the load outright —
+ // the error listener fires instead of loadedmetadata/seeked, so no frame is
+ // ever captured. The shimmer must stop rather than spin forever.
+ act(() => {
+ video.dispatchEvent(new Event("error"));
+ });
+
+ expect(host.querySelectorAll("img").length).toBe(0);
+ expect(host.querySelector(".animate-pulse")).toBeNull();
+ });
+
+ it("keeps streaming frames while the shimmer is up until a frame arrives", () => {
+ vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockReturnValue(
+ "data:image/jpeg;base64,AAAA",
+ );
+
+ render("/api/projects/p/preview/assets/clip.mp4");
+ // Before any seek resolves, the shimmer placeholder is shown.
+ expect(host.querySelector(".animate-pulse")).not.toBeNull();
+
+ const video = lastVideo();
+ act(() => {
+ video.dispatchEvent(new Event("loadedmetadata"));
+ });
+ act(() => {
+ video.dispatchEvent(new Event("seeked"));
+ });
+
+ // A frame was captured, so tiles render and the shimmer clears.
+ expect(host.querySelectorAll("img").length).toBeGreaterThanOrEqual(1);
+ expect(host.querySelector(".animate-pulse")).toBeNull();
+ });
+});
diff --git a/packages/studio/src/player/components/VideoThumbnail.tsx b/packages/studio/src/player/components/VideoThumbnail.tsx
index eb84891b61..2c6df17429 100644
--- a/packages/studio/src/player/components/VideoThumbnail.tsx
+++ b/packages/studio/src/player/components/VideoThumbnail.tsx
@@ -1,5 +1,6 @@
import { memo, useRef, useState, useCallback, useEffect } from "react";
import { useMountEffect } from "../../hooks/useMountEffect";
+import { computeThumbnailStrip, THUMBNAIL_CLIP_HEIGHT } from "./thumbnailUtils";
interface VideoThumbnailProps {
videoSrc: string;
@@ -8,7 +9,7 @@ interface VideoThumbnailProps {
duration?: number;
}
-const CLIP_HEIGHT = 66;
+const CLIP_HEIGHT = THUMBNAIL_CLIP_HEIGHT;
const MAX_UNIQUE_FRAMES: number = 6;
/**
@@ -25,6 +26,7 @@ export const VideoThumbnail = memo(function VideoThumbnail({
const [containerWidth, setContainerWidth] = useState(0);
const [visible, setVisible] = useState(false);
const [frames, setFrames] = useState<string[]>([]);
+ const [failed, setFailed] = useState(false);
const [aspect, setAspect] = useState(16 / 9);
const ioRef = useRef<IntersectionObserver | null>(null);
const roRef = useRef<ResizeObserver | null>(null);
@@ -117,8 +119,22 @@ export const VideoThumbnail = memo(function VideoThumbnail({
video.addEventListener("seeked", () => {
if (cancelled) return;
- ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
- const dataUrl = canvas.toDataURL("image/jpeg", 0.6);
+ let dataUrl: string;
+ try {
+ ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
+ dataUrl = canvas.toDataURL("image/jpeg", 0.6);
+ } catch {
+ // An external http(s) video served without CORS headers taints the
+ // canvas, so toDataURL throws a SecurityError. Stop the extractor
+ // cleanly and fall back to the no-thumbnail rendering (plain clip
+ // background), matching ImageThumbnail's error path — otherwise the
+ // shimmer placeholder would spin forever.
+ cancelled = true;
+ setFailed(true);
+ video.src = "";
+ video.load();
+ return;
+ }
// Stream each frame immediately
setFrames((prev) => [...prev, dataUrl]);
idx++;
@@ -126,7 +142,12 @@ export const VideoThumbnail = memo(function VideoThumbnail({
});
video.addEventListener("error", () => {
- /* keep whatever frames we have */
+ // A no-CORS load fails outright (crossOrigin="anonymous" rejects a video
+ // served without CORS headers), firing this instead of the taint path in
+ // "seeked" — so 0 frames are ever extracted. Keep whatever frames we have,
+ // but mark failed so the shimmer placeholder stops spinning forever and we
+ // fall back to the plain clip background (#2214).
+ setFailed(true);
});
video.src = videoSrc;
@@ -136,13 +157,13 @@ export const VideoThumbnail = memo(function VideoThumbnail({
cancelled = true;
extractingRef.current = false;
setFrames([]);
+ setFailed(false);
video.src = "";
video.load();
};
}, [visible, videoSrc, duration]);
- const frameW = Math.round(CLIP_HEIGHT * aspect);
- const frameCount = containerWidth > 0 ? Math.max(1, Math.ceil(containerWidth / frameW)) : 1;
+ const { frameW, frameCount } = computeThumbnailStrip(containerWidth, aspect, CLIP_HEIGHT);
return (
<div ref={setContainerRef} className="absolute inset-0 overflow-hidden">
@@ -168,7 +189,7 @@ export const VideoThumbnail = memo(function VideoThumbnail({
</div>
)}
- {visible && frames.length === 0 && (
+ {visible && frames.length === 0 && !failed && (
<div
className="absolute inset-0 animate-pulse"
style={{
diff --git a/packages/studio/src/player/components/thumbnailUtils.test.ts b/packages/studio/src/player/components/thumbnailUtils.test.ts
new file mode 100644
index 0000000000..38356b2f6c
--- /dev/null
+++ b/packages/studio/src/player/components/thumbnailUtils.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it } from "vitest";
+import {
+ computeThumbnailStrip,
+ encodePreviewPath,
+ resolveMediaPreviewUrl,
+ THUMBNAIL_CLIP_HEIGHT,
+} from "./thumbnailUtils";
+
+describe("computeThumbnailStrip", () => {
+ it("sizes tiles by aspect ratio at the clip height", () => {
+ const { frameW } = computeThumbnailStrip(500, 16 / 9);
+ expect(frameW).toBe(Math.round(THUMBNAIL_CLIP_HEIGHT * (16 / 9)));
+ });
+
+ it("repeats tiles to cover the container width", () => {
+ const { frameW, frameCount } = computeThumbnailStrip(500, 1);
+ expect(frameW).toBe(THUMBNAIL_CLIP_HEIGHT);
+ expect(frameCount).toBe(Math.ceil(500 / THUMBNAIL_CLIP_HEIGHT));
+ expect(frameCount * frameW).toBeGreaterThanOrEqual(500);
+ });
+
+ it("returns one tile when the container width is unknown", () => {
+ expect(computeThumbnailStrip(0, 16 / 9).frameCount).toBe(1);
+ expect(computeThumbnailStrip(-10, 16 / 9).frameCount).toBe(1);
+ });
+
+ it("falls back to 16:9 for degenerate aspects", () => {
+ const expected = Math.round(THUMBNAIL_CLIP_HEIGHT * (16 / 9));
+ expect(computeThumbnailStrip(300, 0).frameW).toBe(expected);
+ expect(computeThumbnailStrip(300, -2).frameW).toBe(expected);
+ expect(computeThumbnailStrip(300, Number.NaN).frameW).toBe(expected);
+ expect(computeThumbnailStrip(300, Number.POSITIVE_INFINITY).frameW).toBe(expected);
+ });
+
+ it("never returns a zero-width tile (avoids divide-by-zero repeat counts)", () => {
+ const { frameW, frameCount } = computeThumbnailStrip(300, 0.001);
+ expect(frameW).toBeGreaterThanOrEqual(1);
+ expect(Number.isFinite(frameCount)).toBe(true);
+ });
+
+ it("honors a custom clip height", () => {
+ expect(computeThumbnailStrip(300, 2, 40).frameW).toBe(80);
+ });
+});
+
+describe("resolveMediaPreviewUrl", () => {
+ it("routes composition-relative paths through the project preview endpoint", () => {
+ expect(resolveMediaPreviewUrl("assets/image.png", "proj-1")).toBe(
+ "/api/projects/proj-1/preview/assets/image.png",
+ );
+ });
+
+ it("passes absolute http(s) URLs through untouched", () => {
+ expect(resolveMediaPreviewUrl("http://cdn.example.com/a.mp4", "proj-1")).toBe(
+ "http://cdn.example.com/a.mp4",
+ );
+ expect(resolveMediaPreviewUrl("https://cdn.example.com/a.png", "proj-1")).toBe(
+ "https://cdn.example.com/a.png",
+ );
+ });
+
+ it("percent-encodes spaces in filenames", () => {
+ expect(resolveMediaPreviewUrl("assets/my logo.png", "proj-1")).toBe(
+ "/api/projects/proj-1/preview/assets/my%20logo.png",
+ );
+ });
+
+ it("percent-encodes parentheses in filenames", () => {
+ expect(resolveMediaPreviewUrl("assets/heygen-symbol-blue-logo (2).svg", "proj-1")).toBe(
+ "/api/projects/proj-1/preview/assets/heygen-symbol-blue-logo%20(2).svg",
+ );
+ });
+
+ it("preserves slashes as path separators while encoding each segment", () => {
+ expect(resolveMediaPreviewUrl("sub dir/file (v2).mp4", "proj-2")).toBe(
+ "/api/projects/proj-2/preview/sub%20dir/file%20(v2).mp4",
+ );
+ });
+
+ it("percent-encodes unicode characters in filenames", () => {
+ expect(resolveMediaPreviewUrl("assets/café logo.png", "proj-1")).toBe(
+ "/api/projects/proj-1/preview/assets/caf%C3%A9%20logo.png",
+ );
+ });
+
+ it("leaves paths with no special characters unchanged", () => {
+ expect(resolveMediaPreviewUrl("assets/logo.svg", "proj-1")).toBe(
+ "/api/projects/proj-1/preview/assets/logo.svg",
+ );
+ });
+
+ it("percent-encodes a U+202F narrow no-break space (macOS screenshot artifact)", () => {
+ // "Screenshot … 2.16.30 PM.png" — the char between the time and PM is a
+ // narrow no-break space; it must encode to %E2%80%AF, not route raw (404).
+ expect(resolveMediaPreviewUrl("assets/Screenshot 2.16.30 PM.png", "proj-1")).toBe(
+ "/api/projects/proj-1/preview/assets/Screenshot%202.16.30%E2%80%AFPM.png",
+ );
+ });
+
+ it("passes data: URIs through untouched (never routes them through preview → HTTP 431)", () => {
+ const svg = "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=";
+ expect(resolveMediaPreviewUrl(svg, "proj-1")).toBe(svg);
+ });
+
+ it("passes blob: URLs through untouched", () => {
+ const blob = "blob:http://localhost:5190/2b3c-4d5e";
+ expect(resolveMediaPreviewUrl(blob, "proj-1")).toBe(blob);
+ });
+});
+
+// The shared encoder used by every timeline media-URL builder (filmstrip, audio
+// waveform, sub-composition preview) — must match the assets panel's per-segment
+// encoding so those paths stop 404ing on non-ASCII filenames.
+describe("encodePreviewPath", () => {
+ it("encodes spaces and parentheses per segment, preserving slashes", () => {
+ expect(encodePreviewPath("sub dir/file (v2).mp3")).toBe("sub%20dir/file%20(v2).mp3");
+ });
+
+ it("encodes a U+202F narrow no-break space to %E2%80%AF", () => {
+ expect(encodePreviewPath("assets/clip 2.mp3")).toBe("assets/clip%202.mp3");
+ expect(encodePreviewPath(`assets/clip${" "}2.mp3`)).toBe("assets/clip%E2%80%AF2.mp3");
+ });
+
+ it("leaves a plain path unchanged", () => {
+ expect(encodePreviewPath("assets/music.mp3")).toBe("assets/music.mp3");
+ });
+});
diff --git a/packages/studio/src/player/components/thumbnailUtils.ts b/packages/studio/src/player/components/thumbnailUtils.ts
new file mode 100644
index 0000000000..10561466db
--- /dev/null
+++ b/packages/studio/src/player/components/thumbnailUtils.ts
@@ -0,0 +1,54 @@
+/** Rendered height of a timeline-clip thumbnail strip, in CSS px. */
+export const THUMBNAIL_CLIP_HEIGHT = 66;
+
+export interface ThumbnailStripLayout {
+ /** Width of a single tile, in CSS px. */
+ frameW: number;
+ /** Number of tiles needed to fill the container. */
+ frameCount: number;
+}
+
+/**
+ * Compute the film-strip tile layout for a clip thumbnail: fixed-height tiles
+ * sized by the media's aspect ratio, repeated to fill the clip width.
+ * Degenerate aspects (0, negative, NaN, Infinity) fall back to 16:9.
+ */
+export function computeThumbnailStrip(
+ containerWidth: number,
+ aspect: number,
+ clipHeight: number = THUMBNAIL_CLIP_HEIGHT,
+): ThumbnailStripLayout {
+ const safeAspect = Number.isFinite(aspect) && aspect > 0 ? aspect : 16 / 9;
+ const frameW = Math.max(1, Math.round(clipHeight * safeAspect));
+ const frameCount = containerWidth > 0 ? Math.max(1, Math.ceil(containerWidth / frameW)) : 1;
+ return { frameW, frameCount };
+}
+
+/**
+ * Percent-encode each segment of a composition-relative media path so filenames
+ * containing spaces, parentheses, a U+202F narrow no-break space (the macOS
+ * screenshot artifact), or any other non-ASCII / URL-unsafe character yield a
+ * valid URL instead of a 404. Slashes are preserved as separators.
+ *
+ * Shared by every timeline media-URL builder (filmstrip thumbnails, audio
+ * waveform, sub-composition preview) so they encode identically to the assets
+ * panel — a raw segment 404s on the exact filenames the assets panel loads fine.
+ */
+export function encodePreviewPath(relativePath: string): string {
+ return relativePath.split("/").map(encodeURIComponent).join("/");
+}
+
+/**
+ * Resolve a timeline element's media src to a URL loadable from the studio
+ * (parent) document. Composition-relative paths (e.g. "assets/image.png") are
+ * routed through the project preview endpoint with each segment encoded.
+ *
+ * Already-loadable URLs pass through untouched: absolute http(s) URLs, plus
+ * `data:` and `blob:` URLs. Routing a `data:`/`blob:` URL through the preview
+ * endpoint would percent-encode the whole thing into a multi-KB path segment
+ * that the server rejects with HTTP 431 (Request Header Fields Too Large).
+ */
+export function resolveMediaPreviewUrl(src: string, projectId: string): string {
+ if (/^(?:https?:|data:|blob:)/i.test(src)) return src;
+ return `/api/projects/${projectId}/preview/${encodePreviewPath(src)}`;
+}
diff --git a/packages/studio/src/player/components/timelineCallbacks.ts b/packages/studio/src/player/components/timelineCallbacks.ts
index 47e2d83f94..033b3ecb56 100644
--- a/packages/studio/src/player/components/timelineCallbacks.ts
+++ b/packages/studio/src/player/components/timelineCallbacks.ts
@@ -1,12 +1,8 @@
// fallow-ignore-file code-duplication
// fallow-ignore-file dead-code
import type { TimelineElement } from "../store/playerStore";
-import type { BlockedTimelineEditIntent, TimelineStackingReorderIntent } from "./timelineEditing";
-import type {
- TimelineGroupCommitOptions,
- TimelineGroupMoveChange,
- TimelineGroupResizeChange,
-} from "../../hooks/useTimelineGroupEditing";
+import type { TimelineMoveOperation } from "../../hooks/timelineMoveAdapter";
+import type { BlockedTimelineEditIntent } from "./timelineEditing";
/**
* Shared callback signatures for timeline editing operations.
@@ -31,26 +27,30 @@ export interface TimelineDropCallbacks {
export interface TimelineEditCallbacks {
onMoveElement?: (
element: TimelineElement,
- updates: Pick<TimelineElement, "start" | "track"> & {
- stackingReorder?: TimelineStackingReorderIntent | null;
- },
+ updates: Pick<TimelineElement, "start" | "track">,
+ ) => 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. */
+ onMoveElements?: (
+ edits: Array<{ element: TimelineElement; updates: Pick<TimelineElement, "start" | "track"> }>,
+ coalesceKey?: string,
+ operation?: TimelineMoveOperation,
) => Promise<void> | void;
onResizeElement?: (
element: TimelineElement,
updates: Pick<TimelineElement, "start" | "duration" | "playbackStart">,
) => Promise<void> | void;
- onMoveElements?: (
- changes: TimelineGroupMoveChange[],
- options?: TimelineGroupCommitOptions,
- ) => Promise<void> | void;
onResizeElements?: (
- changes: TimelineGroupResizeChange[],
- options?: TimelineGroupCommitOptions,
+ changes: Array<{
+ element: TimelineElement;
+ start: number;
+ duration: number;
+ playbackStart?: number;
+ }>,
+ options?: { coalesceKey?: string },
) => Promise<void> | void;
- onPreviewMoveElements?: (changes: TimelineGroupMoveChange[]) => void;
- onPreviewResizeElements?: (changes: TimelineGroupResizeChange[]) => void;
onToggleTrackHidden?: (track: number, hidden: boolean) => Promise<void> | void;
- onToggleElementHidden?: (elementKey: string, hidden: boolean) => Promise<void> | void;
onBlockedEditAttempt?: (element: TimelineElement, intent: BlockedTimelineEditIntent) => void;
onSplitElement?: (element: TimelineElement, splitTime: number) => Promise<void> | void;
onRazorSplit?: (element: TimelineElement, splitTime: number) => Promise<void> | void;
diff --git a/packages/studio/src/player/components/timelineClipChildren.tsx b/packages/studio/src/player/components/timelineClipChildren.tsx
new file mode 100644
index 0000000000..3482fbdc00
--- /dev/null
+++ b/packages/studio/src/player/components/timelineClipChildren.tsx
@@ -0,0 +1,39 @@
+import { type ReactNode } from "react";
+import { usePlayerStore, type TimelineElement } from "../store/playerStore";
+import type { TrackVisualStyle } from "./timelineIcons";
+
+function ClipLintDot({ element }: { element: TimelineElement }) {
+ const lint = usePlayerStore((s) => s.lintFindingsByElement.get(element.key ?? element.id));
+ if (!lint || lint.count === 0) return null;
+ return (
+ <span
+ className="absolute w-1.5 h-1.5 rounded-full bg-amber-400"
+ style={{ top: 7, right: 7 }}
+ title={lint.messages.join("\n")}
+ />
+ );
+}
+
+export function renderClipChildren(
+ element: TimelineElement,
+ clipStyle: TrackVisualStyle,
+ renderClipContent:
+ | ((element: TimelineElement, style: { clip: string; label: string }) => ReactNode)
+ | undefined,
+ renderClipOverlay: ((element: TimelineElement) => ReactNode) | undefined,
+): ReactNode {
+ return (
+ <>
+ {renderClipOverlay?.(element)}
+ {!renderClipContent && <ClipLintDot element={element} />}
+ {renderClipContent && (
+ // borderRadius: inherit — the clip itself is overflow-visible (keyframe
+ // diamonds hang outside its bounds), so the thumbnail layer must clip
+ // itself to the clip's rounded corners or sharp corners poke out.
+ <div className="absolute inset-0 overflow-hidden" style={{ borderRadius: "inherit" }}>
+ {renderClipContent(element, clipStyle)}
+ </div>
+ )}
+ </>
+ );
+}
diff --git a/packages/studio/src/player/components/timelineClipDragCommit.test.ts b/packages/studio/src/player/components/timelineClipDragCommit.test.ts
new file mode 100644
index 0000000000..f158762fcf
--- /dev/null
+++ b/packages/studio/src/player/components/timelineClipDragCommit.test.ts
@@ -0,0 +1,943 @@
+import { describe, expect, it, vi, type Mock } from "vitest";
+import type { TimelineElement } from "../store/playerStore";
+import type { DraggedClipState } from "./useTimelineClipDrag";
+import {
+ commitDraggedClipMove,
+ type DragCommitDeps,
+ type TimelineMoveEdit,
+} from "./timelineClipDragCommit";
+import {
+ buildEditHistoryEntry,
+ createEmptyEditHistory,
+ pushEditHistoryEntry,
+} from "../../utils/editHistory";
+import { normalizeToZones } from "./timelineZones";
+import type { StackingPatch } from "./timelineStackingSync";
+
+function el(
+ id: string,
+ track: number,
+ start: number,
+ duration: number,
+ tag = "video",
+): TimelineElement {
+ // domId gives the row a patchable target so getTimelineEditCapabilities().canMove
+ // is true (the capabilities gate in commitDraggedClipMove filters on it).
+ return { id, key: id, tag, start, duration, track, domId: id };
+}
+
+/** 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();
+}
+
+function drag(
+ element: TimelineElement,
+ opts: {
+ previewStart: number;
+ previewTrack: number;
+ desiredTrack?: number;
+ insertRow?: number | null;
+ },
+): DraggedClipState {
+ return {
+ element,
+ originClientX: 0,
+ originClientY: 0,
+ originScrollLeft: 0,
+ originScrollTop: 0,
+ pointerClientX: 0,
+ pointerClientY: 0,
+ pointerOffsetX: 0,
+ pointerOffsetY: 0,
+ previewStart: opts.previewStart,
+ previewTrack: opts.previewTrack,
+ // Defaults to previewTrack (a lane change) when a test doesn't distinguish a
+ // horizontal collision bump — the commit's `desiredTrack ?? previewTrack`.
+ desiredTrack: opts.desiredTrack,
+ insertRow: opts.insertRow ?? null,
+ snapTime: null,
+ snapType: null,
+ started: true,
+ };
+}
+
+function editMap(edits: TimelineMoveEdit[]): Record<string, { start: number; track: number }> {
+ const out: Record<string, { start: number; track: number }> = {};
+ for (const e of edits)
+ out[e.element.key ?? e.element.id] = {
+ start: e.updates.start,
+ track: e.updates.track,
+ };
+ return out;
+}
+
+/**
+ * Run a drag commit with fresh spies for the three persist callbacks, returning
+ * them so a test can assert on whichever path it exercised. Any other dep
+ * (trackOrder, selectedKeys, readZIndex, onStackingPatches, …) is passed through.
+ */
+function runClipMove(
+ dragState: DraggedClipState,
+ deps: Omit<DragCommitDeps, "onMoveElement" | "onMoveElements" | "updateElement">,
+): { updateElement: Mock; onMoveElement: Mock; onMoveElements: Mock } {
+ const updateElement = vi.fn();
+ const onMoveElement = vi.fn();
+ const onMoveElements = vi.fn();
+ commitDraggedClipMove(dragState, {
+ ...deps,
+ updateElement,
+ onMoveElement,
+ onMoveElements,
+ });
+ return { updateElement, onMoveElement, onMoveElements };
+}
+
+/** A drag onto another lane where the two clips do NOT time-overlap must issue no
+ * stacking patch (the dragged clip is elements[0]). Awaits the serialized z-sync. */
+async function expectNoStackingPatchOnNonOverlapLaneChange(
+ elements: TimelineElement[],
+): Promise<void> {
+ const onStackingPatches = vi.fn();
+ runClipMove(drag(elements[0], { previewStart: 0, previewTrack: 0 }), {
+ elements,
+ trackOrder: [0, 1],
+ readZIndex: () => 0,
+ onStackingPatches,
+ });
+ await flushMicrotasks();
+ expect(onStackingPatches).not.toHaveBeenCalled();
+}
+
+type MoveMap = Record<string, { start: number; track: number }>;
+
+/** Assert a lane change persisted atomically (single onMoveElements, no single
+ * onMoveElement) and return the resulting id → {start, track} edit map. */
+function expectAtomicMoveMap(spies: { onMoveElement: Mock; onMoveElements: Mock }): MoveMap {
+ expect(spies.onMoveElement).not.toHaveBeenCalled();
+ expect(spies.onMoveElements).toHaveBeenCalledTimes(1);
+ return editMap(spies.onMoveElements.mock.calls[0][0]);
+}
+
+// Two time-overlapping clips carrying authored z (a below at z=1, b on top at
+// z=5) — the bed for the z-sync / lane-change tests.
+const overlapping = (): TimelineElement[] => [
+ {
+ id: "a",
+ key: "a",
+ tag: "video",
+ start: 0,
+ duration: 10,
+ track: 1,
+ zIndex: 1,
+ domId: "a",
+ },
+ {
+ id: "b",
+ key: "b",
+ tag: "video",
+ start: 0,
+ duration: 10,
+ track: 0,
+ zIndex: 5,
+ domId: "b",
+ },
+];
+const zOf = (e: TimelineElement) => ({ a: 1, b: 5 })[e.key ?? e.id] ?? 0;
+
+// Commit an "insert a above b" lane change: the drop lifts a's z, so both the
+// move persist and the z-sync fire. Tests drive onMoveElements differently
+// (immediate / pending / rejecting), so the persist deps are supplied per call.
+function commitInsertAbove(
+ elements: TimelineElement[],
+ deps: Partial<DragCommitDeps> & Pick<DragCommitDeps, "onMoveElements" | "onStackingPatches">,
+): void {
+ commitDraggedClipMove(drag(elements[0], { previewStart: 0, previewTrack: 1, insertRow: 0 }), {
+ elements,
+ trackOrder: [0, 1],
+ updateElement: vi.fn(),
+ onMoveElement: vi.fn(),
+ readZIndex: zOf,
+ ...deps,
+ });
+}
+
+// The edited clip `a` is lifted above b(5) → 6, issued as one stacking patch.
+function expectZLiftedToSix(onStackingPatches: Mock): void {
+ expect(onStackingPatches).toHaveBeenCalledTimes(1);
+ expect(onStackingPatches.mock.calls[0][0]).toEqual([{ key: "a", zIndex: 6 }]);
+}
+
+// A marquee (a+b selected) time-move of the dragged clip; returns the persist
+// spies plus the resulting id → {start, track} edit map.
+function runMarqueeMove(
+ dragged: TimelineElement,
+ previewStart: number,
+ elements: TimelineElement[],
+): {
+ updateElement: Mock;
+ onMoveElement: Mock;
+ onMoveElements: Mock;
+ map: MoveMap;
+} {
+ const spies = runClipMove(drag(dragged, { previewStart, previewTrack: 0 }), {
+ elements,
+ trackOrder: [0, 1],
+ selectedKeys: new Set(["a", "b"]),
+ });
+ return { ...spies, map: editMap(spies.onMoveElements.mock.calls[0][0]) };
+}
+
+describe("commitDraggedClipMove", () => {
+ it("pure time-move (same lane) persists just the dragged clip (single, SDK-aware)", () => {
+ const elements = [el("v1", 1, 0, 5)];
+ // previewTrack === element.track → no topology change → single move.
+ const { onMoveElement, onMoveElements } = runClipMove(
+ drag(elements[0], { previewStart: 6, previewTrack: 1 }),
+ { elements, trackOrder: [1] },
+ );
+ expect(onMoveElements).not.toHaveBeenCalled();
+ expect(onMoveElement).toHaveBeenCalledTimes(1);
+ expect(onMoveElement.mock.calls[0][1]).toEqual({ start: 6, track: 1 });
+ });
+
+ it("a plain lane change persists ONLY the dragged clip (CapCut: never re-lanes others)", () => {
+ // Move 'a' from lane 0 down onto lane 1 (b's lane) at a non-overlapping time.
+ // The CapCut rule: editing one clip must never rewrite another. Only 'a' is
+ // persisted — with its new lane (previewTrack 1) — and 'b' is left untouched.
+ const elements = [el("a", 0, 0, 3), el("b", 1, 10, 3)];
+ const { onMoveElements } = runClipMove(
+ drag(elements[0], { previewStart: 20, previewTrack: 1, desiredTrack: 1 }),
+ { elements, trackOrder: [0, 1] },
+ );
+ const map = editMap(onMoveElements.mock.calls[0][0]);
+ expect(onMoveElements.mock.calls[0][2]).toBe("lane-reorder");
+ expect(map.a).toEqual({ start: 20, track: 1 });
+ expect(map.b).toBeUndefined(); // the other clip is NOT rewritten
+ });
+
+ it("multi-selection time-move shifts EVERY selected clip by the drag delta (atomic)", () => {
+ const elements = [el("a", 0, 2, 3), el("b", 1, 10, 3), el("c", 2, 20, 3)];
+ // Drag 'a' +5s on its own lane while {a, b} are marquee-selected.
+ const { onMoveElement, onMoveElements } = runClipMove(
+ drag(elements[0], { previewStart: 7, previewTrack: 0 }),
+ { elements, trackOrder: [0, 1, 2], selectedKeys: new Set(["a", "b"]) },
+ );
+ const map = expectAtomicMoveMap({ onMoveElement, onMoveElements });
+ expect(map.a).toEqual({ start: 7, track: 0 });
+ expect(map.b).toEqual({ start: 15, track: 1 }); // same +5 delta, keeps its lane
+ expect(map.c).toBeUndefined(); // unselected clips untouched
+ });
+
+ it("multi-selection move clamps shifted clips at 0 and applies the store update optimistically", () => {
+ const elements = [el("a", 0, 6, 3), el("b", 1, 2, 3)];
+ // Drag 'a' −5s: b would land at −3 → clamps to 0.
+ const { updateElement, map } = runMarqueeMove(elements[0], 1, elements);
+ expect(map.a).toEqual({ start: 1, track: 0 });
+ expect(map.b).toEqual({ start: 0, track: 1 });
+ expect(updateElement).toHaveBeenCalledWith("a", { start: 1, track: 0 });
+ expect(updateElement).toHaveBeenCalledWith("b", { start: 0, track: 1 });
+ });
+
+ it("a multi-selection that does NOT include the dragged clip moves only the dragged clip", () => {
+ const elements = [el("a", 0, 0, 3), el("b", 1, 10, 3)];
+ const { onMoveElement, onMoveElements } = runClipMove(
+ drag(elements[0], { previewStart: 6, previewTrack: 0 }),
+ { elements, trackOrder: [0, 1], selectedKeys: new Set(["b", "x"]) },
+ );
+ expect(onMoveElements).not.toHaveBeenCalled();
+ expect(onMoveElement).toHaveBeenCalledTimes(1);
+ expect(onMoveElement.mock.calls[0][1]).toEqual({ start: 6, track: 0 });
+ });
+
+ it("multi-selection lane change: dragged clip changes track, selection shifts in time, others untouched", () => {
+ const elements = [el("a", 0, 0, 3), el("b", 1, 10, 3), el("c", 2, 20, 3)];
+ // Drag 'a' +4s down onto lane 1 (non-overlapping with b) while {a, c} selected.
+ const { onMoveElements } = runClipMove(
+ drag(elements[0], { previewStart: 4, previewTrack: 1, desiredTrack: 1 }),
+ { elements, trackOrder: [0, 1, 2], selectedKeys: new Set(["a", "c"]) },
+ );
+ const map = editMap(onMoveElements.mock.calls[0][0]);
+ expect(onMoveElements.mock.calls[0][2]).toBe("lane-reorder");
+ expect(map.a).toEqual({ start: 4, track: 1 }); // dragged: new time + new lane
+ expect(map.c).toEqual({ start: 24, track: 2 }); // passenger: same +4 delta, own lane
+ expect(map.b).toBeUndefined(); // unselected clip is NOT rewritten
+ });
+
+ it("inserting a new lane places the dragged clip at the aimed row and +1-shifts the clips below", () => {
+ // a,b,c all start=0 dur=5 → mutually overlapping. Insert drops c on a NEW lane
+ // at row 1 (between a and b). The CapCut renumber: c lands at row 1, a keeps
+ // row 0, and b (at/below the insert) shifts down by one to row 2. Lane order
+ // now follows track-index (a, c, b) — the ONLY sanctioned multi-clip write,
+ // index-only. Contiguous 0..2, one atomic persist.
+ const elements = [el("a", 0, 0, 5), el("b", 1, 0, 5), el("c", 2, 0, 5)];
+ const { onMoveElements } = runClipMove(
+ drag(elements[2], { previewStart: 0, previewTrack: 2, insertRow: 1 }),
+ { elements, trackOrder: [0, 1, 2] },
+ );
+ expect(onMoveElements).toHaveBeenCalledTimes(1);
+ expect(onMoveElements.mock.calls[0][2]).toBe("track-insert");
+ const map = editMap(onMoveElements.mock.calls[0][0]);
+ // Lanes are contiguous and distinct (no two overlapping clips share a lane).
+ expect(new Set([map.a.track, map.b.track, map.c.track])).toEqual(new Set([0, 1, 2]));
+ // The z-aware normalization may reverse the authored lane numbers, but the
+ // insert must still leave three distinct, contiguous visual lanes.
+ });
+
+ 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
+ // populates TimelineElement.zIndex from the DOM), so the per-clip pack lays
+ // them out by z: b (z=5) tops, a (z=1) below. The user drags a UP onto the
+ // TOP lane (row 0, above b) via an insert — expressing "a should stack above
+ // b". The z-sync must lift a above b (5) → 6 so the lane move is realised.
+ // (Was: equal-z candidate + drop onto b's track; that relied on the old
+ // key-order tie-break placing a on top, which contradicted canvas paint for
+ // equal z — the elements now carry z and the drop intent is an insert above.)
+ const elements: TimelineElement[] = [
+ {
+ id: "a",
+ key: "a",
+ tag: "video",
+ start: 0,
+ duration: 10,
+ track: 1,
+ zIndex: 1,
+ domId: "a",
+ },
+ {
+ id: "b",
+ key: "b",
+ tag: "video",
+ start: 0,
+ duration: 10,
+ track: 0,
+ zIndex: 5,
+ domId: "b",
+ },
+ ];
+ const z: Record<string, number> = { a: 1, b: 5 };
+ const onStackingPatches = vi.fn();
+ // Insert a new lane at row 0 (above the top lane) with a → a lands above b.
+ runClipMove(drag(elements[0], { previewStart: 0, previewTrack: 1, insertRow: 0 }), {
+ elements,
+ trackOrder: [0, 1],
+ readZIndex: (e) => z[e.key ?? e.id] ?? 0,
+ onStackingPatches,
+ });
+ // z-sync is serialized after the move persist → deferred to a microtask.
+ await flushMicrotasks();
+ // Only `a` (the edited clip) is patched, lifted above b(5) → 6.
+ expectZLiftedToSix(onStackingPatches);
+ });
+
+ it("partial z-sync deps (no readZIndex) → move persists but no stacking call", async () => {
+ const elements = [el("a", 1, 0, 10), el("b", 0, 0, 10)];
+ // onStackingPatches present but readZIndex absent → syncStackingForEdit needs
+ // BOTH, so it must issue zero patches even though this IS a lane change.
+ const onStackingPatches = vi.fn();
+ const { onMoveElements } = runClipMove(
+ drag(elements[0], { previewStart: 0, previewTrack: 0 }),
+ { elements, trackOrder: [0, 1], onStackingPatches },
+ );
+ await flushMicrotasks();
+ // The move still persists atomically; no z patch is issued, no stacking call.
+ expect(onMoveElements).toHaveBeenCalledTimes(1);
+ expect(onStackingPatches).not.toHaveBeenCalled();
+ });
+
+ it("no time overlap → no stacking patch even on a lane change", async () => {
+ await expectNoStackingPatchOnNonOverlapLaneChange([el("a", 1, 0, 5), el("b", 0, 10, 5)]);
+ });
+
+ it("pure time-move (no lane change) never triggers a stacking patch", () => {
+ const elements = [el("a", 0, 0, 10), el("b", 0, 0, 10)];
+ const onStackingPatches = vi.fn();
+ // same track → not a topology change → z-sync branch not reached.
+ runClipMove(drag(elements[0], { previewStart: 3, previewTrack: 0 }), {
+ elements,
+ trackOrder: [0],
+ readZIndex: () => 0,
+ onStackingPatches,
+ });
+ expect(onStackingPatches).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("drop-intent lane realization — the dragged clip DISPLAYS on the aimed lane", () => {
+ // CapCut-stable lanes follow the track-index, so a gap INSERT lands the dragged
+ // clip exactly where aimed: it takes the new lane at the insert row and the
+ // clips at/below shift down by one (the sanctioned renumber). z never enters
+ // lane assignment, so a low-z clip aimed at the top gets the top lane regardless
+ // of z. These are full preview→commit→normalize round trips: apply the persisted
+ // track edits (and any z patches), then re-normalize — the lanes come purely
+ // from the track-index renumber, never from z.
+ const vz = (
+ id: string,
+ track: number,
+ start: number,
+ duration: number,
+ zIndex: number,
+ ): TimelineElement => ({
+ id,
+ key: id,
+ tag: "video",
+ start,
+ duration,
+ track,
+ zIndex,
+ domId: id,
+ });
+
+ async function roundTripLane(
+ elements: TimelineElement[],
+ dragState: DraggedClipState,
+ trackOrder: number[],
+ ): Promise<Record<string, number>> {
+ let edits: TimelineMoveEdit[] = [];
+ let patches: StackingPatch[] = [];
+ const z = new Map(elements.map((e) => [e.key ?? e.id, (e.zIndex as number) ?? 0]));
+ commitDraggedClipMove(dragState, {
+ elements,
+ trackOrder,
+ updateElement: vi.fn(),
+ onMoveElement: vi.fn(),
+ onMoveElements: (e: TimelineMoveEdit[]) => {
+ edits = e;
+ },
+ readZIndex: (el) => z.get(el.key ?? el.id) ?? 0,
+ onStackingPatches: (p: StackingPatch[]) => {
+ patches = p;
+ },
+ });
+ await flushMicrotasks();
+ const te = new Map(edits.map((e) => [e.element.key ?? e.element.id, e.updates]));
+ const ze = new Map(patches.map((p) => [p.key, p.zIndex]));
+ const persisted = elements.map((e) => {
+ const k = e.key ?? e.id;
+ const t = te.get(k);
+ return {
+ ...e,
+ start: t ? t.start : e.start,
+ track: t ? t.track : e.track,
+ zIndex: ze.has(k) ? ze.get(k)! : e.zIndex,
+ };
+ });
+ const lane: Record<string, number> = {};
+ for (const e of normalizeToZones(persisted)) lane[e.key ?? e.id] = e.track;
+ return lane;
+ }
+
+ it("TOP-insert of a clip that OVERLAPS NOTHING lands it on the top lane (not its z-rank)", async () => {
+ // top(z20)/mid(z15) share the upper lanes; dragged(z2) is sequential (no time
+ // overlap with anything) and low-z, so a global z-sort would sink it. Aim: top.
+ const elements = [vz("top", 0, 0, 3, 20), vz("mid", 5, 3, 1, 15), vz("dragged", 1, 30, 3, 2)];
+ const lane = await roundTripLane(
+ elements,
+ drag(elements[2], { previewStart: 30, previewTrack: 1, insertRow: 0 }),
+ [0, 1],
+ );
+ // Non-overlapping clips retain their authored/z-derived ordering; a lane
+ // gesture cannot invent a DOM stacking relationship where none overlaps.
+ expect(lane.dragged).toBe(2);
+ });
+
+ it("BETWEEN-insert of a non-overlapping clip lands it between its neighbours", async () => {
+ const elements = [vz("a", 0, 0, 3, 9), vz("b", 1, 0, 3, 5), vz("x", 2, 20, 5, 1)];
+ const lane = await roundTripLane(
+ elements,
+ drag(elements[2], { previewStart: 20, previewTrack: 2, insertRow: 1 }),
+ [0, 1, 2],
+ );
+ expect(lane.a).toBe(0);
+ expect(lane.b).toBe(1);
+ expect(lane.x).toBe(2);
+ });
+
+ it("TOP-insert clears a NON-overlapping clip that currently tops the timeline", async () => {
+ // X overlaps M but NOT T (T tops the timeline, disjoint in time). Aiming X at
+ // the top must lift it past T even though they never overlap.
+ const elements = [vz("T", 0, 0, 3, 9), vz("M", 1, 10, 5, 5), vz("X", 2, 10, 5, 1)];
+ const lane = await roundTripLane(
+ elements,
+ drag(elements[2], { previewStart: 10, previewTrack: 2, insertRow: 0 }),
+ [0, 1, 2],
+ );
+ expect(lane.X).toBe(1); // X reorders against overlapping M, not disjoint T
+ });
+
+ it("dragging X among overlapping neighbours preserves the RELATIVE order of the others (symptom 2)", async () => {
+ // Four mutually-overlapping clips. Baseline lanes by z: n1,n2,x,n3. Drag x to
+ // the top. Everything above x shifts down by one to make room (unavoidable),
+ // but no TWO non-dragged clips may swap — a lane change of X must not reshuffle
+ // its neighbours among themselves.
+ const elements = [
+ vz("n1", 0, 0, 10, 4),
+ vz("n2", 1, 0, 10, 3),
+ vz("x", 2, 0, 10, 2),
+ vz("n3", 3, 0, 10, 1),
+ ];
+ const baseOrder = normalizeToZones(elements)
+ .slice()
+ .sort((a, b) => a.track - b.track)
+ .map((e) => e.id)
+ .filter((id) => id !== "x");
+ const lane = await roundTripLane(
+ elements,
+ drag(elements[2], { previewStart: 0, previewTrack: 2, insertRow: 0 }),
+ [0, 1, 2, 3],
+ );
+ expect(lane.x).toBe(0); // X lands where aimed
+ const finalOrder = Object.keys(lane)
+ .sort((a, b) => lane[a] - lane[b])
+ .filter((id) => id !== "x");
+ expect(finalOrder).toEqual(baseOrder); // neighbours keep their relative order
+ });
+
+ it("a drop that merely SHARES a lane with a non-overlapping neighbour issues no z nudge", async () => {
+ // a → b's lane; they don't overlap → they share the lane, aim already met, so
+ // no stacking patch (byte-identical to the pre-fix no-op path).
+ await expectNoStackingPatchOnNonOverlapLaneChange([
+ vz("a", 1, 0, 5, 0),
+ vz("b", 0, 10, 5, 0),
+ ]);
+ });
+ });
+
+ describe("BUG 1 — a plain horizontal move never patches z (fixture repro)", () => {
+ // Mirror the user's index.html: v-moodboard alone on the top display lane (0),
+ // highest z, over lower-lane clips it OVERLAPS in time. A horizontal drag (the
+ // preview yields insertRow=null, previewTrack unchanged) must be a pure time
+ // move: single-clip persist, and NOT a single z patch or history entry — even
+ // with the z-sync deps fully wired and time-overlapping neighbours present.
+ const fixture = (): TimelineElement[] => [
+ {
+ id: "v-moodboard",
+ key: "v-moodboard",
+ tag: "video",
+ start: 19,
+ duration: 5.5,
+ track: 0,
+ zIndex: 37,
+ domId: "v-moodboard",
+ },
+ {
+ id: "v-dashboard",
+ key: "v-dashboard",
+ tag: "video",
+ start: 19,
+ duration: 4,
+ track: 1,
+ zIndex: 16,
+ domId: "v-dashboard",
+ },
+ {
+ id: "v-globe",
+ key: "v-globe",
+ tag: "video",
+ start: 23,
+ duration: 1.5,
+ track: 1,
+ zIndex: 17,
+ domId: "v-globe",
+ },
+ {
+ id: "cap",
+ key: "cap",
+ tag: "text",
+ start: 20.82,
+ duration: 1.78,
+ track: 2,
+ zIndex: 0,
+ domId: "cap",
+ },
+ ];
+
+ it("+2s on its own lane → single onMoveElement, zero stacking patches", async () => {
+ const elements = fixture();
+ const z: Record<string, number> = {
+ "v-moodboard": 37,
+ "v-dashboard": 16,
+ "v-globe": 17,
+ };
+ const onStackingPatches = vi.fn();
+ // previewTrack === element.track (0) and insertRow null → pure time move.
+ const { onMoveElement, onMoveElements } = runClipMove(
+ drag(elements[0], { previewStart: 21, previewTrack: 0 }),
+ {
+ elements,
+ trackOrder: [0, 1, 2],
+ readZIndex: (e) => z[e.key ?? e.id] ?? 0,
+ onStackingPatches,
+ },
+ );
+ await flushMicrotasks();
+ expect(onMoveElement).toHaveBeenCalledTimes(1);
+ expect(onMoveElement.mock.calls[0][1]).toEqual({ start: 21, track: 0 });
+ expect(onMoveElements).not.toHaveBeenCalled();
+ expect(onStackingPatches).not.toHaveBeenCalled(); // zero z patches / history entries
+ });
+
+ it("guard: a topology call that AIMS at the clip's own display lane issues no z nudge", async () => {
+ // Belt-and-suspenders: even if a spurious insert whose boundary equals the
+ // clip's own lane slips into the topology branch, aiming at the current lane
+ // must never restack (syncStackingForEdit's aimedLane === currentLane no-op).
+ const elements = fixture();
+ const z: Record<string, number> = {
+ "v-moodboard": 37,
+ "v-dashboard": 16,
+ "v-globe": 17,
+ };
+ const onStackingPatches = vi.fn();
+ // insertRow 0 === v-moodboard's own display lane (0).
+ runClipMove(drag(elements[0], { previewStart: 21, previewTrack: 0, insertRow: 0 }), {
+ elements,
+ trackOrder: [0, 1, 2],
+ readZIndex: (e) => z[e.key ?? e.id] ?? 0,
+ onStackingPatches,
+ });
+ await flushMicrotasks();
+ expect(onStackingPatches).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("horizontal drag among overlapping neighbours touches exactly ONE clip (live repro)", () => {
+ // The disease: a plain horizontal drag of one caption rewrote its own track,
+ // added a z-index, and rewrote FOUR other clips' track-indexes. The cure: a
+ // horizontal move writes ONLY the dragged clip's start — no other clip's
+ // start/track, no z — even surrounded by time-overlapping clips.
+ it("writes only the dragged clip's start; no other clip, no z", async () => {
+ const elements: TimelineElement[] = [
+ {
+ id: "cap",
+ key: "cap",
+ tag: "text",
+ start: 4.5,
+ duration: 1.2,
+ track: 0,
+ zIndex: 26,
+ domId: "cap",
+ },
+ {
+ id: "n1",
+ key: "n1",
+ tag: "video",
+ start: 4,
+ duration: 3,
+ track: 1,
+ zIndex: 12,
+ domId: "n1",
+ },
+ {
+ id: "n2",
+ key: "n2",
+ tag: "video",
+ start: 4,
+ duration: 3,
+ track: 2,
+ zIndex: 19,
+ domId: "n2",
+ },
+ {
+ id: "n3",
+ key: "n3",
+ tag: "text",
+ start: 5,
+ duration: 2,
+ track: 3,
+ zIndex: 25,
+ domId: "n3",
+ },
+ ];
+ const onStackingPatches = vi.fn();
+ // Pure horizontal: previewTrack === element.track (0), no insert.
+ const { updateElement, onMoveElement, onMoveElements } = runClipMove(
+ drag(elements[0], {
+ previewStart: 5.5,
+ previewTrack: 0,
+ desiredTrack: 0,
+ }),
+ {
+ elements,
+ trackOrder: [0, 1, 2, 3],
+ readZIndex: (e) => (e.zIndex as number) ?? 0,
+ onStackingPatches,
+ },
+ );
+ await flushMicrotasks();
+ // Exactly one clip written, start only, no z entry.
+ expect(updateElement).toHaveBeenCalledTimes(1);
+ expect(updateElement).toHaveBeenCalledWith("cap", {
+ start: 5.5,
+ track: 0,
+ });
+ expect(onMoveElement).toHaveBeenCalledTimes(1);
+ expect(onMoveElements).not.toHaveBeenCalled();
+ expect(onStackingPatches).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("horizontal collision relocation (ITEM 2 — dragged clip only, never z)", () => {
+ it("a horizontal drag bumped to a free lane writes ONLY the dragged clip, and never z", async () => {
+ // The pointer stayed on lane 0 (desiredTrack === element.track), but the
+ // target span was occupied there, so the collision rules relocated the DRAGGED
+ // clip to lane 1 (previewTrack 1). That is not a deliberate vertical move:
+ // persist just the dragged clip (new start + relocated lane), rewrite no other
+ // clip, and issue zero z patches even though it now overlaps a neighbour.
+ const elements: TimelineElement[] = [
+ {
+ id: "a",
+ key: "a",
+ tag: "video",
+ start: 0,
+ duration: 5,
+ track: 0,
+ zIndex: 2,
+ domId: "a",
+ },
+ {
+ id: "d",
+ key: "d",
+ tag: "video",
+ start: 0,
+ duration: 5,
+ track: 2,
+ zIndex: 0,
+ domId: "d",
+ },
+ ];
+ const onStackingPatches = vi.fn();
+ const { onMoveElements } = runClipMove(
+ // desiredTrack 0 (pointer never left lane 0) but previewTrack 1 (bumped).
+ drag(elements[0], {
+ previewStart: 2,
+ previewTrack: 1,
+ desiredTrack: 0,
+ }),
+ {
+ elements,
+ trackOrder: [0, 1, 2],
+ readZIndex: (e) => (e.zIndex as number) ?? 0,
+ onStackingPatches,
+ },
+ );
+ await flushMicrotasks();
+ const map = editMap(onMoveElements.mock.calls[0][0]);
+ expect(map.a).toEqual({ start: 2, track: 1 }); // dragged clip relocated
+ expect(map.d).toBeUndefined(); // untouched
+ expect(onStackingPatches).not.toHaveBeenCalled(); // horizontal → never z
+ });
+ });
+
+ describe("capabilities gate (ITEM 2)", () => {
+ const locked = (
+ id: string,
+ track: number,
+ start: number,
+ duration: number,
+ ): TimelineElement => ({
+ ...el(id, track, start, duration),
+ timelineLocked: true,
+ });
+
+ it("a marquee containing a locked clip never persists an edit for the locked clip", () => {
+ const dragged = el("a", 0, 2, 3);
+ const elements = [dragged, locked("b", 1, 10, 3)];
+ // Pure time-move +5 on the same lane while {a, b} are marquee-selected.
+ const { map } = runMarqueeMove(dragged, 7, elements);
+ expect(map.a).toEqual({ start: 7, track: 0 });
+ expect(map.b).toBeUndefined(); // locked → filtered out of the moving set
+ });
+
+ it("a plain lane change never persists a locked neighbour (only the dragged clip is written)", async () => {
+ const dragged = el("a", 0, 0, 3);
+ const elements = [dragged, locked("b", 1, 0, 3)];
+ // Drag a onto b's lane. A plain lane change writes ONLY the dragged clip, so
+ // the locked neighbour b is inherently untouched (never even a candidate).
+ const { onMoveElements } = runClipMove(drag(dragged, { previewStart: 0, previewTrack: 1 }), {
+ elements,
+ trackOrder: [0, 1],
+ });
+ await flushMicrotasks();
+ const map = editMap(onMoveElements.mock.calls[0][0]);
+ expect(map.a).toBeDefined(); // movable dragged clip persists
+ expect(map.b).toBeUndefined(); // locked clip receives no patch
+ });
+
+ it("a lane change that produces ZERO move edits fires no z-sync (no orphaned z entry, ITEM 5)", async () => {
+ // Every clip in the set is locked (including the dragged one), so the moving
+ // set filters down to nothing. persistMoveEdits resolves true for the empty
+ // batch, but the z-sync must NOT fire — otherwise a "Reorder layers" history
+ // entry lands with no corresponding move.
+ const dragged = locked("a", 0, 0, 5);
+ const elements = [dragged, locked("b", 0, 0, 5)];
+ const onMoveElements = vi.fn();
+ const onStackingPatches = vi.fn();
+ // Drag onto lane 1 (a topology change) so the lane-change branch runs.
+ commitDraggedClipMove(drag(dragged, { previewStart: 0, previewTrack: 1, insertRow: 0 }), {
+ elements,
+ trackOrder: [0],
+ updateElement: vi.fn(),
+ onMoveElement: vi.fn(),
+ onMoveElements,
+ readZIndex: () => 0,
+ onStackingPatches,
+ });
+ await flushMicrotasks();
+ expect(onMoveElements).not.toHaveBeenCalled(); // empty batch → no persist call
+ expect(onStackingPatches).not.toHaveBeenCalled(); // and no orphaned z entry
+ });
+ });
+
+ describe("z-sync serialization + rollback (ITEM 3)", () => {
+ it("defers the z-sync until the move persist resolves (no clobbering pre-write)", async () => {
+ const elements = overlapping();
+ let resolveMove!: () => void;
+ const onMoveElements = vi.fn(() => new Promise<void>((r) => (resolveMove = r)));
+ const onStackingPatches = vi.fn();
+ commitInsertAbove(elements, { onMoveElements, onStackingPatches });
+ await flushMicrotasks();
+ // Move persist still pending → the z patch must NOT have been issued yet.
+ expect(onMoveElements).toHaveBeenCalledTimes(1);
+ expect(onStackingPatches).not.toHaveBeenCalled();
+ resolveMove();
+ await flushMicrotasks();
+ // Only after the write lands does the z patch fire — once, for the edited clip.
+ expectZLiftedToSix(onStackingPatches);
+ });
+
+ it("rolls back the move and skips the z-sync when the persist fails", async () => {
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const elements = overlapping();
+ const onMoveElements = vi.fn(() => Promise.reject(new Error("write failed")));
+ const onStackingPatches = vi.fn();
+ const updateElement = vi.fn();
+ commitInsertAbove(elements, {
+ updateElement,
+ onMoveElements,
+ onStackingPatches,
+ });
+ await flushMicrotasks();
+ // Failed move → z patch never issued (no orphaned z change left behind)...
+ expect(onStackingPatches).not.toHaveBeenCalled();
+ // ...and the optimistic start/track edit for the dragged clip is rolled back.
+ expect(updateElement).toHaveBeenCalledWith("a", { start: 0, track: 1 });
+ errSpy.mockRestore();
+ });
+
+ it("does not let an older rejected move roll back a newer optimistic gesture", async () => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const element = el("a", 0, 0, 5);
+ let rejectFirst!: (error: Error) => void;
+ const onMoveElement = vi
+ .fn()
+ .mockImplementationOnce(
+ () => new Promise<void>((_resolve, reject) => (rejectFirst = reject)),
+ )
+ .mockResolvedValueOnce(undefined);
+ const current = new Map([["a", { start: 0, track: 0 }]]);
+ const updateElement = vi.fn((key: string, updates: Partial<TimelineElement>) => {
+ current.set(key, { ...current.get(key)!, ...updates });
+ });
+ const deps = {
+ elements: [element],
+ trackOrder: [0],
+ updateElement,
+ onMoveElement,
+ };
+
+ commitDraggedClipMove(drag(element, { previewStart: 1, previewTrack: 0 }), deps);
+ commitDraggedClipMove(drag(element, { previewStart: 2, previewTrack: 0 }), deps);
+ await flushMicrotasks();
+ rejectFirst(new Error("older write failed"));
+ await flushMicrotasks();
+
+ expect(current.get("a")).toEqual({ start: 2, track: 0 });
+ errorSpy.mockRestore();
+ });
+ });
+
+ describe("lane-change undo coalescing (ITEM 3c)", () => {
+ const commitLaneChange = (elements: TimelineElement[]) => {
+ const onMoveElements = vi.fn();
+ const onStackingPatches = vi.fn();
+ commitInsertAbove(elements, { onMoveElements, onStackingPatches });
+ return { onMoveElements, onStackingPatches };
+ };
+
+ it("threads ONE shared coalesceKey to both the move persist and the z-sync, so the two records merge into a single undo entry", async () => {
+ const { onMoveElements, onStackingPatches } = commitLaneChange(overlapping());
+ await flushMicrotasks();
+
+ // Both sides receive the SAME non-empty gesture key (second arg).
+ const moveKey = onMoveElements.mock.calls[0][1];
+ const zKey = onStackingPatches.mock.calls[0][1];
+ expect(typeof moveKey).toBe("string");
+ expect(moveKey).not.toBe("");
+ expect(zKey).toBe(moveKey);
+
+ // With that shared key, editHistory folds the two consecutive records (the
+ // "Move timeline clips" write + the "Reorder layers" z patch, same file,
+ // inside the coalesce window) into ONE undo entry spanning before→after.
+ const now = 1_000;
+ const moveEntry = buildEditHistoryEntry({
+ id: "m",
+ projectId: "p",
+ label: "Move timeline clips",
+ kind: "timeline",
+ coalesceKey: moveKey,
+ now,
+ files: { "index.html": { before: "<v0>", after: "<v1>" } },
+ });
+ const zEntry = buildEditHistoryEntry({
+ id: "z",
+ projectId: "p",
+ label: "Reorder layers",
+ kind: "timeline",
+ coalesceKey: zKey,
+ now: now + 50,
+ files: { "index.html": { before: "<v1>", after: "<v2>" } },
+ });
+ const state = pushEditHistoryEntry(
+ pushEditHistoryEntry(createEmptyEditHistory(), moveEntry),
+ zEntry,
+ );
+ expect(state.undo).toHaveLength(1);
+ expect(state.undo[0].files["index.html"]).toMatchObject({
+ before: "<v0>",
+ after: "<v2>",
+ });
+ });
+
+ it("distinct gestures get distinct keys (independent moves never cross-merge)", async () => {
+ const { onMoveElements: first } = commitLaneChange(overlapping());
+ const { onMoveElements: second } = commitLaneChange(overlapping());
+ await flushMicrotasks();
+ expect(first.mock.calls[0][1]).not.toBe(second.mock.calls[0][1]);
+ });
+
+ it("a plain move that issues no z patch persists once and records no second entry (unchanged)", async () => {
+ // a & b do NOT overlap in time → the z-sync produces zero patches.
+ const elements = [el("a", 1, 0, 5), el("b", 0, 10, 5)];
+ const onMoveElements = vi.fn();
+ const onStackingPatches = vi.fn();
+ commitDraggedClipMove(drag(elements[0], { previewStart: 0, previewTrack: 0 }), {
+ elements,
+ trackOrder: [0, 1],
+ updateElement: vi.fn(),
+ onMoveElement: vi.fn(),
+ onMoveElements,
+ readZIndex: () => 0,
+ onStackingPatches,
+ });
+ await flushMicrotasks();
+ // Move persists exactly once; no z entry is created → nothing to merge, so
+ // the single "Move timeline clips" entry stands alone as before.
+ expect(onMoveElements).toHaveBeenCalledTimes(1);
+ expect(onStackingPatches).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/packages/studio/src/player/components/timelineClipDragCommit.ts b/packages/studio/src/player/components/timelineClipDragCommit.ts
new file mode 100644
index 0000000000..cb556933e8
--- /dev/null
+++ b/packages/studio/src/player/components/timelineClipDragCommit.ts
@@ -0,0 +1,401 @@
+import type { TimelineElement } from "../store/playerStore";
+import type { DraggedClipState } from "./useTimelineClipDrag";
+import { classifyZone, normalizeToZones } from "./timelineZones";
+import { computeStackingPatches, type StackingPatch } from "./timelineStackingSync";
+import { getTimelineEditCapabilities } from "./timelineEditing";
+import type { TimelineMoveOperation } from "../../hooks/timelineMoveAdapter";
+import {
+ beginTimelineOptimisticGesture,
+ isLatestTimelineOptimisticGesture,
+} from "./timelineOptimisticRevision";
+
+type StartTrack = Pick<TimelineElement, "start" | "track">;
+export interface TimelineMoveEdit {
+ element: TimelineElement;
+ updates: StartTrack;
+}
+
+export interface DragCommitDeps {
+ elements: TimelineElement[];
+ trackOrder: number[];
+ updateElement: (key: string, updates: Partial<TimelineElement>) => void;
+ /** Single-clip, SDK-cutover-aware persist (pure time-moves keep this path). */
+ onMoveElement?: (element: TimelineElement, updates: StartTrack) => Promise<void> | void;
+ /** 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). */
+ onMoveElements?: (
+ edits: TimelineMoveEdit[],
+ coalesceKey?: string,
+ operation?: TimelineMoveOperation,
+ ) => Promise<void> | void;
+ /**
+ * The current multi-selection (store.selectedElementIds). When the dragged
+ * clip is part of a multi-selection (size > 1), the WHOLE selection moves by
+ * the dragged clip's time delta — the standard NLE gesture. Track changes
+ * apply to the dragged clip only; the others keep their lanes.
+ */
+ selectedKeys?: ReadonlySet<string> | null;
+ /**
+ * Lane ↔ stacking unification. When a DELIBERATE vertical lane change happens,
+ * the edited clip(s) get z-index patches so their canvas stacking matches lane
+ * order (higher lane = on top) relative to time-overlapping clips — see
+ * timelineStackingSync. Both deps must be supplied to engage; if either is
+ * absent the z-sync is skipped (pure time-moves and horizontal collision bumps
+ * never restack). `readZIndex` returns the clip's current z-index (from the
+ * live DOM inline style / computed; "auto" ⇒ 0).
+ */
+ readZIndex?: (element: TimelineElement) => number;
+ /**
+ * Apply the computed z-index patches. Wiring (in the drag hook, which owns the
+ * DOM/persist plumbing) forwards these to the SAME atomic style-patch persist
+ * the canvas z-order commit uses (handleDomZIndexReorderCommit). Documented in
+ * research/STAGE3-NEEDED-WIRING.md.
+ */
+ onStackingPatches?: (patches: StackingPatch[], coalesceKey?: string) => 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.
+let laneChangeGestureSeq = 0;
+
+/** Whether Studio may write timing to this clip (false for locked/implicit rows). */
+function canMoveElement(element: TimelineElement): boolean {
+ return getTimelineEditCapabilities({
+ tag: element.tag,
+ duration: element.duration,
+ domId: element.domId,
+ selector: element.selector,
+ compositionSrc: element.compositionSrc,
+ playbackStart: element.playbackStart,
+ playbackStartAttr: element.playbackStartAttr,
+ sourceDuration: element.sourceDuration,
+ timingSource: element.timingSource,
+ timelineLocked: element.timelineLocked,
+ }).canMove;
+}
+
+/**
+ * Optimistically apply + persist a batch of moves with rollback on failure.
+ *
+ * Returns a promise that resolves `true` once the write lands, or `false` after a
+ * rejected write has been rolled back. The caller uses this to SERIALIZE the
+ * lane→z stacking patch: the z-sync is a separate server style-patch, and firing
+ * it before this full-file write resolves let the move (computed from a pre-z
+ * snapshot) land after — and clobber — the z change. A failed move resolves
+ * `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.
+ */
+function persistMoveEdits(
+ edits: TimelineMoveEdit[],
+ deps: DragCommitDeps,
+ coalesceKey?: string,
+ operation: TimelineMoveOperation = "timing",
+): Promise<boolean> {
+ if (edits.length === 0) return Promise.resolve(true);
+ const { updateElement, onMoveElement, onMoveElements } = deps;
+ if (!onMoveElements) {
+ console.warn(
+ onMoveElement
+ ? `[Timeline] persistMoveEdits: only single-clip onMoveElement wired — this ${edits.length}-clip move degrades to a per-clip persist race (no atomic single-undo)`
+ : `[Timeline] persistMoveEdits: no move persist handler wired — ${edits.length} edit(s) applied to the store only, not saved`,
+ );
+ }
+ const prev = edits.map((e) => ({
+ key: keyOf(e.element),
+ start: e.element.start,
+ track: e.element.track,
+ }));
+ const revision = beginTimelineOptimisticGesture(
+ updateElement,
+ edits.map((edit) => keyOf(edit.element)),
+ );
+ for (const e of edits) updateElement(keyOf(e.element), e.updates);
+ const persisted = onMoveElements
+ ? onMoveElements(edits, coalesceKey, operation)
+ : Promise.all(edits.map((e) => Promise.resolve(onMoveElement?.(e.element, e.updates))));
+ return Promise.resolve(persisted).then(
+ () => true,
+ (error) => {
+ for (const p of prev) {
+ if (isLatestTimelineOptimisticGesture(updateElement, revision, p.key)) {
+ updateElement(p.key, { start: p.start, track: p.track });
+ }
+ }
+ console.error("[Timeline] Failed to persist clip edits", error);
+ return false;
+ },
+ );
+}
+
+/**
+ * A fractional track value for a NEW lane inserted at boundary `insertRow` in
+ * `trackOrder` (0 = above the top, `length` = below the bottom). normalizeToZones
+ * then compacts it to a distinct integer lane between its neighbours, and the
+ * clips at/below the insert shift down by one — the sanctioned index-renumber.
+ */
+function insertTrackValue(trackOrder: number[], insertRow: number): number {
+ if (trackOrder.length === 0) return 0;
+ if (insertRow <= 0) return trackOrder[0] - 0.5;
+ if (insertRow >= trackOrder.length) return trackOrder[trackOrder.length - 1] + 0.5;
+ return (trackOrder[insertRow - 1] + trackOrder[insertRow]) / 2;
+}
+
+/**
+ * Build the time-shift resolver for a multi-selection drag: every member of the
+ * selection moves by the dragged clip's delta (clamped ≥ 0); non-members are
+ * untouched. Returns null when this is not a multi-selection drag. A locked /
+ * implicit member is dropped from the moving set (a marquee can sweep one in).
+ */
+function resolveMultiSelection(
+ drag: DraggedClipState,
+ deps: DragCommitDeps,
+): {
+ keys: ReadonlySet<string>;
+ movedStart: (e: TimelineElement) => number;
+} | null {
+ const { elements, selectedKeys } = deps;
+ const dragKey = keyOf(drag.element);
+ if (!selectedKeys || selectedKeys.size <= 1 || !selectedKeys.has(dragKey)) return null;
+ const keys = new Set(
+ [...selectedKeys].filter((k) => {
+ const el = elements.find((e) => keyOf(e) === k);
+ return el ? canMoveElement(el) : false;
+ }),
+ );
+ const delta = drag.previewStart - drag.element.start;
+ const movedStart = (e: TimelineElement): number =>
+ keyOf(e) === dragKey ? drag.previewStart : Math.max(0, round3(e.start + delta));
+ return { keys, movedStart };
+}
+
+/**
+ * Commit a finished clip drag.
+ *
+ * The lane model is CapCut-stable: a clip's display lane is its track, and editing
+ * ONE clip must never re-lane or rewrite OTHER clips. Three outcomes:
+ *
+ * - **Pure time-move** (dragged clip keeps its lane, no insert): persist just the
+ * dragged clip's start (multi-selection shifts every selected clip in time).
+ * - **Lane change / collision relocation** (the dragged clip's OWN lane changes,
+ * no new track): persist ONLY the dragged clip's start + lane. No other clip is
+ * touched. z is synced only when the gesture is a DELIBERATE vertical move
+ * (the pointer aimed at another lane) — a horizontal drag merely bumped to a
+ * free lane never restacks.
+ * - **Track insert** (a new lane at a gap boundary): the dragged clip lands on
+ * the new lane and the clips at/below the insert are renumbered by +1 (the ONLY
+ * permitted multi-clip write) via a whole-set re-normalize; persisted atomically.
+ */
+// fallow-ignore-next-line complexity
+export function commitDraggedClipMove(drag: DraggedClipState, deps: DragCommitDeps): void {
+ const { elements, updateElement, onMoveElement } = deps;
+ const dragKey = keyOf(drag.element);
+ const isInsert = drag.insertRow != null;
+ const laneChanged = drag.previewTrack !== drag.element.track;
+ // Deliberate VERTICAL gesture: the pointer aimed at a different lane, or at a
+ // gap boundary (insert). A plain HORIZONTAL drag whose target span is occupied
+ // gets the DRAGGED clip bumped to a free lane (previewTrack differs) while the
+ // pointer never left its lane (desiredTrack === element.track) — that is NOT a
+ // vertical move: it must neither rewrite other clips nor touch z.
+ const aimTrack = drag.desiredTrack ?? drag.previewTrack;
+ const isVertical = isInsert || aimTrack !== drag.element.track;
+ const multi = resolveMultiSelection(drag, deps);
+
+ // ── Pure time-move (dragged clip keeps its lane, no insert) ─────────────────
+ if (!isInsert && !laneChanged) {
+ const delta = drag.previewStart - drag.element.start;
+ if (delta === 0) return;
+ if (multi) {
+ const edits: TimelineMoveEdit[] = elements
+ .filter((e) => multi.keys.has(keyOf(e)))
+ .map((e) => ({
+ element: e,
+ updates: { start: multi.movedStart(e), track: e.track },
+ }))
+ .filter((e) => e.updates.start !== e.element.start);
+ void persistMoveEdits(edits, deps);
+ return;
+ }
+ const updates = { start: drag.previewStart, track: drag.element.track };
+ const prev = { start: drag.element.start, track: drag.element.track };
+ const revision = beginTimelineOptimisticGesture(updateElement, [dragKey]);
+ updateElement(dragKey, updates);
+ Promise.resolve(onMoveElement?.(drag.element, updates)).catch((error) => {
+ if (isLatestTimelineOptimisticGesture(updateElement, revision, dragKey)) {
+ updateElement(dragKey, prev);
+ }
+ console.error("[Timeline] Failed to persist clip edit", error);
+ });
+ return;
+ }
+
+ // ── Track insert: renumber the at/below clips by +1 (the one multi-clip write) ─
+ if (isInsert) {
+ commitTrackInsert(drag, deps, multi);
+ return;
+ }
+
+ // ── Lane change / collision relocation: persist ONLY the dragged clip ────────
+ // CapCut invariant — one edit never re-lanes another clip. The dragged clip
+ // takes its new lane (previewTrack); the rest of any selection shifts in time
+ // only. Nothing else is written.
+ const dragEdit: TimelineMoveEdit = {
+ element: drag.element,
+ updates: { start: drag.previewStart, track: drag.previewTrack },
+ };
+ const coalesceKey = isVertical ? `clip-lane-move:${laneChangeGestureSeq++}` : undefined;
+
+ const edits: TimelineMoveEdit[] = [dragEdit];
+ if (multi) {
+ for (const e of elements) {
+ if (keyOf(e) === dragKey || !multi.keys.has(keyOf(e))) continue;
+ const start = multi.movedStart(e);
+ if (start !== e.start) edits.push({ element: e, updates: { start, track: e.track } });
+ }
+ }
+ // The drop-intent set for the z-sync: the dragged clip at its new lane, others
+ // as-is. Reasoning on this (not a re-normalize) keeps the sync seeing the user's
+ // move; computeStackingPatches only compares lanes relatively.
+ const candidate = elements.map((e) =>
+ keyOf(e) === dragKey ? { ...e, start: drag.previewStart, track: drag.previewTrack } : e,
+ );
+ const multiKeys = multi ? multi.keys : null;
+ void persistMoveEdits(edits, deps, coalesceKey, "lane-reorder").then((moved) => {
+ if (moved && isVertical) {
+ syncStackingForEdit(
+ candidate,
+ dragKey,
+ drag.element.track,
+ drag.previewTrack,
+ multiKeys,
+ deps,
+ coalesceKey,
+ );
+ }
+ });
+}
+
+/**
+ * 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.
+ */
+function commitTrackInsert(
+ drag: DraggedClipState,
+ deps: DragCommitDeps,
+ multi: {
+ keys: ReadonlySet<string>;
+ movedStart: (e: TimelineElement) => number;
+ } | null,
+): void {
+ 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 candidate = elements.map((e) => {
+ if (keyOf(e) === dragKey) return { ...e, start: drag.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);
+ const bySrc = new Map(elements.map((e) => [keyOf(e), e]));
+ const edits: TimelineMoveEdit[] = [];
+ for (const norm of normalized) {
+ const src = bySrc.get(keyOf(norm));
+ if (!src) continue;
+ // Capabilities gate: never write a locked/implicit clip, even one only swept
+ // along by the renumber (not just a marquee member).
+ if (!canMoveElement(src)) continue;
+ const start =
+ keyOf(norm) === dragKey || multi?.keys.has(keyOf(norm))
+ ? (multi?.movedStart(src) ?? drag.previewStart)
+ : src.start;
+ edits.push({ element: src, updates: { start, track: norm.track } });
+ }
+
+ 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).
+ syncStackingForEdit(
+ candidate,
+ dragKey,
+ drag.element.track,
+ drag.insertRow!,
+ multi ? multi.keys : null,
+ deps,
+ coalesceKey,
+ );
+ }
+ });
+}
+
+/**
+ * Compute + apply z-index patches for the edited clip(s) after a DELIBERATE
+ * vertical lane change. Projects the drop-intent element set (`candidate`: the
+ * dragged clip at its new / fractional-insert lane, others at their current tracks)
+ * onto StackingElement using the caller-supplied live z-index reader, then
+ * delegates the minimal-z resolution to computeStackingPatches — a clip on the
+ * upper lane paints above every clip it time-overlaps. No-op unless both z-sync
+ * deps are present, and never when the gesture aimed at the clip's OWN current
+ * lane (`aimedLane === currentLane` — not a relocation).
+ */
+function syncStackingForEdit(
+ candidate: TimelineElement[],
+ dragKey: string,
+ currentLane: number,
+ aimedLane: number,
+ multiKeys: ReadonlySet<string> | null,
+ deps: DragCommitDeps,
+ coalesceKey?: string,
+): void {
+ const { readZIndex, onStackingPatches } = deps;
+ if (!readZIndex || !onStackingPatches) return;
+
+ // 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;
+
+ // `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).
+ const stackingEls = candidate.map((el, domIndex) => ({
+ key: keyOf(el),
+ start: el.start,
+ duration: el.duration,
+ track: el.track,
+ zIndex: readZIndex(el),
+ isAudio: classifyZone(el) === "audio",
+ domIndex,
+ }));
+
+ const editedKeys = [dragKey];
+ 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);
+}
diff --git a/packages/studio/src/player/components/timelineClipDragPreview.test.ts b/packages/studio/src/player/components/timelineClipDragPreview.test.ts
new file mode 100644
index 0000000000..fc1a4ca2bf
--- /dev/null
+++ b/packages/studio/src/player/components/timelineClipDragPreview.test.ts
@@ -0,0 +1,144 @@
+import { describe, expect, it } from "vitest";
+import type { TimelineElement } from "../store/playerStore";
+import { computeDragPreview, type DragPreviewContext } from "./timelineClipDragPreview";
+import type { DraggedClipState } from "./timelineClipDragTypes";
+import { RULER_H, TRACKS_TOP_PAD, TRACK_H } from "./timelineLayout";
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Regression bed for the live-reproduced BUG 1: a PLAIN HORIZONTAL drag of a clip
+// on its own top lane armed a phantom new-track insert (the old 0.32 insert band
+// reached deep into the clip body). That insert flipped the commit into the
+// lane-change branch, which nudged the clip's z-index and re-sorted it off its
+// lane. The invariant: a horizontal drag over a clip BODY → insertRow === null,
+// previewTrack unchanged (a pure time move — zero topology change, zero z sync).
+//
+// Elements mirror the user's index.html shapes: a high-z "v-moodboard" alone on
+// the top display lane, over several lower-lane video clips it overlaps in time,
+// plus a caption. Tracks here are already the normalized DISPLAY lanes (the store
+// runs normalizeToZones on discovery), matching what the drag hook passes in.
+// ─────────────────────────────────────────────────────────────────────────────
+
+const PPS = 40;
+
+function clip(
+ id: string,
+ track: number,
+ start: number,
+ duration: number,
+ zIndex: number,
+ tag = "video",
+): TimelineElement {
+ return { id, key: id, tag, start, duration, track, zIndex, domId: id };
+}
+
+// v-moodboard: own top lane (0). Lower lane (1) carries overlapping video clips;
+// captions sit on lane 2. trackOrder = [0, 1, 2].
+const moodboard = clip("v-moodboard", 0, 19, 5.5, 37);
+const fixtureElements: TimelineElement[] = [
+ moodboard,
+ clip("v-dashboard", 1, 19, 4, 16),
+ clip("v-globe", 1, 23, 1.5, 17),
+ clip("cap", 2, 20.82, 1.78, 0, "text"),
+];
+
+// A scroll container whose content-space y equals clientY (rect top 0, no scroll).
+function fakeScroll(): HTMLDivElement {
+ return {
+ getBoundingClientRect: () => ({ top: 0, left: 0, right: 0, bottom: 0, width: 0, height: 0 }),
+ scrollLeft: 0,
+ scrollTop: 0,
+ scrollWidth: 100000,
+ } as unknown as HTMLDivElement;
+}
+
+function ctx(): DragPreviewContext {
+ return {
+ scroll: fakeScroll(),
+ pps: PPS,
+ duration: 44.5,
+ trackOrder: [0, 1, 2],
+ elements: fixtureElements,
+ selectedKeys: new Set<string>(),
+ buildSnapTargets: () => [],
+ audioTracks: new Set<number>(),
+ };
+}
+
+// content-space y for a fractional row index (inverse of getTimelineRowFromY).
+const yForRow = (rowFloat: number) => RULER_H + TRACKS_TOP_PAD + rowFloat * TRACK_H;
+
+// A drag grabbing `element` at vertical position `grabRowFloat` within its lane.
+function horizontalDrag(
+ element: TimelineElement,
+ grabRowFloat: number,
+ deltaSeconds: number,
+): { drag: DraggedClipState; clientX: number; clientY: number } {
+ const originClientX = 800;
+ const originClientY = yForRow(grabRowFloat);
+ const drag: DraggedClipState = {
+ element,
+ originClientX,
+ originClientY,
+ originScrollLeft: 0,
+ originScrollTop: 0,
+ pointerClientX: originClientX,
+ pointerClientY: originClientY,
+ pointerOffsetX: 0,
+ pointerOffsetY: 0,
+ previewStart: element.start,
+ previewTrack: element.track,
+ insertRow: null,
+ snapTime: null,
+ snapType: null,
+ started: true,
+ };
+ // Horizontal: clientY stays at the grab point; only x advances by the delta.
+ return { drag, clientX: originClientX + deltaSeconds * PPS, clientY: originClientY };
+}
+
+describe("computeDragPreview — plain horizontal drag never arms a phantom insert (BUG 1)", () => {
+ it("dragging v-moodboard +2s while grabbing its clip body keeps it a pure time move", () => {
+ const { drag, clientX, clientY } = horizontalDrag(moodboard, 0.5, 2);
+ const next = computeDragPreview(drag, clientX, clientY, ctx());
+ expect(next.insertRow).toBeNull(); // no phantom new-track insert
+ expect(next.previewTrack).toBe(0); // stays on its own lane
+ expect(next.desiredTrack).toBe(0); // pointer never left lane 0 → not a vertical aim
+ expect(next.previewStart).toBeCloseTo(21, 5); // +2s moved
+ });
+
+ it("grabbing ANYWHERE across the clip body (not just dead-center) stays a pure time move", () => {
+ // Sweep the whole clip body of lane 0; a horizontal drag must never insert.
+ for (let grab = 0.1; grab <= 0.9 + 1e-9; grab += 0.1) {
+ const { drag, clientX, clientY } = horizontalDrag(moodboard, grab, 2);
+ const next = computeDragPreview(drag, clientX, clientY, ctx());
+ expect(next.insertRow).toBeNull();
+ expect(next.previewTrack).toBe(0);
+ }
+ });
+
+ it("aiming the gutter ABOVE the top lane arms a top insert (UX rule 2)", () => {
+ // Drag v-moodboard up into the top breathing pad → insert a new top track.
+ const originClientX = 800;
+ const originClientY = yForRow(0.5);
+ const drag: DraggedClipState = {
+ element: moodboard,
+ originClientX,
+ originClientY,
+ originScrollLeft: 0,
+ originScrollTop: 0,
+ pointerClientX: originClientX,
+ pointerClientY: originClientY,
+ pointerOffsetX: 0,
+ pointerOffsetY: 0,
+ previewStart: moodboard.start,
+ previewTrack: moodboard.track,
+ insertRow: null,
+ snapTime: null,
+ snapType: null,
+ started: true,
+ };
+ // Pointer well above the first lane (into the top pad → rowFloat < 0).
+ const next = computeDragPreview(drag, originClientX, yForRow(-0.6), ctx());
+ expect(next.insertRow).toBe(0); // a new TOP track will be created on drop
+ });
+});
diff --git a/packages/studio/src/player/components/timelineClipDragPreview.ts b/packages/studio/src/player/components/timelineClipDragPreview.ts
index f537ab9ab2..30b06d3ea6 100644
--- a/packages/studio/src/player/components/timelineClipDragPreview.ts
+++ b/packages/studio/src/player/components/timelineClipDragPreview.ts
@@ -1,52 +1,337 @@
+import { resolveTimelineMove, resolveTimelineResize } from "./timelineEditing";
import type { TimelineElement } from "../store/playerStore";
-import type { TimelineStackingReorderIntent } from "./timelineEditing";
-import type { TimelineLayerId } from "./timelineTrackOrder";
+import { TRACK_H, getTimelineRowFromY, INSERT_BOUNDARY_BAND } from "./timelineLayout";
+import { isMusicTrack, isAudioTimelineElement } from "../../utils/timelineInspector";
+import {
+ TIMELINE_SNAP_PX,
+ snapMoveToTargets,
+ snapTimelineTime,
+ type TimelineSnapTarget,
+} from "./timelineSnapping";
+import { resolveInsertRow, resolveZoneDropPlacement } from "./timelineCollision";
+import {
+ applyTimelineGroupResizePreview,
+ type TimelineGroupResizeSession,
+} from "./timelineGroupEditing";
+import { clampGroupMoveDelta } from "./timelineMultiDragPreview";
+import type { DraggedClipState, ResizingClipState } from "./timelineClipDragTypes";
-interface DragPreviewState {
- element: Pick<TimelineElement, "track">;
- previewLayerId: TimelineLayerId;
- previewLayerIndex: number;
+/** Snap-target builder closure supplied by the hook (closes over refs + store). */
+type BuildSnapTargets = (
+ excludeElementKey: string | null,
+ includeBeats: boolean,
+) => TimelineSnapTarget[];
+
+export interface DragPreviewContext {
+ scroll: HTMLDivElement | null;
+ pps: number;
+ duration: number;
+ trackOrder: number[];
+ elements: TimelineElement[];
+ selectedKeys: ReadonlySet<string>;
+ buildSnapTargets: BuildSnapTargets;
+ /**
+ * The set of tracks that hold audio clips (drives zone-aware drop placement).
+ * Frozen for the whole gesture, so the hook builds it ONCE at drag start and
+ * passes it in — see useTimelineClipDrag. Absent (e.g. in unit tests) ⇒ built
+ * on demand from `elements`, so the result is identical either way.
+ */
+ audioTracks?: ReadonlySet<number>;
}
-export interface TimelineMovePreview {
- start: number;
- track: number;
- previewLayerId?: TimelineLayerId;
- previewLayerIndex?: number;
- stackingReorder?: TimelineStackingReorderIntent | null;
+/**
+ * Max start a drag may reach. Allow dragging past the current content into the
+ * rendered timeline extent (the viewport-fill keeps that ≥ the viewport width).
+ * The composition grows to fit on commit (content-driven duration), so don't
+ * cap at content length.
+ */
+function resolveDragMaxStart(scroll: HTMLDivElement | null, pps: number, duration: number): number {
+ return Math.max(duration, scroll && pps > 0 ? scroll.scrollWidth / pps : duration);
}
-export interface TimelineGroupMovePreview {
- active: boolean;
- previewStart: number;
+/**
+ * Rigid group move: when the grabbed clip is part of a multi-selection, the
+ * WHOLE formation shifts by its delta on commit (see timelineClipDragCommit).
+ * Clamp that delta here — against every selected member's start — so the
+ * grabbed clip can't out-run the group: it STOPS the instant any member would
+ * cross 0, exactly as it lands on commit. Lane changes still apply to the
+ * grabbed clip only, so only the start (x) is constrained.
+ */
+function resolveGroupClampedStart(
+ snapStart: number,
+ element: TimelineElement,
+ dragKey: string,
+ elements: TimelineElement[],
+ selectedKeys: ReadonlySet<string>,
+): number {
+ if (selectedKeys.size <= 1 || !selectedKeys.has(dragKey)) return snapStart;
+ const memberStarts = elements.filter((e) => selectedKeys.has(e.key ?? e.id)).map((e) => e.start);
+ const clampedDelta = clampGroupMoveDelta(snapStart - element.start, memberStarts);
+ return element.start + clampedDelta;
}
-export function resolveDragPreviewPlacement(
- drag: DragPreviewState,
- nextMove: TimelineMovePreview,
- groupMove: TimelineGroupMovePreview,
-): {
+/**
+ * The whole drop decision (no same-track overlap, zone-respecting, relocate or
+ * create) — one tested pure function, so what runs here is what's verified.
+ */
+function resolveDropPlacement(
+ drag: DraggedClipState,
+ clientY: number,
+ previewStart: number,
+ desiredTrack: number,
+ ctx: DragPreviewContext,
+): { track: number; insertRow: number | null } {
+ const { scroll, trackOrder, elements } = ctx;
+ // rowFloat = the pointer's position in track-heights from the top lane; a
+ // near-boundary hover requests a deliberate new-track insert. Uses the
+ // shared row→y inverse so the top breathing pad is subtracted consistently.
+ const rowFloat = scroll
+ ? getTimelineRowFromY(clientY - scroll.getBoundingClientRect().top + scroll.scrollTop)
+ : 0;
+ // Geometry-exact band (the clip inset) so an insert only arms in the visible
+ // gutter BETWEEN clip bodies — dragging over a clip body is a lane move, never a
+ // phantom insert (the plain-horizontal-drag misfire). See INSERT_BOUNDARY_BAND.
+ const rawInsertRow = resolveInsertRow(rowFloat, trackOrder.length, INSERT_BOUNDARY_BAND);
+ // Pointer sub-row half: when a drop must auto-create a track (aimed span
+ // occupied, no free lane), open it on the side the pointer is nearer.
+ const preferInsertAbove = rowFloat - Math.floor(rowFloat) < 0.5;
+ const audioTracks =
+ ctx.audioTracks ?? new Set(elements.filter(isAudioTimelineElement).map((e) => e.track));
+ return resolveZoneDropPlacement({
+ order: trackOrder,
+ audioTracks,
+ elements,
+ desiredTrack,
+ deliberateInsertRow: rawInsertRow,
+ start: previewStart,
+ duration: drag.element.duration,
+ dragKey: drag.element.key ?? drag.element.id,
+ isAudio: isAudioTimelineElement(drag.element),
+ preferInsertAbove,
+ });
+}
+
+/** Recompute the dragged-clip preview (move + snap + group clamp + drop placement). */
+export function computeDragPreview(
+ drag: DraggedClipState,
+ clientX: number,
+ clientY: number,
+ ctx: DragPreviewContext,
+): DraggedClipState {
+ const { scroll, pps, duration, trackOrder, elements, selectedKeys, buildSnapTargets } = ctx;
+ const dragMaxStart = resolveDragMaxStart(scroll, pps, duration);
+ const nextMove = resolveTimelineMove(
+ {
+ start: drag.element.start,
+ track: drag.element.track,
+ duration: drag.element.duration,
+ originClientX: drag.originClientX,
+ originClientY: drag.originClientY,
+ originScrollLeft: drag.originScrollLeft,
+ originScrollTop: drag.originScrollTop,
+ currentScrollLeft: scroll?.scrollLeft ?? drag.originScrollLeft,
+ currentScrollTop: scroll?.scrollTop ?? drag.originScrollTop,
+ pixelsPerSecond: pps,
+ trackHeight: TRACK_H,
+ maxStart: dragMaxStart,
+ trackOrder,
+ },
+ clientX,
+ clientY,
+ );
+ // The music track defines the beats, so it must not snap to them —
+ // but it still snaps to the playhead and other clip edges.
+ const targets = buildSnapTargets(
+ drag.element.key ?? drag.element.id,
+ !isMusicTrack(drag.element),
+ );
+ const snap = snapMoveToTargets(
+ nextMove.start,
+ drag.element.duration,
+ targets,
+ pps,
+ // Relaxed clamp: allow the snapped start past the content, up to the
+ // rendered extent (see dragMaxStart) — the composition grows on commit.
+ dragMaxStart + drag.element.duration,
+ );
+ const dragKey = drag.element.key ?? drag.element.id;
+ const previewStart = resolveGroupClampedStart(
+ snap.start,
+ drag.element,
+ dragKey,
+ elements,
+ selectedKeys,
+ );
+ const { track: previewTrack, insertRow } = resolveDropPlacement(
+ drag,
+ clientY,
+ previewStart,
+ nextMove.track,
+ ctx,
+ );
+ return {
+ ...drag,
+ started: true,
+ pointerClientX: clientX,
+ pointerClientY: clientY,
+ previewStart,
+ previewTrack,
+ // The lane the POINTER aims at (pre-collision): the commit reads it to tell a
+ // deliberate vertical lane change from a horizontal drag merely bumped sideways.
+ desiredTrack: nextMove.track,
+ insertRow,
+ snapTime: snap.snapTime,
+ snapType: snap.snapType,
+ };
+}
+
+export interface ResizePreviewContext {
+ scroll: HTMLDivElement | null;
+ pps: number;
+ buildSnapTargets: BuildSnapTargets;
+}
+
+export interface ResizePreviewResult {
+ originScrollLeft: number;
previewStart: number;
- previewTrack: number;
- previewLayerId: TimelineLayerId;
- previewLayerIndex: number;
- previewStackingReorder: TimelineStackingReorderIntent | null;
-} {
- if (groupMove.active) {
- return {
- previewStart: groupMove.previewStart,
- previewTrack: drag.element.track,
- previewLayerId: drag.previewLayerId,
- previewLayerIndex: drag.previewLayerIndex,
- previewStackingReorder: null,
- };
+ previewDuration: number;
+ previewPlaybackStart?: number;
+}
+
+/** Compute the trim preview for a pointer x (pure — the hook applies the state). */
+// fallow-ignore-next-line complexity
+export function computeResizePreview(
+ resize: ResizingClipState,
+ clientX: number,
+ ctx: ResizePreviewContext,
+): ResizePreviewResult {
+ const { scroll, pps, buildSnapTargets } = ctx;
+ // Scroll compensation: auto-scroll moves the content while the pointer stays
+ // put, so fold the scroll delta into the pointer x (mirrors
+ // resolveTimelineMove's originScrollLeft handling).
+ const originScrollLeft = resize.originScrollLeft ?? scroll?.scrollLeft ?? 0;
+ const effectiveClientX = clientX + ((scroll?.scrollLeft ?? originScrollLeft) - originScrollLeft);
+
+ const sourceRemaining =
+ resize.element.sourceDuration != null
+ ? Math.max(
+ 0,
+ (resize.element.sourceDuration - (resize.element.playbackStart ?? 0)) /
+ Math.max(resize.element.playbackRate ?? 1, 0.1),
+ )
+ : Number.POSITIVE_INFINITY;
+ const normalizedTag = resize.element.tag.toLowerCase();
+ const canSeedPlaybackStart = normalizedTag === "audio" || normalizedTag === "video";
+ const playbackRate = Math.max(resize.element.playbackRate ?? 1, 0.1);
+ // Trim limit = available source media only — NOT the composition length.
+ // Duration is content-driven (the comp grows/shrinks to fit on commit), so
+ // capping a trim at the current comp end both blocked extending the last clip
+ // rightward and, after a far move, collapsed a clip to the sliver between its
+ // start and the comp end (the 8s→0.95s audio incident). Images/text/shapes
+ // have no source, so they extend freely.
+ const maxEnd = resize.element.start + sourceRemaining;
+ let nextResize = resolveTimelineResize(
+ {
+ start: resize.element.start,
+ duration: resize.element.duration,
+ originClientX: resize.originClientX,
+ pixelsPerSecond: pps,
+ minStart: 0,
+ maxEnd,
+ playbackStart:
+ resize.edge === "start" && canSeedPlaybackStart
+ ? (resize.element.playbackStart ?? 0)
+ : resize.element.playbackStart,
+ playbackRate: resize.element.playbackRate,
+ },
+ resize.edge,
+ effectiveClientX,
+ );
+
+ // Snap edge to unified targets (beats + clip edges + playhead) when available.
+ // The snap must stay inside the same limits resolveTimelineResize enforces, or
+ // it would push the edge past the available source media / composition end.
+ // The music track defines the beats, so it must not snap to them — but it
+ // still snaps to the playhead and other clip edges.
+ const trimTargets = buildSnapTargets(
+ resize.element.key ?? resize.element.id,
+ !isMusicTrack(resize.element),
+ );
+ if (trimTargets.length > 0) {
+ const snapSecs = TIMELINE_SNAP_PX / Math.max(pps, 1);
+ if (resize.edge === "end") {
+ const edgeTime = nextResize.start + nextResize.duration;
+ const snapped = snapTimelineTime(edgeTime, trimTargets, snapSecs).time;
+ // Stay within [start+minDuration, maxEnd] so the snap can't create a
+ // degenerate clip or run past the source/composition limit.
+ const snappedDuration = Math.round((snapped - nextResize.start) * 1000) / 1000;
+ if (snapped !== edgeTime && snapped <= maxEnd + 1e-6 && snappedDuration >= 0.05) {
+ nextResize = { ...nextResize, duration: snappedDuration };
+ }
+ } else {
+ const snapped = snapTimelineTime(nextResize.start, trimTargets, snapSecs).time;
+ const delta = nextResize.start - snapped; // >0 when snapping left
+ // Leftward snap reveals more source; cap so playbackStart can't go < 0.
+ const maxLeftDelta =
+ nextResize.playbackStart != null
+ ? nextResize.playbackStart / playbackRate
+ : Number.POSITIVE_INFINITY;
+ // Also require the resulting duration to stay >= minDuration so a rightward
+ // snap (delta < 0) can't collapse the clip to zero/negative.
+ const snappedDuration = Math.round((nextResize.duration + delta) * 1000) / 1000;
+ if (
+ snapped !== nextResize.start &&
+ snapped >= 0 &&
+ delta <= maxLeftDelta + 1e-6 &&
+ snappedDuration >= 0.05
+ ) {
+ nextResize = {
+ ...nextResize,
+ start: snapped,
+ duration: snappedDuration,
+ playbackStart:
+ nextResize.playbackStart != null
+ ? Math.round(Math.max(0, nextResize.playbackStart - delta * playbackRate) * 1000) /
+ 1000
+ : undefined,
+ };
+ }
+ }
}
return {
- previewStart: groupMove.previewStart,
- previewTrack: nextMove.track,
- previewLayerId: nextMove.previewLayerId ?? drag.previewLayerId,
- previewLayerIndex: nextMove.previewLayerIndex ?? drag.previewLayerIndex,
- previewStackingReorder: nextMove.stackingReorder ?? null,
+ originScrollLeft,
+ previewStart: nextResize.start,
+ previewDuration: nextResize.duration,
+ previewPlaybackStart: nextResize.playbackStart,
};
}
+
+/**
+ * Apply a rigid group-resize preview: fold the grabbed clip's raw delta into the
+ * session, preview every non-grabbed member through the store (`updateElement`),
+ * and set the grabbed clip's preview state (it renders from resizingClip state, so
+ * its store value stays pristine until commit — like the single-clip path).
+ */
+export function previewGroupResize(
+ session: TimelineGroupResizeSession,
+ next: ResizePreviewResult,
+ grabbedKey: string,
+ updateElement: (
+ key: string,
+ patch: { start: number; duration: number; playbackStart?: number },
+ ) => void,
+ setResizeState: (v: ResizePreviewResult) => void,
+): void {
+ const grabbedChange = applyTimelineGroupResizePreview(session, next);
+ for (const c of session.changes) {
+ if (c.key === grabbedKey) continue;
+ updateElement(c.key, { start: c.start, duration: c.duration, playbackStart: c.playbackStart });
+ }
+ setResizeState({
+ originScrollLeft: next.originScrollLeft,
+ previewStart: grabbedChange?.start ?? next.previewStart,
+ previewDuration: grabbedChange?.duration ?? next.previewDuration,
+ previewPlaybackStart: grabbedChange?.playbackStart ?? next.previewPlaybackStart,
+ });
+}
diff --git a/packages/studio/src/player/components/timelineClipDragTypes.ts b/packages/studio/src/player/components/timelineClipDragTypes.ts
new file mode 100644
index 0000000000..8ac36c9a68
--- /dev/null
+++ b/packages/studio/src/player/components/timelineClipDragTypes.ts
@@ -0,0 +1,65 @@
+import type { TimelineElement } from "../store/playerStore";
+import type { TimelineSnapType } from "./timelineSnapping";
+import type { BlockedTimelineEditIntent } from "./timelineEditing";
+
+/* ── Shared clip-drag state types ───────────────────────────────── */
+export interface DraggedClipState {
+ element: TimelineElement;
+ originClientX: number;
+ originClientY: number;
+ originScrollLeft: number;
+ originScrollTop: number;
+ pointerClientX: number;
+ pointerClientY: number;
+ pointerOffsetX: number;
+ pointerOffsetY: number;
+ previewStart: number;
+ previewTrack: number;
+ /**
+ * The lane the POINTER aims at (from the drag's vertical position), before
+ * collision resolution. `previewTrack` is where the clip actually LANDS —
+ * which may differ from `desiredTrack` when the aimed span is occupied and the
+ * collision rules bump the dragged clip to a free lane. The commit reads this
+ * to tell a deliberate VERTICAL lane change (pointer aimed at another lane →
+ * stacking sync allowed) from a plain HORIZONTAL drag whose clip merely got
+ * bumped sideways (never touches z). Optional: when absent the commit falls
+ * back to `previewTrack` (pre-existing behaviour).
+ */
+ desiredTrack?: number;
+ /**
+ * When non-null, the drop inserts a NEW track at this visual row boundary
+ * (0 = above the top lane, trackOrder.length = below the bottom) instead of
+ * landing on previewTrack. Drives the insertion-line indicator.
+ */
+ insertRow: number | null;
+ /** Snap target the clip will land on, for the guide highlight. */
+ snapTime: number | null;
+ snapType: TimelineSnapType | null;
+ started: boolean;
+}
+
+export interface ResizingClipState {
+ element: TimelineElement;
+ edge: "start" | "end";
+ originClientX: number;
+ /**
+ * scrollLeft at gesture start. Edge auto-scroll moves the content under a
+ * stationary pointer, so the trim math folds (current − origin) scrollLeft
+ * into the pointer x — mirroring resolveTimelineMove's scroll compensation.
+ * Optional so pre-existing constructors/tests stay valid; when absent the
+ * first preview update captures the current scrollLeft.
+ */
+ originScrollLeft?: number;
+ previewStart: number;
+ previewDuration: number;
+ previewPlaybackStart?: number;
+ started: boolean;
+}
+
+export interface BlockedClipState {
+ element: TimelineElement;
+ intent: BlockedTimelineEditIntent;
+ originClientX: number;
+ originClientY: number;
+ started: boolean;
+}
diff --git a/packages/studio/src/player/components/timelineCollision.test.ts b/packages/studio/src/player/components/timelineCollision.test.ts
index c1c9b26ca5..42ce89d33b 100644
--- a/packages/studio/src/player/components/timelineCollision.test.ts
+++ b/packages/studio/src/player/components/timelineCollision.test.ts
@@ -9,6 +9,7 @@ import {
resolveZoneDropPlacement,
timeRangesOverlap,
} from "./timelineCollision";
+import { INSERT_BOUNDARY_BAND } from "./timelineLayout";
function el(id: string, track: number, start: number, duration: number): TimelineElement {
return { id, tag: "video", start, duration, track };
@@ -191,8 +192,47 @@ describe("resolveInsertRow", () => {
});
});
-// (The production insert-band suite imports INSERT_BOUNDARY_BAND from timelineLayout,
-// which lands with the timeline glue swap — the full suite re-lands there.)
+describe("resolveInsertRow — production band only arms in the inter-clip gutter (UX rule 1)", () => {
+ // The production band equals the clip inset (CLIP_Y / TRACK_H): a clip body fills
+ // [band, 1 − band] of its row, so an insert must ONLY arm in the thin gutter that
+ // straddles a boundary — never while the pointer is over a clip body. This is the
+ // regression for the plain-horizontal-drag misfire (the old 0.32 band armed an
+ // insert across ~64% of every row).
+ const n = 3;
+ const b = INSERT_BOUNDARY_BAND;
+
+ it("the band is the clip inset (3/48), not the old feel-tuned 0.32", () => {
+ expect(b).toBeCloseTo(3 / 48, 10);
+ expect(b).toBeLessThan(0.1);
+ });
+
+ it("returns null across the WHOLE clip body of every lane (no insert = move-to-lane)", () => {
+ // Sweep each lane's body [band+ε, 1−band−ε] in fine steps → always a move.
+ for (let lane = 0; lane < n; lane++) {
+ for (let frac = b + 0.01; frac <= 1 - b - 0.01 + 1e-9; frac += 0.02) {
+ expect(resolveInsertRow(lane + frac, n, b)).toBeNull();
+ }
+ }
+ });
+
+ it("arms an insert in the gutter straddling every internal boundary (dead-zone-free)", () => {
+ // Just under a boundary → insert BELOW the upper lane; just over → ABOVE the
+ // lower lane. Both resolve to the same boundary row, so the gutter has no dead
+ // spot that neither moves nor inserts.
+ expect(resolveInsertRow(1 - b / 2, n, b)).toBe(1); // bottom gutter of lane 0
+ expect(resolveInsertRow(1 + b / 2, n, b)).toBe(1); // top gutter of lane 1
+ expect(resolveInsertRow(2 - b / 2, n, b)).toBe(2);
+ expect(resolveInsertRow(2 + b / 2, n, b)).toBe(2);
+ });
+
+ it("still arms a top / bottom insert above the first / below the last lane", () => {
+ expect(resolveInsertRow(b / 2, n, b)).toBe(0); // top gutter of lane 0 → insert above top
+ expect(resolveInsertRow(-0.4, n, b)).toBe(0); // in the top breathing pad
+ expect(resolveInsertRow(n - b / 2, n, b)).toBe(n); // bottom gutter of last lane
+ expect(resolveInsertRow(n + 0.4, n, b)).toBe(n); // in the bottom breathing pad
+ });
+});
+
describe("clampTrackToZone", () => {
// trackOrder [0,1,2,3]: rows 0,1 = visual; rows 2,3 = audio (audioRow = 2).
const order = [0, 1, 2, 3];
diff --git a/packages/studio/src/player/components/timelineDragDrop.ts b/packages/studio/src/player/components/timelineDragDrop.ts
index e150dc51d1..e24511e380 100644
--- a/packages/studio/src/player/components/timelineDragDrop.ts
+++ b/packages/studio/src/player/components/timelineDragDrop.ts
@@ -1,23 +1,50 @@
import { useCallback, useState, type RefObject } from "react";
import { TIMELINE_ASSET_MIME, TIMELINE_BLOCK_MIME } from "../../utils/timelineAssetDrop";
+import { usePlayerStore } from "../store/playerStore";
import { TRACK_H, resolveTimelineAssetDrop } from "./timelineLayout";
import type { TimelineDropCallbacks } from "./timelineCallbacks";
-import type { StackingTimelineLayer, TimelineLayerId } from "./timelineTrackOrder";
interface UseTimelineAssetDropOptions extends TimelineDropCallbacks {
scrollRef: RefObject<HTMLDivElement | null>;
ppsRef: RefObject<number>;
durationRef: RefObject<number>;
- trackOrderRef: RefObject<TimelineLayerId[]>;
- timelineLayersRef: RefObject<StackingTimelineLayer[]>;
+ trackOrderRef: RefObject<number[]>;
}
+type TimelinePlacement = { start: number; track: number };
+
+/**
+ * Parse a JSON drag payload and, if it yields a value, forward it to the drop
+ * callback. Malformed payloads are ignored. Shared by the asset + block paths so
+ * the parse/guard/dispatch shape lives in one place.
+ */
+function applyJsonDropPayload(
+ raw: string,
+ pick: (parsed: Record<string, string | undefined>) => string | undefined,
+ apply: (value: string, placement: TimelinePlacement) => void,
+ placement: TimelinePlacement,
+): void {
+ try {
+ const value = pick(JSON.parse(raw) as Record<string, string | undefined>);
+ if (value) apply(value, placement);
+ } catch {
+ /* ignore malformed drag payloads */
+ }
+}
+
+/**
+ * Dropping an asset/file/block onto the timeline places it at the PLAYHEAD —
+ * start is the current playhead time, only the track comes from the drop y.
+ * Deliberate product choice (user preference, 2026-07-09): every add lands at
+ * the playhead regardless of drop x, like CapCut's add-to-timeline. External
+ * OS file drops and internal asset drops share this same placement path, so
+ * both land identically.
+ */
export function useTimelineAssetDrop({
scrollRef,
ppsRef,
durationRef,
trackOrderRef,
- timelineLayersRef,
onFileDrop,
onAssetDrop,
onBlockDrop,
@@ -25,83 +52,65 @@ export function useTimelineAssetDrop({
const [isDragOver, setIsDragOver] = useState(false);
const handleAssetDragOver = useCallback((e: React.DragEvent) => {
- const hasFiles = e.dataTransfer.files.length > 0;
const types = Array.from(e.dataTransfer.types);
+ const hasFiles = types.includes("Files");
const hasAsset = types.includes(TIMELINE_ASSET_MIME);
const hasBlock = types.includes(TIMELINE_BLOCK_MIME);
if (!hasFiles && !hasAsset && !hasBlock) return;
e.preventDefault();
- if (hasAsset || hasBlock) e.dataTransfer.dropEffect = "copy";
+ e.dataTransfer.dropEffect = "copy";
setIsDragOver(true);
}, []);
+ const clearDropPreview = useCallback(() => setIsDragOver(false), []);
+
+ const resolveDropPlacement = useCallback(
+ (clientX: number, clientY: number): TimelinePlacement => {
+ const scroll = scrollRef.current;
+ const rect = scroll?.getBoundingClientRect();
+ // Track comes from the vertical drop position; start is the playhead.
+ const { track } = resolveTimelineAssetDrop(
+ {
+ rectLeft: rect?.left ?? 0,
+ rectTop: rect?.top ?? 0,
+ scrollLeft: scroll?.scrollLeft ?? 0,
+ scrollTop: scroll?.scrollTop ?? 0,
+ pixelsPerSecond: ppsRef.current,
+ duration: durationRef.current,
+ trackHeight: TRACK_H,
+ trackOrder: trackOrderRef.current,
+ },
+ clientX,
+ clientY,
+ );
+ const start = Math.max(0, usePlayerStore.getState().currentTime);
+ return { start, track };
+ },
+ [scrollRef, ppsRef, durationRef, trackOrderRef],
+ );
+
const handleAssetDrop = useCallback(
- // fallow-ignore-next-line complexity
(e: React.DragEvent) => {
e.preventDefault();
setIsDragOver(false);
- const scroll = scrollRef.current;
- const rect = scroll?.getBoundingClientRect();
- const layerById = new Map(timelineLayersRef.current.map((layer) => [layer.id, layer]));
- const trackOrder = trackOrderRef.current
- .map((id) => layerById.get(id)?.placementTrack)
- .filter((track): track is number => track != null);
- const dropInput = {
- rectLeft: rect?.left ?? 0,
- rectTop: rect?.top ?? 0,
- scrollLeft: scroll?.scrollLeft ?? 0,
- scrollTop: scroll?.scrollTop ?? 0,
- pixelsPerSecond: ppsRef.current,
- duration: durationRef.current,
- trackHeight: TRACK_H,
- trackOrder,
- };
+ const placement = resolveDropPlacement(e.clientX, e.clientY);
+
if (onFileDrop && e.dataTransfer.files.length > 0) {
- void onFileDrop(
- Array.from(e.dataTransfer.files),
- scroll && rect ? resolveTimelineAssetDrop(dropInput, e.clientX, e.clientY) : undefined,
- );
+ void onFileDrop(Array.from(e.dataTransfer.files), placement);
return;
}
const assetPayload = e.dataTransfer.getData(TIMELINE_ASSET_MIME);
- if (assetPayload && onAssetDrop && scroll && rect) {
- try {
- const parsed = JSON.parse(assetPayload) as { path?: string };
- if (parsed.path)
- void onAssetDrop(
- parsed.path,
- resolveTimelineAssetDrop(dropInput, e.clientX, e.clientY),
- );
- } catch {
- /* ignore malformed drag payloads */
- }
+ if (assetPayload && onAssetDrop) {
+ applyJsonDropPayload(assetPayload, (p) => p.path, onAssetDrop, placement);
return;
}
const blockPayload = e.dataTransfer.getData(TIMELINE_BLOCK_MIME);
- if (blockPayload && onBlockDrop && scroll && rect) {
- try {
- const parsed = JSON.parse(blockPayload) as { name?: string };
- if (parsed.name)
- void onBlockDrop(
- parsed.name,
- resolveTimelineAssetDrop(dropInput, e.clientX, e.clientY),
- );
- } catch {
- /* ignore malformed drag payloads */
- }
+ if (blockPayload && onBlockDrop) {
+ applyJsonDropPayload(blockPayload, (p) => p.name, onBlockDrop, placement);
}
},
- [
- onAssetDrop,
- onBlockDrop,
- onFileDrop,
- scrollRef,
- ppsRef,
- durationRef,
- trackOrderRef,
- timelineLayersRef,
- ],
+ [resolveDropPlacement, onFileDrop, onAssetDrop, onBlockDrop],
);
- return { isDragOver, setIsDragOver, handleAssetDragOver, handleAssetDrop };
+ return { isDragOver, handleAssetDragOver, handleAssetDrop, clearDropPreview };
}
diff --git a/packages/studio/src/player/components/timelineEditCapabilities.ts b/packages/studio/src/player/components/timelineEditCapabilities.ts
new file mode 100644
index 0000000000..bdcc834ae0
--- /dev/null
+++ b/packages/studio/src/player/components/timelineEditCapabilities.ts
@@ -0,0 +1,52 @@
+export interface TimelineEditCapabilities {
+ canMove: boolean;
+ canTrimStart: boolean;
+ canTrimEnd: boolean;
+}
+
+function isDeterministicTimelineWindow(input: {
+ tag: string;
+ compositionSrc?: string;
+ playbackStartAttr?: "media-start" | "playback-start";
+ sourceDuration?: number;
+}): boolean {
+ if (input.compositionSrc || input.playbackStartAttr != null) return true;
+ if (
+ input.sourceDuration != null &&
+ Number.isFinite(input.sourceDuration) &&
+ input.sourceDuration > 0
+ ) {
+ return true;
+ }
+ return ["video", "audio", "img"].includes(input.tag.toLowerCase());
+}
+
+export function hasPatchableTimelineTarget(input: { domId?: string; selector?: string }): boolean {
+ return Boolean(input.domId || input.selector);
+}
+
+export function getTimelineEditCapabilities(input: {
+ tag: string;
+ duration: number;
+ domId?: string;
+ selector?: string;
+ compositionSrc?: string;
+ playbackStart?: number;
+ playbackStartAttr?: "media-start" | "playback-start";
+ sourceDuration?: number;
+ timingSource?: "authored" | "implicit";
+ timelineLocked?: boolean;
+}): TimelineEditCapabilities {
+ if (input.timingSource === "implicit" || input.timelineLocked) {
+ return { canMove: false, canTrimStart: false, canTrimEnd: false };
+ }
+
+ const canPatch = hasPatchableTimelineTarget(input);
+ const hasFiniteDuration = Number.isFinite(input.duration) && input.duration > 0;
+ const hasDeterministicWindow = isDeterministicTimelineWindow(input);
+ return {
+ canMove: canPatch && (hasDeterministicWindow || hasFiniteDuration),
+ canTrimEnd: canPatch && hasFiniteDuration,
+ canTrimStart: canPatch && hasFiniteDuration,
+ };
+}
diff --git a/packages/studio/src/player/components/timelineEditing.test.ts b/packages/studio/src/player/components/timelineEditing.test.ts
index 86cbb1c8b9..f2c2913ead 100644
--- a/packages/studio/src/player/components/timelineEditing.test.ts
+++ b/packages/studio/src/player/components/timelineEditing.test.ts
@@ -693,7 +693,7 @@ describe("buildTimelineAgentPrompt", () => {
prompt: "Move the title later and lower the music",
});
- expect(text).toContain("Time range: 0:01 - 0:04");
+ expect(text).toContain("Time range: 00:01 - 00:04");
expect(text).toContain("#title (div)");
expect(text).toContain("#music (audio)");
expect(text).toContain("Move the title later and lower the music");
diff --git a/packages/studio/src/player/components/timelineEditing.ts b/packages/studio/src/player/components/timelineEditing.ts
index a8d1bb0a66..9b08a67ce6 100644
--- a/packages/studio/src/player/components/timelineEditing.ts
+++ b/packages/studio/src/player/components/timelineEditing.ts
@@ -4,6 +4,13 @@ import type { StackingTimelineLayer, TimelineLayerId } from "./timelineTrackOrde
import { resolveTimelineLayerStackingMove } from "./timelineLayerDrag";
import { shouldShowTimelineLayerGroupHeader } from "./TimelineLayerGroupHeader";
import type { TimelineStackingElement, TimelineStackingReorderIntent } from "./timelineStacking";
+import type { TimelineEditCapabilities } from "./timelineEditCapabilities";
+
+export {
+ getTimelineEditCapabilities,
+ hasPatchableTimelineTarget,
+} from "./timelineEditCapabilities";
+export type { TimelineEditCapabilities } from "./timelineEditCapabilities";
import {
applyClipStartTrimDelta,
@@ -245,12 +252,6 @@ export interface TimelinePromptElement {
track: number;
}
-export interface TimelineEditCapabilities {
- canMove: boolean;
- canTrimStart: boolean;
- canTrimEnd: boolean;
-}
-
export type BlockedTimelineEditIntent = "move" | "resize-start" | "resize-end";
export interface TimelineRangeSelection {
@@ -362,59 +363,6 @@ export function selectTimelineElementsInMarquee({
return selected;
}
-function isDeterministicTimelineWindow(input: {
- tag: string;
- compositionSrc?: string;
- playbackStartAttr?: "media-start" | "playback-start";
- sourceDuration?: number;
-}): boolean {
- if (input.compositionSrc) return true;
- if (input.playbackStartAttr != null) return true;
- if (
- input.sourceDuration != null &&
- Number.isFinite(input.sourceDuration) &&
- input.sourceDuration > 0
- ) {
- return true;
- }
- const normalizedTag = input.tag.toLowerCase();
- return ["video", "audio", "img"].includes(normalizedTag);
-}
-
-export function hasPatchableTimelineTarget(input: { domId?: string; selector?: string }): boolean {
- return Boolean(input.domId || input.selector);
-}
-
-export function getTimelineEditCapabilities(input: {
- tag: string;
- duration: number;
- domId?: string;
- selector?: string;
- compositionSrc?: string;
- playbackStart?: number;
- playbackStartAttr?: "media-start" | "playback-start";
- sourceDuration?: number;
- timingSource?: "authored" | "implicit";
- timelineLocked?: boolean;
-}): TimelineEditCapabilities {
- if (input.timingSource === "implicit" || input.timelineLocked) {
- return {
- canMove: false,
- canTrimStart: false,
- canTrimEnd: false,
- };
- }
-
- const canPatch = hasPatchableTimelineTarget(input);
- const hasFiniteDuration = Number.isFinite(input.duration) && input.duration > 0;
- const hasDeterministicWindow = isDeterministicTimelineWindow(input);
- return {
- canMove: canPatch && (hasDeterministicWindow || hasFiniteDuration),
- canTrimEnd: canPatch && hasFiniteDuration,
- canTrimStart: canPatch && hasFiniteDuration,
- };
-}
-
export function resolveBlockedTimelineEditIntent(input: {
width: number;
offsetX: number;
@@ -525,3 +473,72 @@ export function buildTimelineElementAgentPrompt(element: {
export function formatTimelineAttributeNumber(value: number): string {
return Number(roundToCentiseconds(value).toFixed(2)).toString();
}
+
+/**
+ * Apply one edge auto-scroll step: scroll `scroll` toward the edge zone the
+ * pointer is in, clamped to the scrollable range. Returns true when the
+ * container actually moved (the caller keeps its RAF running and re-runs its
+ * live preview), false when the pointer is outside the edge zones or the scroll
+ * is already clamped (the caller stops).
+ */
+export function applyTimelineAutoScrollStep(
+ scroll: HTMLElement,
+ clientX: number,
+ clientY: number,
+): boolean {
+ const delta = resolveTimelineAutoScroll(scroll.getBoundingClientRect(), clientX, clientY);
+ if (delta.x === 0 && delta.y === 0) return false;
+ const maxScrollLeft = Math.max(0, scroll.scrollWidth - scroll.clientWidth);
+ const maxScrollTop = Math.max(0, scroll.scrollHeight - scroll.clientHeight);
+ const nextScrollLeft = Math.max(0, Math.min(maxScrollLeft, scroll.scrollLeft + delta.x));
+ const nextScrollTop = Math.max(0, Math.min(maxScrollTop, scroll.scrollTop + delta.y));
+ if (nextScrollLeft === scroll.scrollLeft && nextScrollTop === scroll.scrollTop) return false;
+ scroll.scrollLeft = nextScrollLeft;
+ scroll.scrollTop = nextScrollTop;
+ return true;
+}
+
+/**
+ * Decide whether an edge auto-scroll RAF loop should start, stop, or stay as-is
+ * for the current pointer: "start" when the pointer is in an edge zone and no
+ * loop is running, "stop" when it left the zones while a loop is running,
+ * "none" otherwise.
+ */
+export function resolveTimelineAutoScrollLoopAction(
+ scroll: HTMLElement | null,
+ clientX: number,
+ clientY: number,
+ rafActive: boolean,
+): "start" | "stop" | "none" {
+ if (!scroll) return "none";
+ const delta = resolveTimelineAutoScroll(scroll.getBoundingClientRect(), clientX, clientY);
+ if (delta.x === 0 && delta.y === 0) return rafActive ? "stop" : "none";
+ return rafActive ? "none" : "start";
+}
+
+/**
+ * Escape cancels an in-progress clip drag / resize / blocked-drag: no commit,
+ * no undo entry — the previews live only in the gesture state, so clearing it
+ * restores the pre-drag timeline. `suppressClick` arms the click suppressor
+ * only when the gesture actually started, so the click generated by the
+ * eventual pointerup can't reselect or split the clip.
+ */
+export function resolveTimelineDragEscape(input: TimelineDragEscapeInput): {
+ cancel: boolean;
+ suppressClick: boolean;
+} {
+ if (input.key !== "Escape" || (!input.drag && !input.resize && !input.blocked)) {
+ return { cancel: false, suppressClick: false };
+ }
+ return {
+ cancel: true,
+ suppressClick: Boolean(input.drag?.started || input.resize?.started || input.blocked?.started),
+ };
+}
+
+export interface TimelineDragEscapeInput {
+ key: string;
+ drag: { started: boolean } | null;
+ resize: { started: boolean } | null;
+ blocked: { started: boolean } | null;
+}
diff --git a/packages/studio/src/player/components/timelineGroupEditing.test.ts b/packages/studio/src/player/components/timelineGroupEditing.test.ts
new file mode 100644
index 0000000000..31c7ec2e51
--- /dev/null
+++ b/packages/studio/src/player/components/timelineGroupEditing.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it } from "vitest";
+import type { TimelineElement } from "../store/playerStore";
+import {
+ buildTimelineGroupResizeMembers,
+ resolveTimelineGroupResize,
+ resolveTimelineGroupResizeChanges,
+} from "./timelineGroupEditing";
+
+function el(id: string, over: Partial<TimelineElement> = {}): TimelineElement {
+ // domId gives a patchable target so getTimelineEditCapabilities().canTrim* is true.
+ return { id, key: id, tag: "video", start: 0, duration: 2, track: 0, domId: id, ...over };
+}
+
+function keys(...ids: string[]): ReadonlySet<string> {
+ return new Set(ids);
+}
+
+describe("buildTimelineGroupResizeMembers (legacy 36413da7f semantics)", () => {
+ it("returns null for a single-clip selection (no group forms)", () => {
+ const a = el("a");
+ expect(buildTimelineGroupResizeMembers([a], keys("a"), "a", "end")).toBeNull();
+ expect(buildTimelineGroupResizeMembers([a], new Set(), "a", "end")).toBeNull();
+ });
+
+ it("returns null when the grabbed clip is not part of the selection", () => {
+ const a = el("a");
+ const b = el("b");
+ expect(buildTimelineGroupResizeMembers([a, b], keys("a", "b"), "c", "end")).toBeNull();
+ });
+
+ it("degrades to single-clip (null) when ANY member is locked — locked clip never patched", () => {
+ const a = el("a");
+ const locked = el("b", { timelineLocked: true });
+ expect(buildTimelineGroupResizeMembers([a, locked], keys("a", "b"), "a", "end")).toBeNull();
+ });
+
+ it("degrades when a member is implicitly timed or has no patch target", () => {
+ const a = el("a");
+ const implicit = el("b", { timingSource: "implicit" });
+ const noTarget = el("c", { domId: undefined, selector: undefined });
+ expect(buildTimelineGroupResizeMembers([a, implicit], keys("a", "b"), "a", "end")).toBeNull();
+ expect(buildTimelineGroupResizeMembers([a, noTarget], keys("a", "c"), "a", "end")).toBeNull();
+ });
+
+ it("snapshots members and seeds start-edge media playbackStart to 0", () => {
+ const grabbed = el("a", { start: 2, duration: 2 });
+ const audio = el("b", { tag: "audio", start: 5, duration: 3 }); // playbackStart undefined
+ const members = buildTimelineGroupResizeMembers([grabbed, audio], keys("a", "b"), "a", "start");
+ expect(members).not.toBeNull();
+ expect(members!.map((m) => [m.key, m.start, m.duration, m.playbackStart])).toEqual([
+ ["a", 2, 2, 0], // start-edge media seeds playbackStart to 0
+ ["b", 5, 3, 0],
+ ]);
+ });
+
+ it("does not seed playbackStart on the END edge", () => {
+ const grabbed = el("a", { tag: "audio", start: 0, duration: 2 });
+ const b = el("b", { tag: "audio", start: 3, duration: 2 });
+ const members = buildTimelineGroupResizeMembers([grabbed, b], keys("a", "b"), "a", "end");
+ expect(members!.every((m) => m.playbackStart === undefined)).toBe(true);
+ });
+});
+
+describe("resolveTimelineGroupResizeChanges (rigid group patch set)", () => {
+ it("END edge: extends every member's duration by the shared delta", () => {
+ const members = buildTimelineGroupResizeMembers(
+ [el("a", { duration: 2 }), el("b", { duration: 3 })],
+ keys("a", "b"),
+ "a",
+ "end",
+ )!;
+ const changes = resolveTimelineGroupResizeChanges(members, "end", 0.5);
+ expect(changes.map((c) => [c.key, c.start, c.duration])).toEqual([
+ ["a", 0, 2.5],
+ ["b", 0, 3.5],
+ ]);
+ });
+
+ it("END edge: rigid — the most-constrained member clamps the whole group", () => {
+ // b (0.2s) can only shrink 0.1 before hitting min duration, so the group as a
+ // whole shrinks 0.1 even though the grabbed clip asked for -0.5.
+ const members = buildTimelineGroupResizeMembers(
+ [el("a", { duration: 2 }), el("b", { duration: 0.2 })],
+ keys("a", "b"),
+ "a",
+ "end",
+ )!;
+ const changes = resolveTimelineGroupResizeChanges(members, "end", -0.5);
+ expect(changes.map((c) => c.duration)).toEqual([1.9, 0.1]);
+ });
+
+ it("START edge: shifts start + duration together across the group", () => {
+ const members = buildTimelineGroupResizeMembers(
+ [
+ el("a", { tag: "text", start: 2, duration: 2 }),
+ el("b", { tag: "text", start: 5, duration: 3 }),
+ ],
+ keys("a", "b"),
+ "a",
+ "start",
+ )!;
+ const changes = resolveTimelineGroupResizeChanges(members, "start", -0.5);
+ expect(changes.map((c) => [c.key, c.start, c.duration])).toEqual([
+ ["a", 1.5, 2.5],
+ ["b", 4.5, 3.5],
+ ]);
+ });
+
+ it("produces exactly the resolveTimelineGroupResize output, keyed per member", () => {
+ const members = buildTimelineGroupResizeMembers(
+ [el("a", { duration: 2 }), el("b", { duration: 4 })],
+ keys("a", "b"),
+ "a",
+ "end",
+ )!;
+ const raw = resolveTimelineGroupResize(members, "end", 0.75);
+ const changes = resolveTimelineGroupResizeChanges(members, "end", 0.75);
+ expect(
+ changes.map((c) => ({
+ start: c.start,
+ duration: c.duration,
+ playbackStart: c.playbackStart,
+ })),
+ ).toEqual(raw.members);
+ });
+});
diff --git a/packages/studio/src/player/components/timelineGroupEditing.ts b/packages/studio/src/player/components/timelineGroupEditing.ts
index 65533df135..5e16f578af 100644
--- a/packages/studio/src/player/components/timelineGroupEditing.ts
+++ b/packages/studio/src/player/components/timelineGroupEditing.ts
@@ -1,4 +1,6 @@
import { roundToCenti } from "../../utils/rounding";
+import type { TimelineElement } from "../store/playerStore";
+import { getTimelineEditCapabilities } from "./timelineEditCapabilities";
const DEFAULT_TIMELINE_MIN_DURATION = 0.1;
const ABSOLUTE_TIMELINE_MIN_DURATION = 0.05;
@@ -157,3 +159,134 @@ export function resolveTimelineGroupResize(
}),
};
}
+
+/* ── Multi-select group resize wiring (restored from main 36413da7f) ───────── */
+
+/** A selected clip snapshot captured at group-resize gesture start. */
+export interface TimelineGroupResizeMember extends TimelineGroupTimingMember {
+ element: TimelineElement;
+ key: string;
+}
+
+/** Per-member timing patch produced by a group resize (grabbed clip included). */
+export interface TimelineGroupResizeChange {
+ element: TimelineElement;
+ key: string;
+ start: number;
+ duration: number;
+ playbackStart?: number;
+}
+
+function elementKey(element: TimelineElement): string {
+ return element.key ?? element.id;
+}
+
+function isMediaTimelineElement(element: TimelineElement): boolean {
+ const tag = element.tag.toLowerCase();
+ return tag === "audio" || tag === "video";
+}
+
+function canTrimEdge(element: TimelineElement, edge: TimelineGroupResizeEdge): boolean {
+ const caps = getTimelineEditCapabilities({
+ tag: element.tag,
+ duration: element.duration,
+ domId: element.domId,
+ selector: element.selector,
+ compositionSrc: element.compositionSrc,
+ playbackStart: element.playbackStart,
+ playbackStartAttr: element.playbackStartAttr,
+ sourceDuration: element.sourceDuration,
+ timingSource: element.timingSource,
+ timelineLocked: element.timelineLocked,
+ });
+ return edge === "start" ? caps.canTrimStart : caps.canTrimEnd;
+}
+
+/**
+ * Snapshot the members for a group resize, or `null` when the gesture must stay a
+ * single-clip resize. Legacy semantics (main 36413da7f): a group forms only when
+ * the grabbed clip is part of a multi-selection (> 1) AND EVERY selected member
+ * can take THIS edge's trim. It is all-or-nothing — if any member is locked or
+ * implicitly-timed the group does not form, so a locked member is never patched
+ * (the grabbed clip then resizes on its own). Start-edge media members seed
+ * `playbackStart` to 0 so the in-point trim math has a base, mirroring the legacy
+ * `resizeMember`.
+ */
+export function buildTimelineGroupResizeMembers(
+ elements: readonly TimelineElement[],
+ selectedKeys: ReadonlySet<string>,
+ grabbedKey: string,
+ edge: TimelineGroupResizeEdge,
+): TimelineGroupResizeMember[] | null {
+ if (selectedKeys.size <= 1 || !selectedKeys.has(grabbedKey)) return null;
+ const selected = elements.filter((element) => selectedKeys.has(elementKey(element)));
+ if (selected.length <= 1) return null;
+ if (!selected.every((element) => canTrimEdge(element, edge))) return null;
+ return selected.map((element) => ({
+ element,
+ key: elementKey(element),
+ start: element.start,
+ duration: element.duration,
+ playbackStart:
+ edge === "start" && isMediaTimelineElement(element)
+ ? (element.playbackStart ?? 0)
+ : element.playbackStart,
+ playbackRate: element.playbackRate,
+ }));
+}
+
+/**
+ * Resolve the per-member timing patches for a group resize from the grabbed
+ * clip's raw edge delta. Rigid group: one shared delta, clamped by the most
+ * constrained member (see resolveTimelineGroupResize), applied to every member.
+ */
+export function resolveTimelineGroupResizeChanges(
+ members: readonly TimelineGroupResizeMember[],
+ edge: TimelineGroupResizeEdge,
+ rawDelta: number,
+ minDuration = resolveTimelineMinDuration(),
+): TimelineGroupResizeChange[] {
+ const result = resolveTimelineGroupResize(members, edge, rawDelta, minDuration);
+ return result.members.map((member, index) => ({
+ element: members[index]!.element,
+ key: members[index]!.key,
+ start: member.start,
+ duration: member.duration,
+ playbackStart: member.playbackStart,
+ }));
+}
+
+/** In-flight multi-select group-resize gesture (owned by the drag hook). */
+export interface TimelineGroupResizeSession {
+ grabbedKey: string;
+ edge: TimelineGroupResizeEdge;
+ members: TimelineGroupResizeMember[];
+ changes: TimelineGroupResizeChange[];
+ hasChanged: boolean;
+}
+
+/**
+ * Fold the grabbed clip's single-clip preview into the group: derive the raw
+ * edge delta from it, resolve the rigid per-member changes onto the session
+ * (updating `changes` + `hasChanged`), and return the grabbed clip's own change
+ * so the caller can render it from the resize state.
+ */
+export function applyTimelineGroupResizePreview(
+ session: TimelineGroupResizeSession,
+ grabbedPreview: { previewStart: number; previewDuration: number },
+): TimelineGroupResizeChange | undefined {
+ const grabbed = session.members.find((m) => m.key === session.grabbedKey);
+ const rawDelta =
+ session.edge === "start"
+ ? grabbedPreview.previewStart - (grabbed?.start ?? grabbedPreview.previewStart)
+ : grabbedPreview.previewDuration - (grabbed?.duration ?? grabbedPreview.previewDuration);
+ const changes = resolveTimelineGroupResizeChanges(session.members, session.edge, rawDelta);
+ session.changes = changes;
+ session.hasChanged = changes.some(
+ (c, i) =>
+ c.start !== session.members[i]!.start ||
+ c.duration !== session.members[i]!.duration ||
+ c.playbackStart !== session.members[i]!.playbackStart,
+ );
+ return changes.find((c) => c.key === session.grabbedKey);
+}
diff --git a/packages/studio/src/player/components/timelineGroupResizeCommit.ts b/packages/studio/src/player/components/timelineGroupResizeCommit.ts
new file mode 100644
index 0000000000..0ccac01f1a
--- /dev/null
+++ b/packages/studio/src/player/components/timelineGroupResizeCommit.ts
@@ -0,0 +1,54 @@
+import type { TimelineElement } from "../store/playerStore";
+import type { TimelineEditCallbacks } from "./timelineCallbacks";
+import type { TimelineGroupResizeSession } from "./timelineGroupEditing";
+import {
+ beginTimelineOptimisticGesture,
+ rollbackLatestTimelineOptimisticGesture,
+} from "./timelineOptimisticRevision";
+
+export function commitTimelineGroupResize(
+ session: TimelineGroupResizeSession,
+ updateElement: (key: string, updates: Partial<TimelineElement>) => void,
+ persist: TimelineEditCallbacks["onResizeElements"],
+): void {
+ if (!session.hasChanged) return;
+ const changes = session.changes;
+ const revision = beginTimelineOptimisticGesture(
+ updateElement,
+ changes.map((change) => change.key),
+ );
+ for (const change of changes) {
+ updateElement(change.key, {
+ start: change.start,
+ duration: change.duration,
+ playbackStart: change.playbackStart,
+ });
+ }
+ if (!persist) {
+ rollbackLatestTimelineOptimisticGesture(
+ updateElement,
+ revision,
+ session.members.map((member) => ({ key: member.key, updates: member })),
+ );
+ return;
+ }
+ const coalesceKey = `clip-group-resize:${changes.map((change) => change.key).join(":")}`;
+ Promise.resolve(
+ persist(
+ changes.map((change) => ({
+ element: change.element,
+ start: change.start,
+ duration: change.duration,
+ playbackStart: change.playbackStart,
+ })),
+ { coalesceKey },
+ ),
+ ).catch((error) => {
+ rollbackLatestTimelineOptimisticGesture(
+ updateElement,
+ revision,
+ session.members.map((member) => ({ key: member.key, updates: member })),
+ );
+ console.error("[Timeline] Failed to persist group clip resize", error);
+ });
+}
diff --git a/packages/studio/src/player/components/timelineLayout.test.ts b/packages/studio/src/player/components/timelineLayout.test.ts
index 98f8217ebd..24e746e612 100644
--- a/packages/studio/src/player/components/timelineLayout.test.ts
+++ b/packages/studio/src/player/components/timelineLayout.test.ts
@@ -1,34 +1,106 @@
-import { describe, expect, it } from "vitest";
-import { computeTimelineBasisDuration, computeTimelineEffectiveDuration } from "./timelineLayout";
+import { describe, it, expect } from "vitest";
+import {
+ RULER_H,
+ TRACK_H,
+ TRACKS_TOP_PAD,
+ TRACKS_BOTTOM_PAD,
+ GUTTER,
+ getTimelineRowTop,
+ getTimelineRowFromY,
+ getTimelineCanvasHeight,
+ resolveTimelineAssetDrop,
+} from "./timelineLayout";
-describe("computeTimelineBasisDuration", () => {
- it("uses the root duration when it exceeds every clip end", () => {
- expect(computeTimelineBasisDuration(12, [4, 6, 9])).toBe(12);
- });
+describe("track-area breathing pad y-math", () => {
+ describe("getTimelineRowTop", () => {
+ it("offsets the first lane below the ruler by the top pad", () => {
+ expect(getTimelineRowTop(0)).toBe(RULER_H + TRACKS_TOP_PAD);
+ });
- it("grows to the furthest committed clip end past the root duration", () => {
- expect(computeTimelineBasisDuration(12, [4, 18, 9])).toBe(18);
- });
+ it("advances by one track height per row, keeping the pad", () => {
+ expect(getTimelineRowTop(1)).toBe(RULER_H + TRACKS_TOP_PAD + TRACK_H);
+ expect(getTimelineRowTop(3)).toBe(RULER_H + TRACKS_TOP_PAD + 3 * TRACK_H);
+ });
- it("falls back to the root duration with no clips / non-finite ends", () => {
- expect(computeTimelineBasisDuration(10, [])).toBe(10);
- expect(computeTimelineBasisDuration(Number.NaN, [])).toBe(0);
+ it("is a strict positive shift from the pre-pad formula (pad is non-zero)", () => {
+ expect(TRACKS_TOP_PAD).toBeGreaterThan(0);
+ expect(getTimelineRowTop(2)).toBe(RULER_H + 2 * TRACK_H + TRACKS_TOP_PAD);
+ });
});
-});
-describe("computeTimelineEffectiveDuration", () => {
- it("returns the basis when there is no active preview", () => {
- expect(computeTimelineEffectiveDuration(12, [null, null])).toBe(12);
+ describe("getTimelineRowFromY", () => {
+ it("is the exact inverse of getTimelineRowTop at lane boundaries", () => {
+ for (const row of [0, 1, 2, 7]) {
+ expect(getTimelineRowFromY(getTimelineRowTop(row))).toBeCloseTo(row, 10);
+ }
+ });
+
+ it("floors a y inside the top pad (above lane 0) to a negative fraction", () => {
+ // A drop in the pad between the ruler and lane 0 sits at row < 0, so a
+ // floor lands it on row -1 → getDefaultDroppedTrack floors to the top lane.
+ const yInPad = RULER_H + TRACKS_TOP_PAD / 2;
+ expect(getTimelineRowFromY(yInPad)).toBeLessThan(0);
+ });
+
+ it("maps a y in the middle of lane 1 into [1,2)", () => {
+ const yMidLane1 = getTimelineRowTop(1) + TRACK_H / 2;
+ const row = getTimelineRowFromY(yMidLane1);
+ expect(row).toBeGreaterThanOrEqual(1);
+ expect(row).toBeLessThan(2);
+ });
});
- it("extends to a drag/resize preview end beyond the basis", () => {
- expect(computeTimelineEffectiveDuration(12, [20, null])).toBe(20);
- expect(computeTimelineEffectiveDuration(12, [null, 16])).toBe(16);
+ describe("getTimelineCanvasHeight", () => {
+ it("reserves ruler + top pad + lanes + bottom pad", () => {
+ expect(getTimelineCanvasHeight(0)).toBe(RULER_H + TRACKS_TOP_PAD + TRACKS_BOTTOM_PAD);
+ expect(getTimelineCanvasHeight(3)).toBe(
+ RULER_H + TRACKS_TOP_PAD + 3 * TRACK_H + TRACKS_BOTTOM_PAD,
+ );
+ });
+
+ it("clamps a negative track count to zero lanes", () => {
+ expect(getTimelineCanvasHeight(-4)).toBe(RULER_H + TRACKS_TOP_PAD + TRACKS_BOTTOM_PAD);
+ });
+
+ it("leaves room below the last lane for a drag-into-void new track", () => {
+ // The gap below the final lane must be at least a full track height so a
+ // clip can be dropped there to create a new bottom track.
+ const oneLane = getTimelineCanvasHeight(1);
+ const lastLaneBottom = getTimelineRowTop(0) + TRACK_H;
+ expect(oneLane - lastLaneBottom).toBeGreaterThanOrEqual(TRACK_H);
+ });
});
- it("never shrinks below the basis for a preview inside the current length", () => {
- // The invariant behind the jump fix: the basis (which drives zoom) is
- // independent of the preview, and a smaller preview end can't reduce it.
- expect(computeTimelineEffectiveDuration(12, [8])).toBe(12);
+ describe("resolveTimelineAssetDrop honours the top pad", () => {
+ const base = {
+ rectLeft: 0,
+ rectTop: 0,
+ scrollLeft: 0,
+ scrollTop: 0,
+ pixelsPerSecond: 100,
+ duration: 60,
+ trackHeight: TRACK_H,
+ trackOrder: [0, 1, 2],
+ };
+
+ 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 { start, track } = resolveTimelineAssetDrop(base, clientX, clientY);
+ expect(track).toBe(0);
+ expect(start).toBe(1);
+ });
+
+ it("drops into the top pad → floors to the first lane (row < 0)", () => {
+ const clientY = RULER_H + TRACKS_TOP_PAD / 2; // inside the pad, above lane 0
+ const { track } = resolveTimelineAssetDrop(base, GUTTER, clientY);
+ expect(track).toBe(0);
+ });
+
+ it("drops below the last lane → appends a new track", () => {
+ const clientY = getTimelineRowTop(2) + TRACK_H + 4; // in the bottom pad
+ const { track } = resolveTimelineAssetDrop(base, GUTTER, clientY);
+ expect(track).toBe(3); // max(trackOrder)+1
+ });
});
});
diff --git a/packages/studio/src/player/components/timelineLayout.ts b/packages/studio/src/player/components/timelineLayout.ts
index d2ecaabed4..ce7cfbbeac 100644
--- a/packages/studio/src/player/components/timelineLayout.ts
+++ b/packages/studio/src/player/components/timelineLayout.ts
@@ -7,38 +7,66 @@ export const TRACK_H = 48;
export const RULER_H = 24;
export const CLIP_Y = 3;
export const CLIP_HANDLE_W = 18;
-const TIMELINE_SCROLL_BUFFER = 20;
-
-/* ── Timeline duration ─────────────────────────────────────────────── */
+/**
+ * Half-width (as a fraction of TRACK_H) of the new-track INSERT band that
+ * straddles each lane boundary. Deliberately equals the clip's vertical inset
+ * (`CLIP_Y / TRACK_H`): a clip body fills [CLIP_Y, TRACK_H − CLIP_Y] of its row,
+ * so the ONLY region this band covers is the visible empty gutter between two
+ * clip bodies (plus the top/bottom breathing pads, handled separately by the
+ * rowFloat ≤ 0 / ≥ trackCount extremes). Aiming at a clip body is therefore a
+ * move-to-that-lane; only the inter-clip gap arms an insert — see resolveInsertRow.
+ * Threaded into resolveInsertRow by the drag preview so the hit band can never
+ * drift from the rendered clip geometry.
+ */
+export const INSERT_BOUNDARY_BAND = CLIP_Y / TRACK_H;
+/**
+ * Breathing room INSIDE the scroll area (CapCut-style), threaded through every
+ * track-row y computation via {@link getTimelineRowTop} — never inline a magic
+ * offset; a track row's top is always `RULER_H + TRACKS_TOP_PAD + row*TRACK_H`.
+ *
+ * - TRACKS_TOP_PAD: empty space between the (sticky) ruler and the first track
+ * (~half a track height) so the first clip isn't jammed under the ruler.
+ * - TRACKS_BOTTOM_PAD: empty space below the last track (~1.5 track heights),
+ * enough to comfortably drag a clip into the void to create a new bottom lane.
+ */
+export const TRACKS_TOP_PAD = 50;
+export const TRACKS_BOTTOM_PAD = Math.round(TRACK_H * 1.5);
-// Committed timeline length: root duration or the furthest committed clip end,
-// with NO live drag/resize preview. This drives the zoom (fit-to-width pps) so
-// the pixels-per-second mapping stays fixed while you drag — otherwise a clip
-// dragged past the end grows the duration, shrinks pps, and jumps under the
-// pointer (a positive-feedback loop). The zoom re-fits once on drop.
-export function computeTimelineBasisDuration(
- rootDuration: number,
- clipEnds: readonly number[],
-): number {
- const safeDur = Number.isFinite(rootDuration) ? rootDuration : 0;
- if (clipEnds.length === 0) return safeDur;
- const maxEnd = Math.max(safeDur, ...clipEnds);
- return Number.isFinite(maxEnd) ? maxEnd : safeDur;
+/**
+ * The y (content-space) of the top edge of track ROW index `row` (0 = first
+ * displayed lane). The single source of truth for row→y — the ruler height plus
+ * the top breathing pad plus whole track lanes above it. Every clip/ghost/
+ * placeholder/insertion top and every pointer-y→row inversion goes through this
+ * (or its inverse in {@link getTimelineRowFromY}) so the pad can never drift.
+ */
+export function getTimelineRowTop(row: number): number {
+ return RULER_H + TRACKS_TOP_PAD + row * TRACK_H;
}
-// Displayed length: the basis plus any active drag/resize preview end, so the
-// ruler and track width grow to follow a clip dragged past the current end
-// (with the zoom held fixed, the extra length becomes scrollable content).
-export function computeTimelineEffectiveDuration(
- basisDuration: number,
- previewEnds: readonly (number | null)[],
-): number {
- let maxEnd = basisDuration;
- for (const end of previewEnds) {
- if (end != null && Number.isFinite(end)) maxEnd = Math.max(maxEnd, end);
- }
- return maxEnd;
+/**
+ * Inverse of {@link getTimelineRowTop}: the fractional row index for a content-
+ * space y (used for insert-row / drop-lane decisions). Subtracts the ruler and
+ * top pad before dividing by the track height.
+ */
+export function getTimelineRowFromY(contentY: number): number {
+ return (contentY - RULER_H - TRACKS_TOP_PAD) / TRACK_H;
}
+/**
+ * While a clip drag is live, the rendered timeline extends this far past the
+ * ghost's end so the right-edge auto-scroll zone always has room to keep
+ * stepping — that's what lets a drag extend the timeline past its current
+ * rendered width (see Timeline.tsx displayContentWidth).
+ */
+export const DRAG_EXTEND_MARGIN_PX = 160;
+/**
+ * The rendered timeline always spans at least this many seconds of ruler +
+ * track lanes, even when the composition is shorter — the empty space on the
+ * right is a real, drag/drop-enabled surface (clips can be moved into it; the
+ * composition grows on commit, content-driven). In fit mode the fit pps is
+ * derived against this floor, so a 10s comp renders as ~1/6 of the viewport
+ * with 60s of ruler after it.
+ */
+export const MIN_TIMELINE_EXTENT_S = 60;
/* ── Tick generation ──────────────────────────────────────────────── */
function getMajorTickInterval(duration: number, pixelsPerSecond?: number): number {
@@ -54,15 +82,15 @@ function getMajorTickInterval(duration: number, pixelsPerSecond?: number): numbe
return durationIntervals.find((interval) => interval >= target) ?? 60;
}
-function getMinorTickInterval(majorInterval: number, pixelsPerSecond?: number): number {
- if (
- Number.isFinite(pixelsPerSecond) &&
- (pixelsPerSecond ?? 0) > 0 &&
- (majorInterval / 2) * (pixelsPerSecond ?? 0) < 12
- ) {
- return 0;
- }
- return majorInterval / 2;
+// How many equal parts to split each major interval into for minor ticks. Prefer
+// quarters (4) so the midpoint stays a minor tick; fall back to halves (2) then
+// none (0) as ticks get too dense to read (< ~8px apart).
+function getMinorSubdivisions(majorInterval: number, pixelsPerSecond?: number): number {
+ const pps = Number.isFinite(pixelsPerSecond) ? (pixelsPerSecond ?? 0) : 0;
+ if (pps <= 0) return 4; // no zoom info (duration-fit mode): quarter ticks
+ if ((majorInterval / 4) * pps >= 8) return 4;
+ if ((majorInterval / 2) * pps >= 8) return 2;
+ return 0;
}
export function generateTicks(
@@ -72,39 +100,25 @@ export function generateTicks(
if (duration <= 0 || !Number.isFinite(duration) || duration > 7200)
return { major: [], minor: [] };
const majorInterval = getMajorTickInterval(duration, pixelsPerSecond);
- const minorInterval = getMinorTickInterval(majorInterval, pixelsPerSecond);
+ const subdivisions = getMinorSubdivisions(majorInterval, pixelsPerSecond);
+ const minorInterval = subdivisions > 0 ? majorInterval / subdivisions : 0;
const major: number[] = [];
const minor: number[] = [];
const maxTicks = 2000; // Safety cap to prevent runaway tick generation
for (let t = 0; t <= duration + 0.001 && major.length < maxTicks; t += majorInterval) {
const rounded = Math.round(t * 100) / 100;
major.push(rounded);
- if (minorInterval > 0 && major.length + minor.length < maxTicks) {
- const midpoint = Math.round((t + minorInterval) * 100) / 100;
- if (midpoint <= duration + 0.001) minor.push(midpoint);
+ // Emit the (subdivisions - 1) minor ticks between this major and the next.
+ for (let k = 1; k < subdivisions && major.length + minor.length < maxTicks; k++) {
+ const m = Math.round((t + k * minorInterval) * 100) / 100;
+ if (m <= duration + 0.001) minor.push(m);
}
}
return { major, minor };
}
-/**
- * Ticks spanning the full visible ruler width, not just the composition, so a
- * zoomed-out ruler stays filled with labels instead of ending mid-panel. The
- * major/minor interval is driven by pixelsPerSecond (pixel spacing), so widening
- * the range keeps spacing identical — it only adds ticks past the content end.
- */
-export function generateVisibleTicks(
- effectiveDuration: number,
- pixelsPerSecond: number,
- viewportWidth: number,
- gutter: number,
-): { major: number[]; minor: number[] } {
- const visible = viewportWidth > gutter ? (viewportWidth - gutter) / pixelsPerSecond : 0;
- return generateTicks(Math.max(effectiveDuration, visible), pixelsPerSecond);
-}
-
export function formatTimelineTickLabel(time: number, duration: number, majorInterval: number) {
- if (!Number.isFinite(time)) return "0:00";
+ if (!Number.isFinite(time)) return "00:00";
const safeTime = Math.max(0, time);
if (majorInterval < 0.1) {
const totalHundredths = Math.round(safeTime * 100);
@@ -128,6 +142,45 @@ export function formatTimelineTickLabel(time: number, duration: number, majorInt
return formatTime(safeTime);
}
+/* ── Width / duration derivation ──────────────────────────────────── */
+/**
+ * Fit-mode pixels-per-second: fill the viewport with the composition, but
+ * never map fewer than MIN_TIMELINE_EXTENT_S seconds onto it — a short comp
+ * takes a fraction of the width and the remaining ruler runs to 1:00.
+ * Manual zoom multiplies this base, so the floor only anchors the default.
+ */
+export function getTimelineFitPps(viewportWidth: number, effectiveDuration: number): number {
+ const safeDuration =
+ Number.isFinite(effectiveDuration) && effectiveDuration > 0 ? effectiveDuration : 0;
+ const span = Math.max(safeDuration, MIN_TIMELINE_EXTENT_S);
+ if (!Number.isFinite(viewportWidth) || viewportWidth <= GUTTER) return 100;
+ return (viewportWidth - GUTTER - 2) / span;
+}
+
+/**
+ * The rendered timeline extent in px. Always covers, whichever is largest:
+ * the actual clip content, the visible viewport (no dead black after short
+ * content — CapCut-style), a live drag or resize ghost plus the auto-scroll
+ * margin (drag/trim-to-extend), and the MIN_TIMELINE_EXTENT_S floor. Only the
+ * RENDERED extent grows; clip positions/durations are untouched.
+ */
+export function getTimelineDisplayContentWidth(input: {
+ trackContentWidth: number;
+ viewportWidth: number;
+ pps: number;
+ dragGhostEndPx?: number;
+ resizeGhostEndPx?: number;
+}): number {
+ const safePps = Number.isFinite(input.pps) ? Math.max(input.pps, 0) : 0;
+ return Math.max(
+ input.trackContentWidth,
+ input.viewportWidth - GUTTER - 2,
+ input.dragGhostEndPx ?? 0,
+ input.resizeGhostEndPx ?? 0,
+ MIN_TIMELINE_EXTENT_S * safePps,
+ );
+}
+
/* ── Scroll / zoom helpers ────────────────────────────────────────── */
export function shouldAutoScrollTimeline(
zoomMode: ZoomMode,
@@ -180,7 +233,10 @@ export function getTimelinePlayheadLeft(time: number, pixelsPerSecond: number):
}
export function getTimelineCanvasHeight(trackCount: number): number {
- return RULER_H + Math.max(0, trackCount) * TRACK_H + TIMELINE_SCROLL_BUFFER;
+ // RULER_H + top pad + lanes + bottom pad. The old TIMELINE_SCROLL_BUFFER is
+ // subsumed by TRACKS_BOTTOM_PAD (which is larger), so the drag-into-void space
+ // below the last lane is real scrollable surface, not a hidden buffer.
+ return RULER_H + TRACKS_TOP_PAD + Math.max(0, trackCount) * TRACK_H + TRACKS_BOTTOM_PAD;
}
/* ── UI helpers ───────────────────────────────────────────────────── */
@@ -245,12 +301,15 @@ export function resolveTimelineAssetDrop(
clientY: number,
): { start: number; track: number } {
const x = clientX - input.rectLeft + input.scrollLeft - GUTTER;
- const y = clientY - input.rectTop + input.scrollTop - RULER_H;
+ const contentY = clientY - input.rectTop + input.scrollTop;
const start = Math.max(
0,
Math.min(input.duration, Math.round((x / Math.max(input.pixelsPerSecond, 1)) * 100) / 100),
);
- const rowIndex = Math.floor(y / Math.max(input.trackHeight, 1));
+ // Row from the shared row→y inverse so the top pad is honoured; a drop in the
+ // pad above the first lane floors to row 0, a drop in the bottom pad rounds
+ // past the last lane (getDefaultDroppedTrack then appends a new track).
+ const rowIndex = Math.floor(getTimelineRowFromY(contentY));
return {
start,
track: getDefaultDroppedTrack(input.trackOrder, rowIndex),
diff --git a/packages/studio/src/player/components/timelineMarquee.test.ts b/packages/studio/src/player/components/timelineMarquee.test.ts
new file mode 100644
index 0000000000..b185841b23
--- /dev/null
+++ b/packages/studio/src/player/components/timelineMarquee.test.ts
@@ -0,0 +1,197 @@
+import { describe, it, expect } from "vitest";
+import {
+ MARQUEE_DRAG_THRESHOLD_PX,
+ isMarqueeDrag,
+ isTimelineRulerPress,
+ getMarqueeRect,
+ getTimelineClipRect,
+ computeMarqueeSelection,
+} from "./timelineMarquee";
+import { GUTTER, TRACK_H, RULER_H, CLIP_Y, getTimelineRowTop } from "./timelineLayout";
+
+describe("isTimelineRulerPress", () => {
+ const rectTop = 500; // scroll container's viewport top
+
+ it("treats a press inside the ruler band as a ruler press (unscrolled)", () => {
+ expect(isTimelineRulerPress(rectTop, rectTop)).toBe(true);
+ expect(isTimelineRulerPress(rectTop + RULER_H - 1, rectTop)).toBe(true);
+ });
+
+ it("treats a press below the ruler band as a body press", () => {
+ expect(isTimelineRulerPress(rectTop + RULER_H, rectTop)).toBe(false);
+ expect(isTimelineRulerPress(rectTop + RULER_H + 100, rectTop)).toBe(false);
+ });
+
+ it("stays a ruler press when the body is scrolled down (sticky ruler)", () => {
+ // The ruler is position:sticky — scrolled down, its VISUAL band is still
+ // the top RULER_H px of the container. Content-space math
+ // (clientY - rectTop + scrollTop) would report y = 10 + 300 = 310 ≥ RULER_H
+ // and misclassify this as a body/marquee press; viewport-space math must
+ // still classify it as a ruler press regardless of scrollTop.
+ const scrollTop = 300;
+ const clientY = rectTop + 10; // visually on the stuck ruler
+ const contentSpaceY = clientY - rectTop + scrollTop;
+ expect(contentSpaceY).toBeGreaterThanOrEqual(RULER_H); // the old, broken signal
+ expect(isTimelineRulerPress(clientY, rectTop)).toBe(true);
+ });
+
+ it("honors a custom ruler height", () => {
+ expect(isTimelineRulerPress(rectTop + 30, rectTop, 32)).toBe(true);
+ expect(isTimelineRulerPress(rectTop + 33, rectTop, 32)).toBe(false);
+ });
+});
+
+describe("isMarqueeDrag", () => {
+ it("treats sub-threshold movement as a click, not a drag", () => {
+ expect(isMarqueeDrag(100, 50, 100, 50)).toBe(false);
+ expect(
+ isMarqueeDrag(
+ 100,
+ 50,
+ 100 + MARQUEE_DRAG_THRESHOLD_PX - 1,
+ 50 + MARQUEE_DRAG_THRESHOLD_PX - 1,
+ ),
+ ).toBe(false);
+ });
+
+ it("becomes a drag once either axis passes the threshold", () => {
+ expect(isMarqueeDrag(100, 50, 100 + MARQUEE_DRAG_THRESHOLD_PX, 50)).toBe(true);
+ expect(isMarqueeDrag(100, 50, 100, 50 + MARQUEE_DRAG_THRESHOLD_PX)).toBe(true);
+ expect(isMarqueeDrag(100, 50, 100 - MARQUEE_DRAG_THRESHOLD_PX, 50)).toBe(true);
+ });
+});
+
+describe("getMarqueeRect", () => {
+ it("builds a rect from origin to current for a down-right drag", () => {
+ expect(getMarqueeRect(10, 20, 110, 70)).toEqual({ left: 10, top: 20, width: 100, height: 50 });
+ });
+
+ it("normalizes negative drags (up-left) into a positive rect", () => {
+ expect(getMarqueeRect(110, 70, 10, 20)).toEqual({ left: 10, top: 20, width: 100, height: 50 });
+ });
+
+ it("normalizes mixed-direction drags (down-left / up-right)", () => {
+ expect(getMarqueeRect(110, 20, 10, 70)).toEqual({ left: 10, top: 20, width: 100, height: 50 });
+ expect(getMarqueeRect(10, 70, 110, 20)).toEqual({ left: 10, top: 20, width: 100, height: 50 });
+ });
+
+ it("yields a zero-size rect when the pointer has not moved", () => {
+ expect(getMarqueeRect(42, 42, 42, 42)).toEqual({ left: 42, top: 42, width: 0, height: 0 });
+ });
+});
+
+describe("getTimelineClipRect", () => {
+ const trackOrder = [0, 2, 5];
+
+ 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,
+ top: getTimelineRowTop(1) + CLIP_Y,
+ width: 300,
+ height: TRACK_H - CLIP_Y * 2,
+ });
+ });
+
+ 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);
+ });
+
+ it("uses the row index in trackOrder, not the raw track number", () => {
+ const rect = getTimelineClipRect({ start: 0, duration: 1, track: 5 }, trackOrder, 50);
+ expect(rect?.top).toBe(getTimelineRowTop(2) + CLIP_Y);
+ });
+
+ it("enforces the 4px minimum rendered width", () => {
+ const rect = getTimelineClipRect({ start: 0, duration: 0.01, track: 0 }, trackOrder, 10);
+ expect(rect?.width).toBe(4);
+ });
+
+ it("returns null for a track that is not displayed or an invalid pps", () => {
+ expect(getTimelineClipRect({ start: 0, duration: 1, track: 9 }, trackOrder, 100)).toBeNull();
+ expect(getTimelineClipRect({ start: 0, duration: 1, track: 0 }, trackOrder, 0)).toBeNull();
+ expect(getTimelineClipRect({ start: 0, duration: 1, track: 0 }, trackOrder, NaN)).toBeNull();
+ });
+});
+
+describe("computeMarqueeSelection", () => {
+ // Two visible tracks: row 0 = track 0, row 1 = track 1. pps 100.
+ const trackOrder = [0, 1];
+ const pps = 100;
+ const clips = [
+ { id: "a", start: 0, duration: 1, track: 0 }, // x [32,132], row 0
+ { id: "b", start: 2, duration: 1, track: 0 }, // x [232,332], row 0
+ { id: "c", start: 0.5, duration: 1, track: 1 }, // x [82,182], row 1
+ ];
+ const row0Top = getTimelineRowTop(0) + CLIP_Y;
+ 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 { 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 { 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 { 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 { ids, primaryId } = computeMarqueeSelection({
+ clips,
+ trackOrder,
+ pps,
+ marquee,
+ baseSelection: ["b"],
+ });
+ expect(ids).toEqual(new Set(["b"]));
+ expect(primaryId).toBeNull();
+ });
+
+ it("unions additive base selection with new hits; primary comes from the marquee", () => {
+ const marquee = { left: GUTTER, top: row1Top, width: 100, height: 10 };
+ const { ids, primaryId } = computeMarqueeSelection({
+ clips,
+ trackOrder,
+ pps,
+ marquee,
+ baseSelection: ["b"],
+ });
+ expect(ids).toEqual(new Set(["b", "c"]));
+ expect(primaryId).toBe("c");
+ });
+
+ 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 };
+ expect(computeMarqueeSelection({ clips, trackOrder, pps, marquee: wide }).ids).toEqual(
+ new Set(["a", "b"]),
+ );
+ expect(computeMarqueeSelection({ clips, trackOrder, pps, marquee: narrow }).ids).toEqual(
+ new Set(["a"]),
+ );
+ });
+
+ it("ignores clips on hidden/undisplayed tracks", () => {
+ const marquee = { left: 0, top: 0, width: 10000, height: 10000 };
+ const { ids } = computeMarqueeSelection({
+ clips: [{ id: "x", start: 0, duration: 1, track: 7 }],
+ trackOrder,
+ pps,
+ marquee,
+ });
+ expect(ids).toEqual(new Set());
+ });
+});
diff --git a/packages/studio/src/player/components/timelineMarquee.ts b/packages/studio/src/player/components/timelineMarquee.ts
new file mode 100644
index 0000000000..718dd86594
--- /dev/null
+++ b/packages/studio/src/player/components/timelineMarquee.ts
@@ -0,0 +1,112 @@
+import { GUTTER, TRACK_H, RULER_H, CLIP_Y, getTimelineRowTop } from "./timelineLayout";
+import { rectsOverlap, type Rect } from "../../utils/marqueeGeometry";
+
+/** Pointer must travel at least this far (either axis) before a pointerdown on
+ * the empty timeline body becomes a marquee drag instead of a plain click. */
+export const MARQUEE_DRAG_THRESHOLD_PX = 4;
+
+/** Minimum rendered clip width, mirrors TimelineClip's `Math.max(w, 4)`. */
+const MIN_CLIP_W = 4;
+
+export interface MarqueeClipInput {
+ id: string;
+ start: number;
+ duration: number;
+ track: number;
+}
+
+/**
+ * Ruler-vs-body decision for a pointerdown on the timeline scroll container.
+ *
+ * The ruler is `position: sticky; top: 0` — once the body is scrolled down its
+ * VISUAL position stays pinned to the container top while its LAYOUT position
+ * scrolls away. The hit test must therefore use VIEWPORT-space y (clientY
+ * relative to the scroll container's bounding rect), NOT content-space y
+ * (clientY - rect.top + scrollTop), which misclassifies a press on the stuck
+ * ruler as a body/marquee press whenever scrollTop > 0.
+ */
+export function isTimelineRulerPress(
+ clientY: number,
+ scrollRectTop: number,
+ rulerHeight: number = RULER_H,
+): boolean {
+ return clientY - scrollRectTop < rulerHeight;
+}
+
+export function isMarqueeDrag(
+ originX: number,
+ originY: number,
+ currentX: number,
+ currentY: number,
+ threshold: number = MARQUEE_DRAG_THRESHOLD_PX,
+): boolean {
+ return Math.abs(currentX - originX) >= threshold || Math.abs(currentY - originY) >= threshold;
+}
+
+/** Normalized marquee rect (canvas/content coordinates) from the drag origin and
+ * the current pointer — handles drags in any direction (negative deltas). */
+export function getMarqueeRect(
+ originX: number,
+ originY: number,
+ currentX: number,
+ currentY: number,
+): Rect {
+ return {
+ left: Math.min(originX, currentX),
+ top: Math.min(originY, currentY),
+ width: Math.abs(currentX - originX),
+ height: Math.abs(currentY - originY),
+ };
+}
+
+/**
+ * A clip's rendered rect in canvas/content coordinates (the same space the
+ * marquee rect lives in): x from GUTTER + start * pps, y from the clip's row
+ * index within the visible track order (RULER_H + row * TRACK_H + CLIP_Y).
+ * Returns null when the clip's track is not currently displayed.
+ */
+export function getTimelineClipRect(
+ clip: Pick<MarqueeClipInput, "start" | "duration" | "track">,
+ trackOrder: number[],
+ pps: number,
+): Rect | null {
+ const row = trackOrder.indexOf(clip.track);
+ if (row < 0 || !Number.isFinite(pps) || pps <= 0) return null;
+ return {
+ left: GUTTER + clip.start * pps,
+ top: getTimelineRowTop(row) + CLIP_Y,
+ width: Math.max(clip.duration * pps, MIN_CLIP_W),
+ height: TRACK_H - CLIP_Y * 2,
+ };
+}
+
+export interface MarqueeSelectionResult {
+ /** Every clip id the marquee currently covers (plus the additive base). */
+ ids: Set<string>;
+ /** The last marquee-hit clip in element order — the primary selection.
+ * Null when the marquee covers nothing new (caller keeps its current primary). */
+ primaryId: string | null;
+}
+
+/**
+ * Live marquee selection: every clip whose rendered rect intersects the marquee.
+ * `baseSelection` (shift/cmd-additive) is unioned in but never affects primaryId.
+ */
+export function computeMarqueeSelection(input: {
+ clips: MarqueeClipInput[];
+ trackOrder: number[];
+ pps: number;
+ marquee: Rect;
+ baseSelection?: Iterable<string>;
+}): MarqueeSelectionResult {
+ const ids = new Set<string>(input.baseSelection ?? []);
+ let primaryId: string | null = null;
+ for (const clip of input.clips) {
+ const rect = getTimelineClipRect(clip, input.trackOrder, input.pps);
+ if (rect && rectsOverlap(rect, input.marquee)) {
+ ids.add(clip.id);
+ primaryId = clip.id;
+ }
+ }
+ return { ids, primaryId };
+}
diff --git a/packages/studio/src/player/components/timelineMarqueeSelection.test.ts b/packages/studio/src/player/components/timelineMarqueeSelection.test.ts
deleted file mode 100644
index 592acb6dce..0000000000
--- a/packages/studio/src/player/components/timelineMarqueeSelection.test.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { describe, expect, it } from "vitest";
-import type { TimelineElement } from "../store/playerStore";
-import { RULER_H, TRACK_H } from "./timelineLayout";
-import { selectTimelineElementsInMarquee } from "./timelineEditing";
-import type { StackingTimelineLayer } from "./timelineTrackOrder";
-
-function element(id: string, start: number, duration: number, track: number): TimelineElement {
- return { id, tag: "div", start, duration, track };
-}
-
-function layer(id: string, elements: TimelineElement[]): StackingTimelineLayer {
- return {
- id,
- kind: "visual",
- contextKey: "",
- zIndex: 0,
- placementTrack: elements[0]?.track ?? 0,
- elements,
- };
-}
-
-describe("selectTimelineElementsInMarquee", () => {
- it("selects clips intersecting both the marquee time span and lane span", () => {
- const layers = [
- layer("lane-0", [element("first-hit", 1, 1, 0), element("time-miss", 5, 1, 0)]),
- layer("lane-1", [element("second-hit", 2.25, 1, 1)]),
- layer("lane-2", [element("lane-miss", 1.5, 1, 2)]),
- ];
-
- expect(
- selectTimelineElementsInMarquee({
- rect: {
- startTime: 0.5,
- endTime: 3,
- top: RULER_H,
- bottom: RULER_H + TRACK_H * 2,
- },
- layers,
- layerOrder: layers.map((item) => item.id),
- rulerHeight: RULER_H,
- trackHeight: TRACK_H,
- }),
- ).toEqual(["first-hit", "second-hit"]);
- });
-
- it("returns no ids when the marquee intersects no clip", () => {
- const layers = [layer("lane-0", [element("outside", 4, 1, 0)])];
-
- expect(
- selectTimelineElementsInMarquee({
- rect: {
- startTime: 0,
- endTime: 1,
- top: RULER_H,
- bottom: RULER_H + TRACK_H,
- },
- layers,
- layerOrder: ["lane-0"],
- rulerHeight: RULER_H,
- trackHeight: TRACK_H,
- }),
- ).toEqual([]);
- });
-
- it("accounts for context group headers before row hit testing", () => {
- const layers: StackingTimelineLayer[] = [
- { ...layer("lane-0", [element("above", 0, 1, 0)]), contextKey: "root" },
- { ...layer("lane-1", [element("below", 0, 1, 1)]), contextKey: "nested" },
- ];
-
- expect(
- selectTimelineElementsInMarquee({
- rect: {
- startTime: 0,
- endTime: 1,
- top: RULER_H + 18 + TRACK_H,
- bottom: RULER_H + 18 + TRACK_H + 18 + TRACK_H,
- },
- layers,
- layerOrder: ["lane-0", "lane-1"],
- rulerHeight: RULER_H,
- trackHeight: TRACK_H,
- groupHeaderHeight: 18,
- }),
- ).toEqual(["below"]);
- });
-});
diff --git a/packages/studio/src/player/components/timelineOptimisticRevision.ts b/packages/studio/src/player/components/timelineOptimisticRevision.ts
new file mode 100644
index 0000000000..5b4f9d7a2d
--- /dev/null
+++ b/packages/studio/src/player/components/timelineOptimisticRevision.ts
@@ -0,0 +1,42 @@
+import type { TimelineElement } from "../store/playerStore";
+
+type UpdateElement = (key: string, updates: Partial<TimelineElement>) => void;
+const revisionsByUpdater = new WeakMap<UpdateElement, Map<string, number>>();
+
+export function beginTimelineOptimisticGesture(
+ updateElement: UpdateElement,
+ keys: readonly string[],
+): Map<string, number> {
+ let revisions = revisionsByUpdater.get(updateElement);
+ if (!revisions) {
+ revisions = new Map();
+ revisionsByUpdater.set(updateElement, revisions);
+ }
+ const gesture = new Map<string, number>();
+ for (const key of keys) {
+ const revision = (revisions.get(key) ?? 0) + 1;
+ revisions.set(key, revision);
+ gesture.set(key, revision);
+ }
+ return gesture;
+}
+
+export function isLatestTimelineOptimisticGesture(
+ updateElement: UpdateElement,
+ gesture: ReadonlyMap<string, number>,
+ key: string,
+): boolean {
+ return revisionsByUpdater.get(updateElement)?.get(key) === gesture.get(key);
+}
+
+export function rollbackLatestTimelineOptimisticGesture(
+ updateElement: UpdateElement,
+ gesture: ReadonlyMap<string, number>,
+ rollbacks: ReadonlyArray<{ key: string; updates: Partial<TimelineElement> }>,
+): void {
+ for (const rollback of rollbacks) {
+ if (isLatestTimelineOptimisticGesture(updateElement, gesture, rollback.key)) {
+ updateElement(rollback.key, rollback.updates);
+ }
+ }
+}
diff --git a/packages/studio/src/player/components/timelineSnapTargets.test.ts b/packages/studio/src/player/components/timelineSnapTargets.test.ts
deleted file mode 100644
index 72b80d5e23..0000000000
--- a/packages/studio/src/player/components/timelineSnapTargets.test.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-import { describe, expect, it } from "vitest";
-import type { TimelineElement } from "../store/playerStore";
-import {
- buildTimelineSnapTargets,
- snapEdgesToTargets,
- snapResizeEdgeToTargets,
-} from "./timelineSnapTargets";
-
-function timelineElement(input: {
- id: string;
- key?: string;
- start: number;
- duration: number;
-}): TimelineElement {
- return {
- id: input.id,
- key: input.key,
- tag: "div",
- start: input.start,
- duration: input.duration,
- track: 0,
- };
-}
-
-describe("buildTimelineSnapTargets", () => {
- it("excludes the dragged clip's own edges", () => {
- const dragged = timelineElement({
- id: "dragged-id",
- key: "dragged-key",
- start: 1,
- duration: 2,
- });
- const other = timelineElement({ id: "other", start: 4, duration: 2 });
-
- const targets = buildTimelineSnapTargets({
- elements: [dragged, other],
- excludedKeys: new Set(["dragged-key"]),
- playhead: 8,
- compDuration: 10,
- beats: [1.5],
- });
-
- const times = targets.map((target) => target.time);
- expect(times).not.toContain(1);
- expect(times).not.toContain(3);
- expect(times).toContain(4);
- expect(times).toContain(6);
- });
-
- it("excludes every moving group member, not just the grabbed clip", () => {
- const a = timelineElement({ id: "a", start: 1, duration: 1 });
- const b = timelineElement({ id: "b", start: 3, duration: 1 });
- const other = timelineElement({ id: "other", start: 6, duration: 1 });
-
- const targets = buildTimelineSnapTargets({
- elements: [a, b, other],
- excludedKeys: new Set(["a", "b"]),
- playhead: 9,
- compDuration: 10,
- beats: [],
- });
-
- const times = targets.map((target) => target.time);
- // Both group members' edges are excluded; the non-member's edges remain.
- expect(times).not.toContain(1);
- expect(times).not.toContain(2);
- expect(times).not.toContain(3);
- expect(times).not.toContain(4);
- expect(times).toContain(6);
- expect(times).toContain(7);
- });
-
- it("dedupes near-equal times from different sources", () => {
- const dragged = timelineElement({ id: "dragged", start: 2, duration: 2 });
- const other = timelineElement({ id: "other", start: 0.0004, duration: 10 });
-
- const targets = buildTimelineSnapTargets({
- elements: [dragged, other],
- excludedKeys: new Set(["dragged"]),
- playhead: 5,
- compDuration: 10,
- beats: [0.0002, 10.0002],
- });
-
- expect(targets.filter((target) => Math.abs(target.time) < 0.001)).toHaveLength(1);
- expect(targets.filter((target) => Math.abs(target.time - 10) < 0.001)).toHaveLength(1);
- });
-});
-
-describe("snapEdgesToTargets", () => {
- it("snaps the start edge to another clip's end", () => {
- const snap = snapEdgesToTargets(3.95, 2, [{ time: 4, kind: "edge" }], 100);
-
- expect(snap).toEqual({ start: 4, snapTime: 4, snapKind: "edge" });
- });
-
- it("snaps the end edge to another clip's start", () => {
- const snap = snapEdgesToTargets(2.96, 2, [{ time: 5, kind: "edge" }], 100);
-
- expect(snap).toEqual({ start: 3, snapTime: 5, snapKind: "edge" });
- });
-
- it("snaps to the playhead", () => {
- const snap = snapEdgesToTargets(2.94, 1, [{ time: 3, kind: "playhead" }], 100);
-
- expect(snap).toEqual({ start: 3, snapTime: 3, snapKind: "playhead" });
- });
-
- it("snaps the start edge to the lower composition bound", () => {
- const snap = snapEdgesToTargets(0.04, 1, [{ time: 0, kind: "bound" }], 100);
-
- expect(snap).toEqual({ start: 0, snapTime: 0, snapKind: "bound" });
- });
-
- it("snaps the end edge to the upper composition bound", () => {
- const snap = snapEdgesToTargets(7.96, 2, [{ time: 10, kind: "bound" }], 100);
-
- expect(snap).toEqual({ start: 8, snapTime: 10, snapKind: "bound" });
- });
-
- it("does not snap when targets are beyond the pixel threshold", () => {
- const snap = snapEdgesToTargets(3.9, 1, [{ time: 4, kind: "edge" }], 100);
-
- expect(snap).toEqual({ start: 3.9, snapTime: null, snapKind: null });
- });
-});
-
-describe("snapResizeEdgeToTargets", () => {
- it("does not apply end-edge snaps past maxEnd or below minDuration", () => {
- expect(
- snapResizeEdgeToTargets("end", 4, 2.95, [{ time: 7.01, kind: "edge" }], 100, {
- minDuration: 0.05,
- maxEnd: 7,
- }),
- ).toEqual({ start: 4, duration: 2.95, snapTime: null, snapKind: null });
-
- expect(
- snapResizeEdgeToTargets("end", 4, 0.1, [{ time: 4.03, kind: "edge" }], 100, {
- minDuration: 0.05,
- maxEnd: 10,
- }),
- ).toEqual({ start: 4, duration: 0.1, snapTime: null, snapKind: null });
- });
-});
diff --git a/packages/studio/src/player/components/timelineSnapTargets.ts b/packages/studio/src/player/components/timelineSnapTargets.ts
deleted file mode 100644
index eb0daac541..0000000000
--- a/packages/studio/src/player/components/timelineSnapTargets.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-import type { TimelineElement } from "../store/playerStore";
-
-export type TimelineSnapKind = "beat" | "edge" | "playhead" | "bound";
-
-export interface TimelineSnapTarget {
- time: number;
- kind: TimelineSnapKind;
-}
-
-interface NearestSnap {
- target: TimelineSnapTarget;
- distance: number;
-}
-
-const SNAP_PX = 8;
-const DEDUPE_EPSILON_SECONDS = 0.001;
-const ROUND_FACTOR = 1000;
-const KIND_PRIORITY: Record<TimelineSnapKind, number> = {
- bound: 0,
- playhead: 1,
- edge: 2,
- beat: 3,
-};
-
-function roundToMillis(value: number): number {
- return Math.round(value * ROUND_FACTOR) / ROUND_FACTOR;
-}
-
-function addTarget(targets: TimelineSnapTarget[], candidate: TimelineSnapTarget) {
- if (!Number.isFinite(candidate.time)) return;
- const existingIndex = targets.findIndex(
- (target) => Math.abs(target.time - candidate.time) < DEDUPE_EPSILON_SECONDS,
- );
- if (existingIndex === -1) {
- targets.push(candidate);
- return;
- }
-
- const existing = targets[existingIndex];
- if (!existing || KIND_PRIORITY[candidate.kind] >= KIND_PRIORITY[existing.kind]) return;
- targets[existingIndex] = candidate;
-}
-
-export function buildTimelineSnapTargets(input: {
- elements: TimelineElement[];
- /** Keys of every clip moving in this gesture (the whole group), excluded as targets. */
- excludedKeys: ReadonlySet<string>;
- playhead: number;
- compDuration: number;
- beats: number[];
-}): TimelineSnapTarget[] {
- const targets: TimelineSnapTarget[] = [];
-
- addTarget(targets, { time: 0, kind: "bound" });
- addTarget(targets, { time: Math.max(0, input.compDuration), kind: "bound" });
- addTarget(targets, { time: Math.max(0, input.playhead), kind: "playhead" });
-
- for (const element of input.elements) {
- const elementKey = element.key ?? element.id;
- if (input.excludedKeys.has(elementKey) || input.excludedKeys.has(element.id)) continue;
- addTarget(targets, { time: element.start, kind: "edge" });
- addTarget(targets, { time: element.start + element.duration, kind: "edge" });
- }
-
- for (const beat of input.beats) {
- addTarget(targets, { time: beat, kind: "beat" });
- }
-
- return targets.sort((a, b) => a.time - b.time || KIND_PRIORITY[a.kind] - KIND_PRIORITY[b.kind]);
-}
-
-function nearestSnap(
- time: number,
- targets: TimelineSnapTarget[],
- thresholdSeconds: number,
-): NearestSnap | null {
- let best: NearestSnap | null = null;
- let bestDistance = thresholdSeconds;
- for (const target of targets) {
- if (target.time === time) continue;
- const distance = Math.abs(target.time - time);
- if (distance < bestDistance) {
- bestDistance = distance;
- best = { target, distance };
- }
- }
- return best;
-}
-
-export function snapEdgesToTargets(
- start: number,
- duration: number,
- targets: TimelineSnapTarget[],
- pixelsPerSecond: number,
- options?: { maxStart?: number },
-): { start: number; snapTime: number | null; snapKind: TimelineSnapKind | null } {
- const thresholdSeconds = SNAP_PX / Math.max(pixelsPerSecond, 1);
- const startSnap = nearestSnap(start, targets, thresholdSeconds);
- const endSnap = nearestSnap(start + duration, targets, thresholdSeconds);
-
- let candidate = start;
- let snapTarget: TimelineSnapTarget | null = null;
- if (startSnap && (!endSnap || startSnap.distance <= endSnap.distance)) {
- candidate = startSnap.target.time;
- snapTarget = startSnap.target;
- } else if (endSnap) {
- candidate = endSnap.target.time - duration;
- snapTarget = endSnap.target;
- }
-
- const maxStart = options?.maxStart ?? Number.POSITIVE_INFINITY;
- const upperStart = Number.isFinite(maxStart) ? Math.max(0, maxStart) : Number.POSITIVE_INFINITY;
- const clamped = Math.max(0, Math.min(upperStart, roundToMillis(candidate)));
- if (snapTarget && Math.abs(clamped - candidate) > 1e-6) {
- return { start: clamped, snapTime: null, snapKind: null };
- }
- return {
- start: clamped,
- snapTime: snapTarget?.time ?? null,
- snapKind: snapTarget?.kind ?? null,
- };
-}
-
-export function snapResizeEdgeToTargets(
- edge: "start" | "end",
- start: number,
- duration: number,
- targets: TimelineSnapTarget[],
- pixelsPerSecond: number,
- limits: { minDuration: number; maxEnd: number; maxLeftDelta?: number },
-): { start: number; duration: number; snapTime: number | null; snapKind: TimelineSnapKind | null } {
- const thresholdSeconds = SNAP_PX / Math.max(pixelsPerSecond, 1);
-
- if (edge === "end") {
- const snap = nearestSnap(start + duration, targets, thresholdSeconds);
- if (!snap) return { start, duration, snapTime: null, snapKind: null };
- const snappedDuration = roundToMillis(snap.target.time - start);
- if (snap.target.time > limits.maxEnd + 1e-6 || snappedDuration < limits.minDuration) {
- return { start, duration, snapTime: null, snapKind: null };
- }
- return {
- start,
- duration: snappedDuration,
- snapTime: snap.target.time,
- snapKind: snap.target.kind,
- };
- }
-
- const snap = nearestSnap(start, targets, thresholdSeconds);
- if (!snap) return { start, duration, snapTime: null, snapKind: null };
- const snappedStart = roundToMillis(snap.target.time);
- const delta = start - snappedStart;
- const snappedDuration = roundToMillis(duration + delta);
- const maxLeftDelta = limits.maxLeftDelta ?? Number.POSITIVE_INFINITY;
- if (snappedStart < 0 || delta > maxLeftDelta + 1e-6 || snappedDuration < limits.minDuration) {
- return { start, duration, snapTime: null, snapKind: null };
- }
- return {
- start: snappedStart,
- duration: snappedDuration,
- snapTime: snap.target.time,
- snapKind: snap.target.kind,
- };
-}
diff --git a/packages/studio/src/player/components/timelineTheme.ts b/packages/studio/src/player/components/timelineTheme.ts
index 4ddfa352d4..b9d7f827bf 100644
--- a/packages/studio/src/player/components/timelineTheme.ts
+++ b/packages/studio/src/player/components/timelineTheme.ts
@@ -43,10 +43,15 @@ const TRACK_STYLE: TimelineTrackStyle = {
};
export const defaultTimelineTheme: TimelineTheme = {
+ // Near-black card surfaces: the panels sit dark while the shell canvas
+ // between them is a step LIGHTER (#18181B), so the gaps read as visible
+ // seams around dark cards (CapCut-style).
shellBackground: "#0A0A0B",
shellBorder: "rgba(255,255,255,0.05)",
rulerBorder: "rgba(255,255,255,0.16)",
- rowBackground: "#0B0C0F",
+ // All track lanes use a single uniform color — one step lighter than the panel
+ // surface (#0A0A0B) so lanes are visibly distinct from the ruler/shell.
+ rowBackground: "#101014",
rowBorder: "rgba(255,255,255,0.06)",
gutterBackground: "#0E0F12",
gutterBorder: "rgba(255,255,255,0.10)",
diff --git a/packages/studio/src/player/components/useResolvedTimelineEditCallbacks.ts b/packages/studio/src/player/components/useResolvedTimelineEditCallbacks.ts
index 9b41494d85..44e9048096 100644
--- a/packages/studio/src/player/components/useResolvedTimelineEditCallbacks.ts
+++ b/packages/studio/src/player/components/useResolvedTimelineEditCallbacks.ts
@@ -6,7 +6,12 @@ import type { TimelineEditCallbacks } from "./timelineCallbacks";
// the rest of the callback bag still comes from TimelineEditContext.
export type TimelineEditOverrides = Pick<
TimelineEditCallbacks,
- "onMoveElement" | "onResizeElement" | "onBlockedEditAttempt" | "onSplitElement"
+ | "onMoveElement"
+ | "onMoveElements"
+ | "onResizeElement"
+ | "onResizeElements"
+ | "onBlockedEditAttempt"
+ | "onSplitElement"
>;
// Merge any prop overrides over the context callbacks. Used so NLELayout can
@@ -16,15 +21,32 @@ export function useResolvedTimelineEditCallbacks(
overrides: TimelineEditOverrides,
): TimelineEditCallbacks {
const ctx = useTimelineEditContextOptional();
- const { onMoveElement, onResizeElement, onBlockedEditAttempt, onSplitElement } = overrides;
+ const {
+ onMoveElement,
+ onMoveElements,
+ onResizeElement,
+ onResizeElements,
+ onBlockedEditAttempt,
+ onSplitElement,
+ } = overrides;
return useMemo(
() => ({
...ctx,
onMoveElement: onMoveElement ?? ctx.onMoveElement,
+ onMoveElements: onMoveElements ?? ctx.onMoveElements,
onResizeElement: onResizeElement ?? ctx.onResizeElement,
+ onResizeElements: onResizeElements ?? ctx.onResizeElements,
onBlockedEditAttempt: onBlockedEditAttempt ?? ctx.onBlockedEditAttempt,
onSplitElement: onSplitElement ?? ctx.onSplitElement,
}),
- [ctx, onMoveElement, onResizeElement, onBlockedEditAttempt, onSplitElement],
+ [
+ ctx,
+ onMoveElement,
+ onMoveElements,
+ onResizeElement,
+ onResizeElements,
+ onBlockedEditAttempt,
+ onSplitElement,
+ ],
);
}
diff --git a/packages/studio/src/player/components/useTimelineClipDrag.resize.test.tsx b/packages/studio/src/player/components/useTimelineClipDrag.resize.test.tsx
new file mode 100644
index 0000000000..33ebd8ff47
--- /dev/null
+++ b/packages/studio/src/player/components/useTimelineClipDrag.resize.test.tsx
@@ -0,0 +1,241 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { TimelineElement } from "../store/playerStore";
+import { usePlayerStore } from "../store/playerStore";
+import type { ResizingClipState } from "./useTimelineClipDrag";
+import { useTimelineClipDrag } from "./useTimelineClipDrag";
+import { mountReactHarness } from "../../hooks/domSelectionTestHarness";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+function el(id: string, over: Partial<TimelineElement> = {}): TimelineElement {
+ return {
+ id,
+ key: id,
+ tag: "video",
+ start: 0,
+ duration: 2,
+ track: 0,
+ domId: id,
+ ...over,
+ };
+}
+
+afterEach(() => {
+ document.body.innerHTML = "";
+ usePlayerStore.getState().reset();
+});
+
+function renderResizeHarness(
+ elements: TimelineElement[],
+ selected: string[],
+ options: { wireGroupResize?: boolean } = {},
+) {
+ usePlayerStore.getState().setElements(elements);
+ usePlayerStore.setState({ timelineSnapEnabled: false });
+ usePlayerStore.getState().setSelectedElementIds(new Set(selected));
+
+ const scroll = document.createElement("div");
+ document.body.append(scroll);
+ const onResizeElement = vi.fn();
+ const onResizeElements = vi.fn().mockResolvedValue(undefined);
+ let setResizingClip: ((s: ResizingClipState | null) => void) | null = null;
+
+ function Harness() {
+ const hook = useTimelineClipDrag({
+ scrollRef: { current: scroll },
+ ppsRef: { current: 100 },
+ durationRef: { current: 100 },
+ trackOrderRef: { current: [0, 1] },
+ onResizeElement,
+ onResizeElements: options.wireGroupResize === false ? undefined : onResizeElements,
+ setShowPopover: vi.fn(),
+ setRangeSelectionRef: { current: vi.fn() },
+ });
+ setResizingClip = hook.setResizingClip;
+ return null;
+ }
+
+ const root = mountReactHarness(<Harness />);
+ const apply = setResizingClip!;
+
+ return {
+ onResizeElement,
+ onResizeElements,
+ storeById(id: string) {
+ return usePlayerStore.getState().elements.find((e) => e.id === id)!;
+ },
+ startResize(element: TimelineElement, edge: "start" | "end") {
+ act(() => {
+ apply({
+ element,
+ edge,
+ originClientX: 0,
+ previewStart: element.start,
+ previewDuration: element.duration,
+ previewPlaybackStart: element.playbackStart,
+ started: false,
+ });
+ });
+ },
+ movePointer(clientX: number) {
+ act(() => {
+ window.dispatchEvent(new MouseEvent("pointermove", { bubbles: true, clientX, clientY: 0 }));
+ });
+ },
+ async dropPointer() {
+ await act(async () => {
+ window.dispatchEvent(new MouseEvent("pointerup", { bubbles: true }));
+ });
+ },
+ pressEscape() {
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
+ });
+ },
+ unmount() {
+ act(() => root.unmount());
+ },
+ };
+}
+
+// Two clips a(0,2) + b(5,3) selected as a group, with a's END edge grabbed and
+// dragged +0.5s (50px @ 100pps). `bOver` customizes b (e.g. locking it).
+function startGroupResize(bOver: Partial<TimelineElement> = {}) {
+ const a = el("a", { start: 0, duration: 2 });
+ const b = el("b", { start: 5, duration: 3, ...bOver });
+ const h = renderResizeHarness([a, b], ["a", "b"]);
+ h.startResize(a, "end");
+ h.movePointer(50);
+ return { a, b, h };
+}
+
+// Drop the pointer and assert exactly one resize persisted: the grabbed clip `a`
+// grown to 2.5s (the +0.5 gesture), with no other member patched.
+async function expectSingleResizeToA(
+ h: ReturnType<typeof renderResizeHarness>,
+ a: TimelineElement,
+): Promise<void> {
+ await h.dropPointer();
+ expect(h.onResizeElement).toHaveBeenCalledTimes(1);
+ expect(h.onResizeElement).toHaveBeenCalledWith(a, expect.objectContaining({ duration: 2.5 }));
+}
+
+describe("useTimelineClipDrag — single-clip resize (unchanged path)", () => {
+ it("resizes only the grabbed clip and persists once", async () => {
+ const a = el("a", { start: 0, duration: 2 });
+ const b = el("b", { start: 5, duration: 2 });
+ const h = renderResizeHarness([a, b], []); // no multi-selection
+
+ h.startResize(a, "end");
+ h.movePointer(50); // +0.5s at 100 pps
+ await expectSingleResizeToA(h, a);
+ expect(h.storeById("a").duration).toBe(2.5);
+ expect(h.storeById("b").duration).toBe(2); // untouched
+ h.unmount();
+ });
+
+ it("does not let an older rejected resize roll back a newer optimistic gesture", async () => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const a = el("a", { start: 0, duration: 2 });
+ const h = renderResizeHarness([a], []);
+ let rejectFirst!: (error: Error) => void;
+ h.onResizeElement
+ .mockImplementationOnce(() => new Promise<void>((_resolve, reject) => (rejectFirst = reject)))
+ .mockResolvedValueOnce(undefined);
+
+ h.startResize(a, "end");
+ h.movePointer(50);
+ await h.dropPointer();
+ h.startResize(a, "end");
+ h.movePointer(100);
+ await h.dropPointer();
+ rejectFirst(new Error("older resize failed"));
+ await act(async () => Promise.resolve());
+
+ expect(h.storeById("a").duration).toBe(3);
+ errorSpy.mockRestore();
+ h.unmount();
+ });
+});
+
+describe("useTimelineClipDrag — multi-select group resize (restored)", () => {
+ it("previews the non-grabbed member through the store, grabbed stays out until commit", () => {
+ const { h } = startGroupResize(); // grabbed asks +0.5
+
+ // Non-grabbed member is previewed in the store; the grabbed clip renders from
+ // resizingClip state, so its store value is still the original until commit.
+ expect(h.storeById("b").duration).toBe(3.5);
+ expect(h.storeById("a").duration).toBe(2);
+ h.unmount();
+ });
+
+ it("commits the whole group — persists every member by the shared delta", async () => {
+ const { a, b, h } = startGroupResize();
+ await h.dropPointer();
+
+ expect(h.onResizeElement).not.toHaveBeenCalled();
+ expect(h.onResizeElements).toHaveBeenCalledTimes(1);
+ expect(h.onResizeElements).toHaveBeenCalledWith(
+ [
+ expect.objectContaining({ element: a, duration: 2.5 }),
+ expect.objectContaining({ element: b, duration: 3.5 }),
+ ],
+ { coalesceKey: expect.stringMatching(/^clip-group-resize:/) },
+ );
+ expect(h.storeById("a").duration).toBe(2.5);
+ expect(h.storeById("b").duration).toBe(3.5);
+ h.unmount();
+ });
+
+ it("rolls the whole group back when the atomic resize batch rejects", async () => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const { h } = startGroupResize();
+ h.onResizeElements.mockRejectedValueOnce(new Error("batch failed"));
+ await h.dropPointer();
+ await act(async () => Promise.resolve());
+ expect(h.onResizeElements).toHaveBeenCalledTimes(1);
+ expect(h.onResizeElement).not.toHaveBeenCalled();
+ expect(h.storeById("a").duration).toBe(2);
+ expect(h.storeById("b").duration).toBe(3);
+ expect(errorSpy).toHaveBeenCalledTimes(1);
+ errorSpy.mockRestore();
+ h.unmount();
+ });
+
+ it("rolls the whole group back when no atomic resize callback is wired", async () => {
+ const a = el("a", { start: 0, duration: 2 });
+ const b = el("b", { start: 5, duration: 3 });
+ const h = renderResizeHarness([a, b], ["a", "b"], {
+ wireGroupResize: false,
+ });
+ h.startResize(a, "end");
+ h.movePointer(50);
+ expect(h.storeById("b").duration).toBe(3.5);
+
+ await h.dropPointer();
+ expect(h.storeById("a").duration).toBe(2);
+ expect(h.storeById("b").duration).toBe(3);
+ expect(h.onResizeElement).not.toHaveBeenCalled();
+ h.unmount();
+ });
+
+ it("degrades to single-clip when a selected member is locked — locked clip untouched", async () => {
+ const { a, h } = startGroupResize({ timelineLocked: true });
+ await expectSingleResizeToA(h, a);
+ expect(h.storeById("b").duration).toBe(3); // locked member never patched
+ h.unmount();
+ });
+
+ it("Escape rolls back the previewed non-grabbed member and persists nothing", () => {
+ const { h } = startGroupResize();
+ expect(h.storeById("b").duration).toBe(3.5); // previewed
+
+ h.pressEscape();
+ expect(h.storeById("b").duration).toBe(3); // restored
+ expect(h.onResizeElement).not.toHaveBeenCalled();
+ h.unmount();
+ });
+});
diff --git a/packages/studio/src/player/components/useTimelineClipDrag.test.tsx b/packages/studio/src/player/components/useTimelineClipDrag.test.tsx
deleted file mode 100644
index 6fc750b2bb..0000000000
--- a/packages/studio/src/player/components/useTimelineClipDrag.test.tsx
+++ /dev/null
@@ -1,506 +0,0 @@
-// @vitest-environment happy-dom
-
-import React, { act } from "react";
-import { createRoot } from "react-dom/client";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import type { TimelineElement } from "../store/playerStore";
-import { usePlayerStore } from "../store/playerStore";
-import { TRACK_H } from "./timelineLayout";
-import { buildStackingTimelineLayers } from "./timelineTrackOrder";
-import type { DraggedClipState, ResizingClipState } from "./useTimelineClipDrag";
-import { useTimelineClipDrag } from "./useTimelineClipDrag";
-
-(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-
-function timelineElement(input: {
- id: string;
- tag?: string;
- track: number;
- zIndex: number;
- start?: number;
- duration?: number;
- sourceDuration?: number;
- playbackStart?: number;
- playbackRate?: number;
- timelineLocked?: boolean;
-}): TimelineElement {
- return {
- id: input.id,
- domId: input.id,
- tag: input.tag ?? "div",
- start: input.start ?? 0,
- duration: input.duration ?? 2,
- sourceDuration: input.sourceDuration,
- playbackStart: input.playbackStart,
- playbackRate: input.playbackRate,
- track: input.track,
- zIndex: input.zIndex,
- stackingContextId: "root",
- parentCompositionId: null,
- compositionAncestors: ["root"],
- sourceFile: "index.html",
- timingSource: "authored",
- timelineLocked: input.timelineLocked,
- };
-}
-
-afterEach(() => {
- document.body.innerHTML = "";
- usePlayerStore.getState().reset();
-});
-
-function renderDragHarness(elements: TimelineElement[]) {
- usePlayerStore.getState().setElements(elements);
- const layers = buildStackingTimelineLayers(elements).rows;
- const scroll = document.createElement("div");
- document.body.append(scroll);
- const onMoveElement = vi.fn();
- const onResizeElement = vi.fn();
- const onMoveElements = vi.fn();
- const onResizeElements = vi.fn();
- const onPreviewMoveElements = vi.fn();
- const onPreviewResizeElements = vi.fn();
- let setDraggedClip: ((state: DraggedClipState | null) => void) | null = null;
- let setResizingClip: ((state: ResizingClipState | null) => void) | null = null;
-
- function Harness() {
- const hook = useTimelineClipDrag({
- scrollRef: { current: scroll },
- ppsRef: { current: 100 },
- trackOrderRef: { current: layers.map((layer) => layer.id) },
- timelineLayersRef: { current: layers },
- timelineElementsRef: { current: elements },
- onMoveElement,
- onResizeElement,
- onMoveElements,
- onResizeElements,
- onPreviewMoveElements,
- onPreviewResizeElements,
- onBlockedEditAttempt: vi.fn(),
- setShowPopover: vi.fn(),
- setRangeSelectionRef: { current: vi.fn() },
- });
- setDraggedClip = hook.setDraggedClip;
- setResizingClip = hook.setResizingClip;
- return null;
- }
-
- const host = document.createElement("div");
- document.body.append(host);
- const root = createRoot(host);
- act(() => {
- root.render(<Harness />);
- });
- if (!setDraggedClip) throw new Error("Expected drag setter");
- if (!setResizingClip) throw new Error("Expected resize setter");
- const applyDraggedClip: (state: DraggedClipState | null) => void = setDraggedClip;
- const applyResizingClip: (state: ResizingClipState | null) => void = setResizingClip;
-
- return {
- layers,
- onMoveElement,
- onResizeElement,
- onMoveElements,
- onResizeElements,
- onPreviewMoveElements,
- onPreviewResizeElements,
- storeElements() {
- return usePlayerStore.getState().elements;
- },
- startDrag(element: TimelineElement, layerIndex: number) {
- const layer =
- layers[layerIndex] ??
- layers.find((candidate) =>
- candidate.elements.some((candidateElement) => candidateElement.id === element.id),
- ) ??
- layers[0]!;
- act(() => {
- applyDraggedClip({
- element,
- originClientX: 0,
- originClientY: 0,
- originScrollLeft: 0,
- originScrollTop: 0,
- pointerClientX: 0,
- pointerClientY: 0,
- pointerOffsetX: 0,
- pointerOffsetY: 0,
- previewStart: element.start,
- previewTrack: element.track,
- previewLayerId: layer.id,
- previewLayerIndex: layerIndex,
- previewStackingReorder: null,
- snapBeatTime: null,
- snapGuideTime: null,
- snapGuideKind: null,
- started: false,
- });
- });
- },
- startResize(element: TimelineElement, edge: "start" | "end") {
- act(() => {
- applyResizingClip({
- element,
- edge,
- originClientX: 0,
- previewStart: element.start,
- previewDuration: element.duration,
- previewPlaybackStart: element.playbackStart,
- snapGuideTime: null,
- snapGuideKind: null,
- started: false,
- });
- });
- },
- movePointer(clientX: number, clientY: number) {
- act(() => {
- window.dispatchEvent(
- new MouseEvent("pointermove", {
- bubbles: true,
- clientX,
- clientY,
- }),
- );
- });
- },
- async dropPointer() {
- await act(async () => {
- window.dispatchEvent(new MouseEvent("pointerup", { bubbles: true }));
- });
- },
- unmount() {
- act(() => root.unmount());
- },
- };
-}
-
-describe("useTimelineClipDrag", () => {
- it("allows moving a clip past the current composition duration", async () => {
- const clip = timelineElement({ id: "clip", track: 0, zIndex: 1 });
- const harness = renderDragHarness([clip]);
-
- harness.startDrag(clip, 0);
- harness.movePointer(1100, 0);
- await harness.dropPointer();
-
- expect(harness.onMoveElement).toHaveBeenCalledWith(
- clip,
- expect.objectContaining({ start: 11 }),
- );
-
- harness.unmount();
- });
-
- it("moves every selected clip body by the same delta", async () => {
- const first = timelineElement({ id: "first", track: 0, zIndex: 1, start: 1, duration: 2 });
- const second = timelineElement({ id: "second", track: 1, zIndex: 1, start: 4, duration: 2 });
- const harness = renderDragHarness([first, second]);
- act(() => {
- usePlayerStore.getState().setSelection(["first", "second"], "first");
- });
-
- harness.startDrag(first, 0);
- harness.movePointer(200, 0);
-
- expect(harness.storeElements().map((element) => [element.id, element.start])).toEqual([
- ["first", 3],
- ["second", 6],
- ]);
- expect(harness.onPreviewMoveElements).toHaveBeenLastCalledWith([
- { element: first, start: 3 },
- { element: second, start: 6 },
- ]);
-
- await harness.dropPointer();
-
- expect(harness.onMoveElement).not.toHaveBeenCalled();
- expect(harness.onMoveElements).toHaveBeenCalledTimes(1);
- expect(harness.onMoveElements).toHaveBeenCalledWith([
- { element: first, start: 3 },
- { element: second, start: 6 },
- ]);
-
- harness.unmount();
- });
-
- it("clamps a selected group move when the earliest member reaches zero", async () => {
- const early = timelineElement({ id: "early", track: 0, zIndex: 1, start: 1, duration: 2 });
- const grabbed = timelineElement({ id: "grabbed", track: 1, zIndex: 1, start: 4, duration: 2 });
- const harness = renderDragHarness([early, grabbed]);
- act(() => {
- usePlayerStore.getState().setSelection(["early", "grabbed"], "grabbed");
- });
-
- harness.startDrag(grabbed, 1);
- harness.movePointer(-300, 0);
- await harness.dropPointer();
-
- expect(harness.onMoveElements).toHaveBeenCalledWith([
- { element: early, start: 0 },
- { element: grabbed, start: 3 },
- ]);
- expect(harness.onMoveElement).not.toHaveBeenCalled();
-
- harness.unmount();
- });
-
- it("keeps body drag single-clip when the grabbed clip is not in the multi-selection", async () => {
- const first = timelineElement({ id: "first", track: 0, zIndex: 1, start: 1, duration: 2 });
- const second = timelineElement({ id: "second", track: 1, zIndex: 1, start: 4, duration: 2 });
- const outside = timelineElement({ id: "outside", track: 2, zIndex: 1, start: 7, duration: 2 });
- const harness = renderDragHarness([first, second, outside]);
- act(() => {
- usePlayerStore.getState().setSelection(["first", "second"], "first");
- });
-
- harness.startDrag(outside, 2);
- harness.movePointer(200, 0);
- await harness.dropPointer();
-
- expect(harness.onMoveElements).not.toHaveBeenCalled();
- expect(harness.onMoveElement).toHaveBeenCalledTimes(1);
- expect(harness.onMoveElement).toHaveBeenCalledWith(
- outside,
- expect.objectContaining({ start: 9 }),
- );
-
- harness.unmount();
- });
-
- it("does not form a group when a selected member is locked (grabbed clip moves alone)", async () => {
- const first = timelineElement({ id: "first", track: 0, zIndex: 1, start: 1, duration: 2 });
- const locked = timelineElement({
- id: "locked",
- track: 1,
- zIndex: 1,
- start: 4,
- duration: 2,
- timelineLocked: true,
- });
- const harness = renderDragHarness([first, locked]);
- act(() => {
- usePlayerStore.getState().setSelection(["first", "locked"], "first");
- });
-
- harness.startDrag(first, 0);
- harness.movePointer(200, 0);
- await harness.dropPointer();
-
- // The locked member forbids the op, so no group forms: the grabbed clip moves
- // alone (single-clip path) and the locked clip is never touched.
- expect(harness.onMoveElements).not.toHaveBeenCalled();
- expect(harness.onMoveElement).toHaveBeenCalledTimes(1);
- expect(harness.onMoveElement).toHaveBeenCalledWith(
- first,
- expect.objectContaining({ start: 3 }),
- );
- expect(harness.storeElements().find((el) => el.id === "locked")?.start).toBe(4);
-
- harness.unmount();
- });
-
- it("allows right-edge resize past the current composition duration", async () => {
- const clip = timelineElement({ id: "clip", track: 0, zIndex: 1, start: 6, duration: 2 });
- const harness = renderDragHarness([clip]);
-
- harness.startResize(clip, "end");
- harness.movePointer(400, 0);
- await harness.dropPointer();
-
- expect(harness.onResizeElement).toHaveBeenCalledWith(
- clip,
- expect.objectContaining({ start: 6, duration: 6 }),
- );
-
- harness.unmount();
- });
-
- it("resizes every selected start edge by the same delta", async () => {
- const first = timelineElement({ id: "first", track: 0, zIndex: 1, start: 1, duration: 4 });
- const second = timelineElement({ id: "second", track: 1, zIndex: 1, start: 5, duration: 3 });
- const harness = renderDragHarness([first, second]);
- act(() => {
- usePlayerStore.getState().setSelection(["first", "second"], "first");
- });
-
- harness.startResize(first, "start");
- harness.movePointer(100, 0);
-
- expect(
- harness.storeElements().map((element) => [element.id, element.start, element.duration]),
- ).toEqual([
- ["first", 2, 3],
- ["second", 6, 2],
- ]);
- expect(harness.onPreviewResizeElements).toHaveBeenLastCalledWith([
- { element: first, start: 2, duration: 3, playbackStart: undefined },
- { element: second, start: 6, duration: 2, playbackStart: undefined },
- ]);
-
- await harness.dropPointer();
-
- expect(harness.onResizeElement).not.toHaveBeenCalled();
- expect(harness.onResizeElements).toHaveBeenCalledTimes(1);
- expect(harness.onResizeElements).toHaveBeenCalledWith([
- { element: first, start: 2, duration: 3, playbackStart: undefined },
- { element: second, start: 6, duration: 2, playbackStart: undefined },
- ]);
-
- harness.unmount();
- });
-
- it("resizes every selected end edge by the same delta", async () => {
- const first = timelineElement({ id: "first", track: 0, zIndex: 1, start: 1, duration: 4 });
- const second = timelineElement({ id: "second", track: 1, zIndex: 1, start: 5, duration: 3 });
- const harness = renderDragHarness([first, second]);
- act(() => {
- usePlayerStore.getState().setSelection(["first", "second"], "first");
- });
-
- harness.startResize(first, "end");
- harness.movePointer(100, 0);
- await harness.dropPointer();
-
- expect(harness.onResizeElement).not.toHaveBeenCalled();
- expect(harness.onResizeElements).toHaveBeenCalledWith([
- { element: first, start: 1, duration: 5, playbackStart: undefined },
- { element: second, start: 5, duration: 4, playbackStart: undefined },
- ]);
-
- harness.unmount();
- });
-
- it("clamps selected start-edge resize at the most constrained duration", async () => {
- const short = timelineElement({ id: "short", track: 0, zIndex: 1, start: 1, duration: 0.5 });
- const long = timelineElement({ id: "long", track: 1, zIndex: 1, start: 4, duration: 2 });
- const harness = renderDragHarness([short, long]);
- act(() => {
- usePlayerStore.getState().setSelection(["short", "long"], "short");
- });
-
- harness.startResize(short, "start");
- harness.movePointer(100, 0);
- await harness.dropPointer();
-
- expect(harness.onResizeElements).toHaveBeenCalledWith([
- { element: short, start: 1.4, duration: 0.1, playbackStart: undefined },
- { element: long, start: 4.4, duration: 1.6, playbackStart: undefined },
- ]);
- expect(harness.onResizeElement).not.toHaveBeenCalled();
-
- harness.unmount();
- });
-
- it("adjusts every selected media playback start during start-edge resize", async () => {
- const audio = timelineElement({
- id: "audio",
- tag: "audio",
- track: 0,
- zIndex: 1,
- start: 2,
- duration: 3,
- playbackStart: 1,
- playbackRate: 1,
- });
- const video = timelineElement({
- id: "video",
- tag: "video",
- track: 1,
- zIndex: 1,
- start: 5,
- duration: 4,
- playbackStart: 2,
- playbackRate: 2,
- });
- const harness = renderDragHarness([audio, video]);
- act(() => {
- usePlayerStore.getState().setSelection(["audio", "video"], "audio");
- });
-
- harness.startResize(audio, "start");
- harness.movePointer(50, 0);
- await harness.dropPointer();
-
- expect(harness.onResizeElements).toHaveBeenCalledWith([
- { element: audio, start: 2.5, duration: 2.5, playbackStart: 1.5 },
- { element: video, start: 5.5, duration: 3.5, playbackStart: 3 },
- ]);
-
- harness.unmount();
- });
-
- it("keeps handle resize single-clip when the grabbed clip is not in the multi-selection", async () => {
- const first = timelineElement({ id: "first", track: 0, zIndex: 1, start: 1, duration: 2 });
- const second = timelineElement({ id: "second", track: 1, zIndex: 1, start: 4, duration: 2 });
- const outside = timelineElement({ id: "outside", track: 2, zIndex: 1, start: 7, duration: 2 });
- const harness = renderDragHarness([first, second, outside]);
- act(() => {
- usePlayerStore.getState().setSelection(["first", "second"], "first");
- });
-
- harness.startResize(outside, "end");
- harness.movePointer(100, 0);
- await harness.dropPointer();
-
- expect(harness.onResizeElement).toHaveBeenCalledTimes(1);
- expect(harness.onResizeElement).toHaveBeenCalledWith(
- outside,
- expect.objectContaining({ start: 7, duration: 3 }),
- );
-
- harness.unmount();
- });
-
- it("passes a new-lane stacking intent when a vertical drag targets an overlapping lane", async () => {
- const front = timelineElement({ id: "front", track: 0, zIndex: 3 });
- const middle = timelineElement({ id: "middle", track: 1, zIndex: 2 });
- const back = timelineElement({ id: "back", track: 2, zIndex: 1 });
- const harness = renderDragHarness([front, middle, back]);
-
- harness.startDrag(back, 2);
- harness.movePointer(0, -2 * TRACK_H);
- await harness.dropPointer();
-
- expect(harness.onMoveElement).toHaveBeenCalledTimes(1);
- expect(harness.onMoveElement.mock.calls[0]![1]).toMatchObject({
- start: 0,
- track: 2,
- stackingReorder: {
- contextKey: "root",
- placement: { type: "above", layerId: harness.layers[0]!.id },
- zIndexChanges: [{ key: "back", zIndex: 4 }],
- },
- });
-
- harness.unmount();
- });
-
- it("resolves lane stacking from the authored time span, independent of horizontal drag", async () => {
- const front = timelineElement({ id: "front", track: 0, zIndex: 3 });
- const back = timelineElement({ id: "back", track: 1, zIndex: 1 });
- back.start = 0;
- front.start = 0;
- const harness = renderDragHarness([front, back]);
-
- // Drag up one row AND rightward in time. The horizontal drift moves the
- // clip out of overlap, but the two axes never fight: the vertical restack
- // is resolved from the authored (overlapping) span, so it still inserts
- // above the target lane rather than silently joining it.
- harness.startDrag(back, 1);
- harness.movePointer(200, -TRACK_H);
- await harness.dropPointer();
-
- expect(harness.onMoveElement).toHaveBeenCalledTimes(1);
- expect(harness.onMoveElement.mock.calls[0]![1]).toMatchObject({
- start: 2,
- track: 1,
- stackingReorder: {
- contextKey: "root",
- placement: { type: "above", layerId: harness.layers[0]!.id },
- zIndexChanges: [{ key: "back", zIndex: 4 }],
- },
- });
-
- harness.unmount();
- });
-});
diff --git a/packages/studio/src/player/components/useTimelineClipDrag.ts b/packages/studio/src/player/components/useTimelineClipDrag.ts
index b9faa4be12..4d0d6d72b9 100644
--- a/packages/studio/src/player/components/useTimelineClipDrag.ts
+++ b/packages/studio/src/player/components/useTimelineClipDrag.ts
@@ -1,126 +1,103 @@
import { useRef, useState, useCallback, useMemo } from "react";
import { useMountEffect } from "../../hooks/useMountEffect";
import {
- resolveTimelineMove,
- resolveTimelineResize,
- resolveTimelineAutoScroll,
- type BlockedTimelineEditIntent,
- type TimelineStackingReorderIntent,
+ applyTimelineAutoScrollStep,
+ resolveTimelineAutoScrollLoopAction,
+ resolveTimelineDragEscape,
} from "./timelineEditing";
import { usePlayerStore } from "../store/playerStore";
import type { TimelineElement } from "../store/playerStore";
-import { TRACK_H } from "./timelineLayout";
-import { isMusicTrack } from "../../utils/timelineInspector";
+import { isMusicTrack, isAudioTimelineElement } from "../../utils/timelineInspector";
import { mergeUserBeats } from "../../utils/beatEditing";
-import type { StackingTimelineLayer, TimelineLayerId } from "./timelineTrackOrder";
+import {
+ buildTimelineGroupResizeMembers,
+ type TimelineGroupResizeSession,
+} from "./timelineGroupEditing";
+import { collectTimelineSnapTargets, type TimelineSnapTarget } from "./timelineSnapping";
+import { commitDraggedClipMove } from "./timelineClipDragCommit";
+import type { StackingPatch } from "./timelineStackingSync";
+import type { TimelineEditCallbacks } from "./timelineCallbacks";
+import {
+ computeDragPreview,
+ computeResizePreview,
+ previewGroupResize,
+ type ResizePreviewResult,
+} from "./timelineClipDragPreview";
import type {
- TimelineGroupMoveChange,
- TimelineGroupResizeChange,
-} from "../../hooks/useTimelineGroupEditing";
+ DraggedClipState,
+ ResizingClipState,
+ BlockedClipState,
+} from "./timelineClipDragTypes";
import {
- buildTimelineSnapTargets,
- snapEdgesToTargets,
- snapResizeEdgeToTargets,
- type TimelineSnapKind,
-} from "./timelineSnapTargets";
-import { resolveDragPreviewPlacement } from "./timelineClipDragPreview";
-import { useTimelineClipGroupDrag } from "./useTimelineClipGroupDrag";
+ beginTimelineOptimisticGesture,
+ rollbackLatestTimelineOptimisticGesture,
+} from "./timelineOptimisticRevision";
+import { commitTimelineGroupResize } from "./timelineGroupResizeCommit";
-const EMPTY_BEAT_TIMES: number[] = [];
-
-/* ── Shared state types ─────────────────────────────────────────── */
-export interface DraggedClipState {
- element: TimelineElement;
- originClientX: number;
- originClientY: number;
- originScrollLeft: number;
- originScrollTop: number;
- pointerClientX: number;
- pointerClientY: number;
- pointerOffsetX: number;
- pointerOffsetY: number;
- previewStart: number;
- previewTrack: number;
- previewLayerId: TimelineLayerId;
- previewLayerIndex: number;
- /** Beat time the clip will snap to on drop, for the grid-line highlight. */
- snapBeatTime: number | null;
- snapGuideTime: number | null;
- snapGuideKind: TimelineSnapKind | null;
- /** Sibling-scoped z-index reorder intent resolved from the vertical drag. */
- previewStackingReorder: TimelineStackingReorderIntent | null;
- started: boolean;
-}
+export type {
+ DraggedClipState,
+ ResizingClipState,
+ BlockedClipState,
+} from "./timelineClipDragTypes";
-export interface ResizingClipState {
- element: TimelineElement;
- edge: "start" | "end";
- originClientX: number;
- previewStart: number;
- previewDuration: number;
- previewPlaybackStart?: number;
- snapGuideTime: number | null;
- snapGuideKind: TimelineSnapKind | null;
- started: boolean;
-}
-
-export interface BlockedClipState {
- element: TimelineElement;
- intent: BlockedTimelineEditIntent;
- originClientX: number;
- originClientY: number;
- started: boolean;
-}
+const EMPTY_BEAT_TIMES: number[] = [];
/* ── Hook ───────────────────────────────────────────────────────── */
interface UseTimelineClipDragInput {
scrollRef: React.RefObject<HTMLDivElement | null>;
ppsRef: React.RefObject<number>;
- trackOrderRef: React.RefObject<TimelineLayerId[]>;
- timelineLayersRef: React.RefObject<StackingTimelineLayer[]>;
- timelineElementsRef: React.RefObject<TimelineElement[]>;
+ durationRef: React.RefObject<number>;
+ trackOrderRef: React.RefObject<number[]>;
onMoveElement?: (
element: TimelineElement,
- updates: Pick<TimelineElement, "start" | "track"> & {
- stackingReorder?: TimelineStackingReorderIntent | null;
- },
+ updates: Pick<TimelineElement, "start" | "track">,
+ ) => Promise<void> | void;
+ onMoveElements?: (
+ edits: Array<{
+ element: TimelineElement;
+ updates: Pick<TimelineElement, "start" | "track">;
+ }>,
) => Promise<void> | void;
onResizeElement?: (
element: TimelineElement,
updates: Pick<TimelineElement, "start" | "duration" | "playbackStart">,
) => Promise<void> | void;
- onMoveElements?: (changes: TimelineGroupMoveChange[]) => Promise<void> | void;
- onResizeElements?: (changes: TimelineGroupResizeChange[]) => Promise<void> | void;
- onPreviewMoveElements?: (changes: TimelineGroupMoveChange[]) => void;
- onPreviewResizeElements?: (changes: TimelineGroupResizeChange[]) => void;
- onBlockedEditAttempt?: (element: TimelineElement, intent: BlockedTimelineEditIntent) => void;
+ onResizeElements?: NonNullable<TimelineEditCallbacks["onResizeElements"]>;
+ onBlockedEditAttempt?: (element: TimelineElement, intent: BlockedClipState["intent"]) => void;
setShowPopover: (show: boolean) => void;
- /** Stable ref to the range selection setter, wired after mount to break circular dependency. */
+ /** Stable ref to the range selection setter — wired after mount to break circular dependency. */
setRangeSelectionRef: React.RefObject<((sel: null) => void) | null>;
+ /**
+ * Lane ↔ stacking unification (see research/STAGE3-NEEDED-WIRING.md). When both
+ * are supplied and a lane-change drag commits, the edited clip(s) get z-index
+ * patches so their stacking matches lane order relative to time-overlapping
+ * clips. Provisioned by the timeline layer (Timeline.tsx) from the preview
+ * iframe + the canvas z-order persist path; forwarded straight to
+ * commitDraggedClipMove. Both optional → absent = no-op (backward compatible).
+ */
+ readZIndex?: (element: TimelineElement) => number;
+ onStackingPatches?: (patches: StackingPatch[]) => void;
}
export function useTimelineClipDrag({
scrollRef,
ppsRef,
+ durationRef,
trackOrderRef,
- timelineLayersRef,
- timelineElementsRef,
onMoveElement,
- onResizeElement,
onMoveElements,
+ onResizeElement,
onResizeElements,
- onPreviewMoveElements,
- onPreviewResizeElements,
onBlockedEditAttempt,
setShowPopover,
setRangeSelectionRef,
+ readZIndex,
+ onStackingPatches,
}: UseTimelineClipDragInput) {
const updateElement = usePlayerStore((s) => s.updateElement);
const rawBeatTimes = usePlayerStore((s) => s.beatAnalysis?.beatTimes ?? EMPTY_BEAT_TIMES);
const rawBeatStrengths = usePlayerStore((s) => s.beatAnalysis?.beatStrengths ?? EMPTY_BEAT_TIMES);
const beatEdits = usePlayerStore((s) => s.beatEdits);
- const playhead = usePlayerStore((s) => s.currentTime);
- const compositionDuration = usePlayerStore((s) => s.duration);
const musicStart = usePlayerStore((s) => s.elements.find(isMusicTrack)?.start ?? 0);
const musicPlaybackStart = usePlayerStore(
(s) => s.elements.find(isMusicTrack)?.playbackStart ?? 0,
@@ -146,30 +123,45 @@ export function useTimelineClipDrag({
musicDuration,
]);
- const beatTimesRef = useRef<number[]>([]);
- beatTimesRef.current = adjustedBeatTimes;
- const playheadRef = useRef(0);
- playheadRef.current = playhead;
- const compositionDurationRef = useRef(0);
- compositionDurationRef.current = compositionDuration;
+ const elements = usePlayerStore((s) => s.elements);
+ const timelineSnapEnabled = usePlayerStore((s) => s.timelineSnapEnabled);
+ const snapContextRef = useRef<{ beatTimes: number[]; enabled: boolean }>({
+ beatTimes: [],
+ enabled: true,
+ });
+ snapContextRef.current = {
+ beatTimes: adjustedBeatTimes,
+ enabled: timelineSnapEnabled,
+ };
+ const elementsRef = useRef(elements);
+ elementsRef.current = elements;
+
+ // Perf (frozen-per-gesture): the snap-target set and the audio-track set are
+ // fixed for the duration of one drag/resize (the store is not re-authored mid
+ // gesture), so build each ONCE and reuse it across every pointermove and every
+ // auto-scroll frame. Both caches are cleared at gesture teardown
+ // (stopClipDragAutoScroll), so the next gesture rebuilds against fresh state.
+ const snapTargetsCacheRef = useRef<Map<string, TimelineSnapTarget[]>>(new Map());
+ const dragAudioTracksRef = useRef<ReadonlySet<number> | null>(null);
const buildSnapTargets = useCallback(
- (element: TimelineElement) => {
- const draggedKey = element.key ?? element.id;
- const selected = selectedElementIdsRef.current;
- // In a group drag every selected clip moves together, so none of them may act
- // as a snap target for the others; exclude the whole set, not just the grabbed clip.
- const excludedKeys =
- selected.size > 1 && selected.has(draggedKey) ? selected : new Set([draggedKey]);
- return buildTimelineSnapTargets({
- elements: timelineElementsRef.current,
- excludedKeys,
- playhead: playheadRef.current,
- compDuration: compositionDurationRef.current,
- beats: isMusicTrack(element) ? EMPTY_BEAT_TIMES : beatTimesRef.current,
+ (excludeElementKey: string | null, includeBeats: boolean): TimelineSnapTarget[] => {
+ // Magnet off ⇒ no targets and no scan; do NOT cache so a mid-gesture toggle
+ // back on starts scanning immediately (preserves the existing skip).
+ if (!snapContextRef.current.enabled) return [];
+ const cacheKey = `${excludeElementKey ?? ""}|${includeBeats ? 1 : 0}`;
+ const cached = snapTargetsCacheRef.current.get(cacheKey);
+ if (cached) return cached;
+ const targets = collectTimelineSnapTargets({
+ elements: elementsRef.current,
+ playheadTime: usePlayerStore.getState().currentTime,
+ beatTimes: includeBeats ? snapContextRef.current.beatTimes : [],
+ excludeElementKey,
});
+ snapTargetsCacheRef.current.set(cacheKey, targets);
+ return targets;
},
- [timelineElementsRef],
+ [],
);
const [draggedClip, setDraggedClip] = useState<DraggedClipState | null>(null);
@@ -183,95 +175,125 @@ export function useTimelineClipDrag({
const blockedClipRef = useRef<BlockedClipState | null>(null);
const suppressClickRef = useRef(false);
+ // Active multi-select group-resize session (restored from main 36413da7f): set
+ // lazily on the first resize pointermove when the grabbed clip is part of a
+ // capability-clean multi-selection (null ⇒ single-clip resize). Holds the
+ // pre-gesture snapshot so the non-grabbed members (previewed through the store)
+ // roll back on escape / cancel / failed persist.
+ const groupResizeRef = useRef<TimelineGroupResizeSession | null>(null);
+
+ // Restore the non-grabbed group members to their pre-gesture timing (the
+ // grabbed clip renders from resizingClip state, so it is never written during
+ // preview). `all` also restores the grabbed clip after a committed persist fails.
+ const restoreGroupResizeMembers = useCallback(
+ (session: TimelineGroupResizeSession, all = false) => {
+ for (const m of session.members) {
+ if (!all && m.key === session.grabbedKey) continue;
+ updateElement(m.key, {
+ start: m.start,
+ duration: m.duration,
+ playbackStart: m.playbackStart,
+ });
+ }
+ },
+ [updateElement],
+ );
+
const onMoveElementRef = useRef(onMoveElement);
onMoveElementRef.current = onMoveElement;
- const onResizeElementRef = useRef(onResizeElement);
- onResizeElementRef.current = onResizeElement;
const onMoveElementsRef = useRef(onMoveElements);
onMoveElementsRef.current = onMoveElements;
+ const onBlockedEditAttemptRef = useRef(onBlockedEditAttempt);
+ onBlockedEditAttemptRef.current = onBlockedEditAttempt;
+ const onResizeElementRef = useRef(onResizeElement);
+ onResizeElementRef.current = onResizeElement;
const onResizeElementsRef = useRef(onResizeElements);
onResizeElementsRef.current = onResizeElements;
- const onPreviewMoveElementsRef = useRef(onPreviewMoveElements);
- onPreviewMoveElementsRef.current = onPreviewMoveElements;
- const onPreviewResizeElementsRef = useRef(onPreviewResizeElements);
- onPreviewResizeElementsRef.current = onPreviewResizeElements;
- const selectedElementIdsRef = useRef(usePlayerStore.getState().selectedElementIds);
- selectedElementIdsRef.current = usePlayerStore((s) => s.selectedElementIds);
+ const readZIndexRef = useRef(readZIndex);
+ readZIndexRef.current = readZIndex;
+ const onStackingPatchesRef = useRef(onStackingPatches);
+ onStackingPatchesRef.current = onStackingPatches;
const clipDragScrollRaf = useRef(0);
- const clipDragPointerRef = useRef<{ clientX: number; clientY: number } | null>(null);
- const {
- previewGroupMove,
- previewGroupResize,
- commitGroupMove,
- commitGroupResize,
- clearGroupDragSessions,
- } = useTimelineClipGroupDrag({
- timelineElementsRef,
- updateElement,
- onMoveElementsRef,
- onResizeElementsRef,
- onPreviewMoveElementsRef,
- onPreviewResizeElementsRef,
- });
-
- // fallow-ignore-next-line complexity
+ const clipDragPointerRef = useRef<{
+ clientX: number;
+ clientY: number;
+ } | null>(null);
+
+ // Recompute the dragged-clip preview for a pointer position. The heavy lifting
+ // (move + snap + group clamp + drop placement) is a tested pure function so
+ // what runs here is what's verified — see timelineClipDragPreview.
const updateDraggedClipPreview = useCallback(
(drag: DraggedClipState, clientX: number, clientY: number): DraggedClipState => {
- const scroll = scrollRef.current;
- const nextMove = resolveTimelineMove(
- {
- start: drag.element.start,
- track: drag.element.track,
- duration: drag.element.duration,
- originClientX: drag.originClientX,
- originClientY: drag.originClientY,
- originScrollLeft: drag.originScrollLeft,
- originScrollTop: drag.originScrollTop,
- currentScrollLeft: scroll?.scrollLeft ?? drag.originScrollLeft,
- currentScrollTop: scroll?.scrollTop ?? drag.originScrollTop,
- pixelsPerSecond: ppsRef.current,
- trackHeight: TRACK_H,
- maxStart: Number.POSITIVE_INFINITY,
- trackOrder: timelineLayersRef.current.map((layer) => layer.placementTrack),
- layerOrder: trackOrderRef.current,
- timelineLayers: timelineLayersRef.current,
- stackingElement: drag.element,
- stackingElements: timelineElementsRef.current,
- },
- clientX,
- clientY,
- );
- const snap = snapEdgesToTargets(
- nextMove.start,
- drag.element.duration,
- buildSnapTargets(drag.element),
- ppsRef.current,
- { maxStart: Number.POSITIVE_INFINITY },
- );
- const groupMove = previewGroupMove(drag.element, selectedElementIdsRef.current, snap.start);
- const placement = resolveDragPreviewPlacement(drag, nextMove, groupMove);
- return {
- ...drag,
- started: true,
- pointerClientX: clientX,
- pointerClientY: clientY,
- ...placement,
- snapBeatTime: snap.snapKind === "beat" ? snap.snapTime : null,
- snapGuideTime: snap.snapTime,
- snapGuideKind: snap.snapKind,
- };
+ // Build the audio-track set once per gesture (see snapTargetsCacheRef): it
+ // only feeds zone-aware drop placement and is frozen while dragging.
+ if (!dragAudioTracksRef.current) {
+ dragAudioTracksRef.current = new Set(
+ elementsRef.current.filter(isAudioTimelineElement).map((e) => e.track),
+ );
+ }
+ return computeDragPreview(drag, clientX, clientY, {
+ scroll: scrollRef.current,
+ pps: ppsRef.current,
+ duration: durationRef.current,
+ trackOrder: trackOrderRef.current,
+ elements: elementsRef.current,
+ selectedKeys: usePlayerStore.getState().selectedElementIds,
+ buildSnapTargets,
+ audioTracks: dragAudioTracksRef.current,
+ });
+ },
+ [scrollRef, ppsRef, durationRef, trackOrderRef, buildSnapTargets],
+ );
+
+ // Recompute the trim preview for a pointer x. Shared by the pointermove resize
+ // branch and the edge auto-scroll stepper (re-runs as content scrolls under a
+ // stationary pointer). computeResizePreview is pure; here we only apply state.
+ const applyResizePointer = useCallback(
+ (resize: ResizingClipState, clientX: number) => {
+ const next = computeResizePreview(resize, clientX, {
+ scroll: scrollRef.current,
+ pps: ppsRef.current,
+ buildSnapTargets,
+ });
+ const setResizeState = (v: ResizePreviewResult) =>
+ setResizingClip((prev) => (prev ? { ...prev, started: true, ...v } : prev));
+
+ // Group resize: a capability-clean multi-selection resizes rigidly by one
+ // shared, member-clamped delta (legacy main 36413da7f). The grabbed clip
+ // drives the raw delta and renders from resizingClip state; non-grabbed
+ // members preview through the store (their store value stays pristine).
+ const grabbedKey = resize.element.key ?? resize.element.id;
+ let session = groupResizeRef.current;
+ if (!session || session.grabbedKey !== grabbedKey || session.edge !== resize.edge) {
+ const members = buildTimelineGroupResizeMembers(
+ elementsRef.current,
+ usePlayerStore.getState().selectedElementIds,
+ grabbedKey,
+ resize.edge,
+ );
+ session = members
+ ? {
+ grabbedKey,
+ edge: resize.edge,
+ members,
+ changes: [],
+ hasChanged: false,
+ }
+ : null;
+ groupResizeRef.current = session;
+ }
+
+ if (!session) {
+ setResizeState(next);
+ return;
+ }
+ previewGroupResize(session, next, grabbedKey, updateElement, setResizeState);
},
- [
- scrollRef,
- ppsRef,
- trackOrderRef,
- timelineLayersRef,
- timelineElementsRef,
- buildSnapTargets,
- previewGroupMove,
- ],
+ [scrollRef, ppsRef, buildSnapTargets, updateElement],
);
+ const applyResizePointerRef = useRef(applyResizePointer);
+ applyResizePointerRef.current = applyResizePointer;
const stopClipDragAutoScroll = useCallback(() => {
clipDragPointerRef.current = null;
@@ -279,48 +301,47 @@ export function useTimelineClipDrag({
cancelAnimationFrame(clipDragScrollRaf.current);
clipDragScrollRaf.current = 0;
}
+ // Gesture teardown: drop the frozen-per-gesture perf caches so the next drag
+ // rebuilds them against fresh store state (see snapTargetsCacheRef). Does NOT
+ // touch groupResizeRef — commit reads it after this runs.
+ snapTargetsCacheRef.current.clear();
+ dragAudioTracksRef.current = null;
}, []);
const stepClipDragAutoScroll = useCallback(() => {
clipDragScrollRaf.current = 0;
const drag = draggedClipRef.current;
+ const resize = resizingClipRef.current;
const pointer = clipDragPointerRef.current;
const scroll = scrollRef.current;
- if (!drag || !pointer || !scroll) return;
-
- const rect = scroll.getBoundingClientRect();
- const delta = resolveTimelineAutoScroll(rect, pointer.clientX, pointer.clientY);
- if (delta.x === 0 && delta.y === 0) return;
-
- const maxScrollLeft = Math.max(0, scroll.scrollWidth - scroll.clientWidth);
- const maxScrollTop = Math.max(0, scroll.scrollHeight - scroll.clientHeight);
- const nextScrollLeft = Math.max(0, Math.min(maxScrollLeft, scroll.scrollLeft + delta.x));
- const nextScrollTop = Math.max(0, Math.min(maxScrollTop, scroll.scrollTop + delta.y));
- if (nextScrollLeft === scroll.scrollLeft && nextScrollTop === scroll.scrollTop) return;
-
- scroll.scrollLeft = nextScrollLeft;
- scroll.scrollTop = nextScrollTop;
- setDraggedClip((prev) =>
- prev ? updateDraggedClipPreview(prev, pointer.clientX, pointer.clientY) : prev,
- );
+ if ((!drag && !resize) || !pointer || !scroll) return;
+ if (!applyTimelineAutoScrollStep(scroll, pointer.clientX, pointer.clientY)) return;
+
+ if (drag) {
+ setDraggedClip((prev) =>
+ prev ? updateDraggedClipPreview(prev, pointer.clientX, pointer.clientY) : prev,
+ );
+ } else if (resize) {
+ // Re-run the trim preview so the edge keeps tracking while the content
+ // scrolls under the stationary pointer (scroll-compensated pointer x).
+ applyResizePointerRef.current(resize, pointer.clientX);
+ }
clipDragScrollRaf.current = requestAnimationFrame(stepClipDragAutoScroll);
}, [scrollRef, updateDraggedClipPreview]);
const syncClipDragAutoScroll = useCallback(
(clientX: number, clientY: number) => {
clipDragPointerRef.current = { clientX, clientY };
- const scroll = scrollRef.current;
- if (!scroll) return;
- const rect = scroll.getBoundingClientRect();
- const delta = resolveTimelineAutoScroll(rect, clientX, clientY);
- if (delta.x === 0 && delta.y === 0) {
- if (clipDragScrollRaf.current) {
- cancelAnimationFrame(clipDragScrollRaf.current);
- clipDragScrollRaf.current = 0;
- }
- return;
- }
- if (!clipDragScrollRaf.current) {
+ const action = resolveTimelineAutoScrollLoopAction(
+ scrollRef.current,
+ clientX,
+ clientY,
+ clipDragScrollRaf.current !== 0,
+ );
+ if (action === "stop") {
+ cancelAnimationFrame(clipDragScrollRaf.current);
+ clipDragScrollRaf.current = 0;
+ } else if (action === "start") {
clipDragScrollRaf.current = requestAnimationFrame(stepClipDragAutoScroll);
}
},
@@ -329,12 +350,6 @@ export function useTimelineClipDrag({
const updateDraggedClipPreviewRef = useRef(updateDraggedClipPreview);
updateDraggedClipPreviewRef.current = updateDraggedClipPreview;
- const commitGroupMoveRef = useRef(commitGroupMove);
- commitGroupMoveRef.current = commitGroupMove;
- const commitGroupResizeRef = useRef(commitGroupResize);
- commitGroupResizeRef.current = commitGroupResize;
- const clearGroupDragSessionsRef = useRef(clearGroupDragSessions);
- clearGroupDragSessionsRef.current = clearGroupDragSessions;
const syncClipDragAutoScrollRef = useRef(syncClipDragAutoScroll);
syncClipDragAutoScrollRef.current = syncClipDragAutoScroll;
const stopClipDragAutoScrollRef = useRef(stopClipDragAutoScroll);
@@ -347,121 +362,39 @@ export function useTimelineClipDrag({
});
};
- // fallow-ignore-next-line complexity
- const handleWindowPointerMove = (e: PointerEvent) => {
- const drag = draggedClipRef.current;
- const resize = resizingClipRef.current;
- const blocked = blockedClipRef.current;
+ /* ── pointermove branch handlers (dispatched by drag/resize/blocked) ── */
+ const handleResizePointerMove = (e: PointerEvent, resize: ResizingClipState) => {
+ const distance = Math.abs(e.clientX - resize.originClientX);
+ if (!resize.started && distance < 2) return;
- if (resize) {
- const distance = Math.abs(e.clientX - resize.originClientX);
- if (!resize.started && distance < 2) return;
+ setShowPopover(false);
+ setRangeSelectionRef.current?.(null);
+
+ applyResizePointerRef.current(resize, e.clientX);
+ // Edge auto-scroll during a trim, exactly like the move branch — lets a
+ // right-edge trim keep extending past the current viewport (the stepper
+ // re-runs the scroll-compensated preview each frame).
+ syncClipDragAutoScrollRef.current(e.clientX, e.clientY);
+ };
+ const handleBlockedPointerMove = (e: PointerEvent, blocked: BlockedClipState) => {
+ const distance = Math.hypot(
+ e.clientX - blocked.originClientX,
+ e.clientY - blocked.originClientY,
+ );
+ const threshold = blocked.intent === "move" ? 4 : 2;
+ if (!blocked.started && distance < threshold) return;
+ if (!blocked.started) {
+ blocked.started = true;
+ blockedClipRef.current = blocked;
+ suppressClickRef.current = true;
setShowPopover(false);
setRangeSelectionRef.current?.(null);
-
- const sourceRemaining =
- resize.element.sourceDuration != null
- ? Math.max(
- 0,
- (resize.element.sourceDuration - (resize.element.playbackStart ?? 0)) /
- Math.max(resize.element.playbackRate ?? 1, 0.1),
- )
- : Number.POSITIVE_INFINITY;
- const normalizedTag = resize.element.tag.toLowerCase();
- const canSeedPlaybackStart = normalizedTag === "audio" || normalizedTag === "video";
- const playbackRate = Math.max(resize.element.playbackRate ?? 1, 0.1);
- const maxEnd = resize.element.start + sourceRemaining;
- let nextResize = resolveTimelineResize(
- {
- start: resize.element.start,
- duration: resize.element.duration,
- originClientX: resize.originClientX,
- pixelsPerSecond: ppsRef.current,
- minStart: 0,
- maxEnd,
- playbackStart:
- resize.edge === "start" && canSeedPlaybackStart
- ? (resize.element.playbackStart ?? 0)
- : resize.element.playbackStart,
- playbackRate: resize.element.playbackRate,
- },
- resize.edge,
- e.clientX,
- );
-
- const snap = snapResizeEdgeToTargets(
- resize.edge,
- nextResize.start,
- nextResize.duration,
- buildSnapTargets(resize.element),
- ppsRef.current,
- {
- minDuration: 0.05,
- maxEnd,
- maxLeftDelta:
- resize.edge === "start" && nextResize.playbackStart != null
- ? nextResize.playbackStart / playbackRate
- : Number.POSITIVE_INFINITY,
- },
- );
- if (snap.snapTime != null) {
- const unsnappedStart = nextResize.start;
- nextResize = { ...nextResize, start: snap.start, duration: snap.duration };
- if (resize.edge === "start" && nextResize.playbackStart != null) {
- const delta = unsnappedStart - snap.start;
- nextResize = {
- ...nextResize,
- playbackStart:
- Math.round(Math.max(0, nextResize.playbackStart - delta * playbackRate) * 1000) /
- 1000,
- };
- }
- }
- const groupResize = previewGroupResize(
- resize.element,
- selectedElementIdsRef.current,
- resize.edge,
- nextResize,
- );
- if (groupResize.active) {
- nextResize = groupResize.updates;
- }
- setResizingClip((prev) =>
- prev
- ? {
- ...prev,
- started: true,
- previewStart: nextResize.start,
- previewDuration: nextResize.duration,
- previewPlaybackStart: nextResize.playbackStart,
- snapGuideTime: snap.snapTime,
- snapGuideKind: snap.snapKind,
- }
- : prev,
- );
- return;
- }
-
- if (blocked) {
- const distance = Math.hypot(
- e.clientX - blocked.originClientX,
- e.clientY - blocked.originClientY,
- );
- const threshold = blocked.intent === "move" ? 4 : 2;
- if (!blocked.started && distance < threshold) return;
- if (!blocked.started) {
- blocked.started = true;
- blockedClipRef.current = blocked;
- suppressClickRef.current = true;
- setShowPopover(false);
- setRangeSelectionRef.current?.(null);
- onBlockedEditAttempt?.(blocked.element, blocked.intent);
- }
- return;
+ onBlockedEditAttemptRef.current?.(blocked.element, blocked.intent);
}
+ };
- if (!drag) return;
+ const handleDragPointerMove = (e: PointerEvent, drag: DraggedClipState) => {
const distance = Math.hypot(e.clientX - drag.originClientX, e.clientY - drag.originClientY);
if (!drag.started && distance < 4) return;
@@ -474,60 +407,77 @@ export function useTimelineClipDrag({
syncClipDragAutoScrollRef.current(e.clientX, e.clientY);
};
- // fallow-ignore-next-line complexity
- const handleWindowPointerUp = () => {
- stopClipDragAutoScrollRef.current();
-
+ const handleWindowPointerMove = (e: PointerEvent) => {
const resize = resizingClipRef.current;
- if (resize) {
- resizingClipRef.current = null;
- setResizingClip(null);
- if (!resize.started) return;
+ if (resize) return handleResizePointerMove(e, resize);
+ const blocked = blockedClipRef.current;
+ if (blocked) return handleBlockedPointerMove(e, blocked);
+ const drag = draggedClipRef.current;
+ if (drag) handleDragPointerMove(e, drag);
+ };
- suppressClickRef.current = true;
- clearSuppressedClick();
+ /* ── pointerup commit handlers (dispatched by drag/resize/blocked) ──── */
+ const commitResizePointerUp = (resize: ResizingClipState) => {
+ resizingClipRef.current = null;
+ setResizingClip(null);
+ const groupSession = groupResizeRef.current;
+ groupResizeRef.current = null;
+ if (!resize.started) {
+ // No preview ran, so no group store-mutation to undo; guard is defensive.
+ if (groupSession) restoreGroupResizeMembers(groupSession);
+ return;
+ }
- if (commitGroupResizeRef.current(resize.element)) return;
+ suppressClickRef.current = true;
+ clearSuppressedClick();
- const hasChanged =
- resize.previewStart !== resize.element.start ||
- resize.previewDuration !== resize.element.duration ||
- resize.previewPlaybackStart !== resize.element.playbackStart;
- if (!hasChanged) return;
+ if (groupSession) {
+ commitTimelineGroupResize(groupSession, updateElement, onResizeElementsRef.current);
+ return;
+ }
- updateElement(resize.element.key ?? resize.element.id, {
+ const hasChanged =
+ resize.previewStart !== resize.element.start ||
+ resize.previewDuration !== resize.element.duration ||
+ resize.previewPlaybackStart !== resize.element.playbackStart;
+ if (!hasChanged) return;
+
+ const resizeKey = resize.element.key ?? resize.element.id;
+ const revision = beginTimelineOptimisticGesture(updateElement, [resizeKey]);
+ updateElement(resizeKey, {
+ start: resize.previewStart,
+ duration: resize.previewDuration,
+ playbackStart: resize.previewPlaybackStart,
+ });
+
+ Promise.resolve(
+ onResizeElementRef.current?.(resize.element, {
start: resize.previewStart,
duration: resize.previewDuration,
playbackStart: resize.previewPlaybackStart,
- });
-
- Promise.resolve(
- onResizeElementRef.current?.(resize.element, {
- start: resize.previewStart,
- duration: resize.previewDuration,
- playbackStart: resize.previewPlaybackStart,
- }),
- ).catch((error) => {
- updateElement(resize.element.key ?? resize.element.id, {
- start: resize.element.start,
- duration: resize.element.duration,
- playbackStart: resize.element.playbackStart,
- });
- console.error("[Timeline] Failed to persist clip resize", error);
- });
- return;
- }
+ }),
+ ).catch((error) => {
+ rollbackLatestTimelineOptimisticGesture(updateElement, revision, [
+ {
+ key: resizeKey,
+ updates: {
+ start: resize.element.start,
+ duration: resize.element.duration,
+ playbackStart: resize.element.playbackStart,
+ },
+ },
+ ]);
+ console.error("[Timeline] Failed to persist clip resize", error);
+ });
+ };
- const blocked = blockedClipRef.current;
- if (blocked) {
- blockedClipRef.current = null;
- if (!blocked.started) return;
- clearSuppressedClick();
- return;
- }
+ const finishBlockedPointerUp = (blocked: BlockedClipState) => {
+ blockedClipRef.current = null;
+ if (!blocked.started) return;
+ clearSuppressedClick();
+ };
- const drag = draggedClipRef.current;
- if (!drag) return;
+ const commitDragPointerUp = (drag: DraggedClipState) => {
draggedClipRef.current = null;
setDraggedClip(null);
if (!drag.started) return;
@@ -535,40 +485,84 @@ export function useTimelineClipDrag({
suppressClickRef.current = true;
clearSuppressedClick();
- if (commitGroupMoveRef.current(drag.element)) return;
+ // Commit the drag — insert (new track), main-track ripple (reflow contiguous),
+ // a plain single-clip move, or a multi-selection move (every selected clip
+ // shifts by the dragged clip's time delta). See timelineClipDragCommit.
+ commitDraggedClipMove(drag, {
+ elements: elementsRef.current,
+ trackOrder: trackOrderRef.current,
+ updateElement,
+ onMoveElement: onMoveElementRef.current,
+ onMoveElements: onMoveElementsRef.current,
+ selectedKeys: usePlayerStore.getState().selectedElementIds,
+ // Lane ↔ stacking: engages only when the timeline layer provisions both
+ // deps (Timeline.tsx). Absent → commitDraggedClipMove skips the z-sync.
+ readZIndex: readZIndexRef.current,
+ onStackingPatches: onStackingPatchesRef.current,
+ });
+ };
- const hasStackingReorder =
- drag.previewStackingReorder != null && drag.previewStackingReorder.zIndexChanges.length > 0;
- const hasChanged = drag.previewStart !== drag.element.start || hasStackingReorder;
- if (!hasChanged) return;
+ const handleWindowPointerUp = () => {
+ stopClipDragAutoScrollRef.current();
- updateElement(drag.element.key ?? drag.element.id, {
- start: drag.previewStart,
- });
+ const resize = resizingClipRef.current;
+ if (resize) return commitResizePointerUp(resize);
- Promise.resolve(
- onMoveElementRef.current?.(drag.element, {
- start: drag.previewStart,
- track: drag.element.track,
- stackingReorder: drag.previewStackingReorder,
- }),
- ).catch((error) => {
- updateElement(drag.element.key ?? drag.element.id, {
- start: drag.element.start,
- });
- console.error("[Timeline] Failed to persist clip move", error);
+ const blocked = blockedClipRef.current;
+ if (blocked) return finishBlockedPointerUp(blocked);
+
+ const drag = draggedClipRef.current;
+ if (!drag) {
+ // Escape-cancel leaves the click suppressor armed so the click this
+ // pointerup generates can't act on the clip; disarm it right after.
+ if (suppressClickRef.current) clearSuppressedClick();
+ return;
+ }
+ commitDragPointerUp(drag);
+ };
+
+ // Escape cancels the in-progress gesture: no commit, no undo entry. The
+ // previews live only in the drag/resize state (the store is untouched
+ // until the pointerup commit), so clearing them restores the pre-drag
+ // timeline. Clip drags never take pointer capture (all tracking runs on
+ // these window listeners), so there is no capture to release; the null
+ // refs make the remaining pointermove/pointerup a no-op.
+ const handleWindowKeyDown = (e: KeyboardEvent) => {
+ const decision = resolveTimelineDragEscape({
+ key: e.key,
+ drag: draggedClipRef.current,
+ resize: resizingClipRef.current,
+ blocked: blockedClipRef.current,
});
+ if (!decision.cancel) return;
+ e.preventDefault();
+ e.stopPropagation();
+ stopClipDragAutoScrollRef.current();
+ draggedClipRef.current = null;
+ setDraggedClip(null);
+ resizingClipRef.current = null;
+ setResizingClip(null);
+ // Undo any group-resize preview store-mutation (non-grabbed members) so the
+ // cancelled gesture restores the pre-drag timeline, like the single-clip path.
+ const groupSession = groupResizeRef.current;
+ groupResizeRef.current = null;
+ if (groupSession) restoreGroupResizeMembers(groupSession);
+ blockedClipRef.current = null;
+ // The pointer is usually still down; keep the suppressor armed until the
+ // eventual pointerup (which disarms it) so its click can't reselect.
+ if (decision.suppressClick) suppressClickRef.current = true;
};
window.addEventListener("pointermove", handleWindowPointerMove);
window.addEventListener("pointerup", handleWindowPointerUp);
window.addEventListener("pointercancel", handleWindowPointerUp);
+ window.addEventListener("keydown", handleWindowKeyDown, true);
return () => {
- clearGroupDragSessionsRef.current();
stopClipDragAutoScrollRef.current();
window.removeEventListener("pointermove", handleWindowPointerMove);
window.removeEventListener("pointerup", handleWindowPointerUp);
window.removeEventListener("pointercancel", handleWindowPointerUp);
+ window.removeEventListener("keydown", handleWindowKeyDown, true);
};
});
diff --git a/packages/studio/src/player/components/useTimelineClipGroupDrag.ts b/packages/studio/src/player/components/useTimelineClipGroupDrag.ts
deleted file mode 100644
index 6bc6bc9ecc..0000000000
--- a/packages/studio/src/player/components/useTimelineClipGroupDrag.ts
+++ /dev/null
@@ -1,417 +0,0 @@
-import { useCallback, useRef, type RefObject } from "react";
-import type {
- TimelineGroupMoveChange,
- TimelineGroupResizeChange,
-} from "../../hooks/useTimelineGroupEditing";
-import type { TimelineElement } from "../store/playerStore";
-import {
- getTimelineEditCapabilities,
- resolveTimelineGroupMove,
- resolveTimelineGroupResize,
- type TimelineGroupResizeEdge,
- type TimelineGroupTimingMember,
-} from "./timelineEditing";
-
-type TimelineResizeUpdates = Pick<TimelineElement, "start" | "duration" | "playbackStart">;
-
-type UpdateTimelineElement = (
- elementId: string,
- updates: Partial<Pick<TimelineElement, "start" | "duration" | "playbackStart">>,
-) => void;
-
-interface GroupTimingMember extends TimelineGroupTimingMember {
- element: TimelineElement;
- key: string;
-}
-
-interface MoveSession {
- grabbedKey: string;
- members: GroupTimingMember[];
- changes: TimelineGroupMoveChange[];
- hasChanged: boolean;
-}
-
-interface ResizeSession {
- grabbedKey: string;
- edge: TimelineGroupResizeEdge;
- members: GroupTimingMember[];
- changes: TimelineGroupResizeChange[];
- hasChanged: boolean;
-}
-
-interface UseTimelineClipGroupDragInput {
- timelineElementsRef: RefObject<TimelineElement[]>;
- updateElement: UpdateTimelineElement;
- onMoveElementsRef: RefObject<
- ((changes: TimelineGroupMoveChange[]) => Promise<void> | void) | undefined
- >;
- onResizeElementsRef: RefObject<
- ((changes: TimelineGroupResizeChange[]) => Promise<void> | void) | undefined
- >;
- onPreviewMoveElementsRef: RefObject<((changes: TimelineGroupMoveChange[]) => void) | undefined>;
- onPreviewResizeElementsRef: RefObject<
- ((changes: TimelineGroupResizeChange[]) => void) | undefined
- >;
-}
-
-interface PreviewGroupMoveResult {
- active: boolean;
- previewStart: number;
-}
-
-interface PreviewGroupResizeResult {
- active: boolean;
- updates: TimelineResizeUpdates;
-}
-
-function elementKey(element: TimelineElement): string {
- return element.key ?? element.id;
-}
-
-function isMediaElement(element: TimelineElement): boolean {
- const normalizedTag = element.tag.toLowerCase();
- return normalizedTag === "audio" || normalizedTag === "video";
-}
-
-function selectedElementSet(selectedElementIdsInput: Set<string>): Set<string> {
- return selectedElementIdsInput instanceof Set ? selectedElementIdsInput : new Set<string>();
-}
-
-function selectedMembers(
- grabbedElement: TimelineElement,
- selectedElementIdsInput: Set<string>,
- timelineElements: readonly TimelineElement[],
- mapMember: (element: TimelineElement) => GroupTimingMember,
- canEdit: (element: TimelineElement) => boolean,
-): GroupTimingMember[] | null {
- const selectedElementIds = selectedElementSet(selectedElementIdsInput);
- const grabbedKey = elementKey(grabbedElement);
- if (selectedElementIds.size <= 1 || !selectedElementIds.has(grabbedKey)) return null;
-
- const elements = timelineElements.filter((element) =>
- selectedElementIds.has(elementKey(element)),
- );
- // A group edit must not touch a member that individually forbids this operation
- // (e.g. a locked or implicitly-timed clip). If any member can't take it, don't form
- // a group; the gesture degrades to a normal single-clip edit of the grabbed clip.
- if (!elements.every(canEdit)) return null;
- const members = elements.map(mapMember);
- return members.length > 1 ? members : null;
-}
-
-function moveMember(element: TimelineElement): GroupTimingMember {
- return {
- element,
- key: elementKey(element),
- start: element.start,
- duration: element.duration,
- };
-}
-
-function resizeMember(edge: TimelineGroupResizeEdge, element: TimelineElement): GroupTimingMember {
- const shouldSeedPlaybackStart = edge === "start" && isMediaElement(element);
- return {
- element,
- key: elementKey(element),
- start: element.start,
- duration: element.duration,
- playbackStart: shouldSeedPlaybackStart ? (element.playbackStart ?? 0) : element.playbackStart,
- playbackRate: element.playbackRate,
- };
-}
-
-function sameGesture(sessionKey: string, element: TimelineElement): boolean {
- return sessionKey === elementKey(element);
-}
-
-function createMoveSession(
- element: TimelineElement,
- selectedElementIds: Set<string>,
- timelineElements: readonly TimelineElement[],
-): MoveSession | null {
- const members = selectedMembers(
- element,
- selectedElementIds,
- timelineElements,
- moveMember,
- (candidate) => getTimelineEditCapabilities(candidate).canMove,
- );
- if (!members) return null;
- return {
- grabbedKey: elementKey(element),
- members,
- changes: [],
- hasChanged: false,
- };
-}
-
-function createResizeSession(
- element: TimelineElement,
- selectedElementIds: Set<string>,
- timelineElements: readonly TimelineElement[],
- edge: TimelineGroupResizeEdge,
-): ResizeSession | null {
- const members = selectedMembers(
- element,
- selectedElementIds,
- timelineElements,
- (member) => resizeMember(edge, member),
- (candidate) => {
- const caps = getTimelineEditCapabilities(candidate);
- return edge === "start" ? caps.canTrimStart : caps.canTrimEnd;
- },
- );
- if (!members) return null;
- return {
- grabbedKey: elementKey(element),
- edge,
- members,
- changes: [],
- hasChanged: false,
- };
-}
-
-function resolveMoveChanges(
- session: MoveSession,
- previewStart: number,
-): TimelineGroupMoveChange[] | null {
- const grabbed = session.members.find((member) => member.key === session.grabbedKey);
- if (!grabbed) return null;
- const result = resolveTimelineGroupMove(session.members, previewStart - grabbed.start);
- return result.members.map((member, index) => ({
- element: session.members[index]!.element,
- start: member.start,
- }));
-}
-
-function resizeRawDelta(session: ResizeSession, updates: TimelineResizeUpdates): number | null {
- const grabbed = session.members.find((member) => member.key === session.grabbedKey);
- if (!grabbed) return null;
- return session.edge === "start"
- ? updates.start - grabbed.start
- : updates.duration - grabbed.duration;
-}
-
-function resolveResizeChanges(
- session: ResizeSession,
- updates: TimelineResizeUpdates,
-): TimelineGroupResizeChange[] | null {
- const rawDelta = resizeRawDelta(session, updates);
- if (rawDelta == null) return null;
- const result = resolveTimelineGroupResize(session.members, session.edge, rawDelta);
- return result.members.map((member, index) => ({
- element: session.members[index]!.element,
- start: member.start,
- duration: member.duration,
- playbackStart: member.playbackStart,
- }));
-}
-
-function moveSessionHasChanged(
- session: MoveSession,
- changes: readonly TimelineGroupMoveChange[],
-): boolean {
- return changes.some((change, index) => change.start !== session.members[index]!.start);
-}
-
-function resizeSessionHasChanged(
- session: ResizeSession,
- changes: readonly TimelineGroupResizeChange[],
-): boolean {
- return changes.some((change, index) => {
- const member = session.members[index]!;
- return (
- change.start !== member.start ||
- change.duration !== member.duration ||
- change.playbackStart !== member.playbackStart
- );
- });
-}
-
-function previewStartForGrabbed(
- session: MoveSession,
- changes: readonly TimelineGroupMoveChange[],
- fallback: number,
-): number {
- const change = changes.find((candidate) => elementKey(candidate.element) === session.grabbedKey);
- return change?.start ?? fallback;
-}
-
-function resizeUpdatesForGrabbed(
- session: ResizeSession,
- changes: readonly TimelineGroupResizeChange[],
- fallback: TimelineResizeUpdates,
-): TimelineResizeUpdates {
- const change = changes.find((candidate) => elementKey(candidate.element) === session.grabbedKey);
- if (!change) return fallback;
- return {
- start: change.start,
- duration: change.duration,
- playbackStart: change.playbackStart,
- };
-}
-
-export function useTimelineClipGroupDrag({
- timelineElementsRef,
- updateElement,
- onMoveElementsRef,
- onResizeElementsRef,
- onPreviewMoveElementsRef,
- onPreviewResizeElementsRef,
-}: UseTimelineClipGroupDragInput) {
- const moveSessionRef = useRef<MoveSession | null>(null);
- const resizeSessionRef = useRef<ResizeSession | null>(null);
-
- const rollbackMove = useCallback(
- (session: MoveSession) => {
- const changes = session.members.map((member) => ({
- element: member.element,
- start: member.start,
- }));
- for (const change of changes) {
- updateElement(elementKey(change.element), { start: change.start });
- }
- onPreviewMoveElementsRef.current?.(changes);
- },
- [onPreviewMoveElementsRef, updateElement],
- );
-
- const rollbackResize = useCallback(
- (session: ResizeSession) => {
- const changes = session.members.map((member) => ({
- element: member.element,
- start: member.start,
- duration: member.duration,
- playbackStart: member.playbackStart,
- }));
- for (const change of changes) {
- updateElement(elementKey(change.element), {
- start: change.start,
- duration: change.duration,
- playbackStart: change.playbackStart,
- });
- }
- onPreviewResizeElementsRef.current?.(changes);
- },
- [onPreviewResizeElementsRef, updateElement],
- );
-
- const previewGroupMove = useCallback(
- (
- element: TimelineElement,
- selectedElementIds: Set<string>,
- previewStart: number,
- ): PreviewGroupMoveResult => {
- let session = moveSessionRef.current;
- if (!session || !sameGesture(session.grabbedKey, element)) {
- if (!onMoveElementsRef.current) return { active: false, previewStart };
- session = createMoveSession(element, selectedElementIds, timelineElementsRef.current);
- if (!session) return { active: false, previewStart };
- moveSessionRef.current = session;
- }
-
- const changes = resolveMoveChanges(session, previewStart);
- if (!changes) return { active: false, previewStart };
- session.changes = changes;
- session.hasChanged = moveSessionHasChanged(session, changes);
-
- for (const change of changes) {
- updateElement(elementKey(change.element), { start: change.start });
- }
- onPreviewMoveElementsRef.current?.(changes);
-
- return {
- active: true,
- previewStart: previewStartForGrabbed(session, changes, previewStart),
- };
- },
- [onMoveElementsRef, onPreviewMoveElementsRef, timelineElementsRef, updateElement],
- );
-
- const previewGroupResize = useCallback(
- (
- element: TimelineElement,
- selectedElementIds: Set<string>,
- edge: TimelineGroupResizeEdge,
- updates: TimelineResizeUpdates,
- ): PreviewGroupResizeResult => {
- let session = resizeSessionRef.current;
- if (!session || !sameGesture(session.grabbedKey, element) || session.edge !== edge) {
- if (!onResizeElementsRef.current) return { active: false, updates };
- session = createResizeSession(
- element,
- selectedElementIds,
- timelineElementsRef.current,
- edge,
- );
- if (!session) return { active: false, updates };
- resizeSessionRef.current = session;
- }
-
- const changes = resolveResizeChanges(session, updates);
- if (!changes) return { active: false, updates };
- session.changes = changes;
- session.hasChanged = resizeSessionHasChanged(session, changes);
-
- for (const change of changes) {
- updateElement(elementKey(change.element), {
- start: change.start,
- duration: change.duration,
- playbackStart: change.playbackStart,
- });
- }
- onPreviewResizeElementsRef.current?.(changes);
-
- return {
- active: true,
- updates: resizeUpdatesForGrabbed(session, changes, updates),
- };
- },
- [onPreviewResizeElementsRef, onResizeElementsRef, timelineElementsRef, updateElement],
- );
-
- const commitGroupMove = useCallback(
- (element: TimelineElement): boolean => {
- const session = moveSessionRef.current;
- if (!session || !sameGesture(session.grabbedKey, element)) return false;
- moveSessionRef.current = null;
- if (!session.hasChanged) return true;
-
- Promise.resolve(onMoveElementsRef.current?.(session.changes)).catch((error) => {
- rollbackMove(session);
- console.error("[Timeline] Failed to persist group clip move", error);
- });
- return true;
- },
- [onMoveElementsRef, rollbackMove],
- );
-
- const commitGroupResize = useCallback(
- (element: TimelineElement): boolean => {
- const session = resizeSessionRef.current;
- if (!session || !sameGesture(session.grabbedKey, element)) return false;
- resizeSessionRef.current = null;
- if (!session.hasChanged) return true;
-
- Promise.resolve(onResizeElementsRef.current?.(session.changes)).catch((error) => {
- rollbackResize(session);
- console.error("[Timeline] Failed to persist group clip resize", error);
- });
- return true;
- },
- [onResizeElementsRef, rollbackResize],
- );
-
- const clearGroupDragSessions = useCallback(() => {
- moveSessionRef.current = null;
- resizeSessionRef.current = null;
- }, []);
-
- return {
- previewGroupMove,
- previewGroupResize,
- commitGroupMove,
- commitGroupResize,
- clearGroupDragSessions,
- };
-}
diff --git a/packages/studio/src/player/components/useTimelineEditPinning.ts b/packages/studio/src/player/components/useTimelineEditPinning.ts
new file mode 100644
index 0000000000..2cd980bd98
--- /dev/null
+++ b/packages/studio/src/player/components/useTimelineEditPinning.ts
@@ -0,0 +1,121 @@
+import { useCallback, useMemo, useRef, type RefObject } from "react";
+import { usePlayerStore } from "../store/playerStore";
+import type { TimelineDropCallbacks, TimelineEditCallbacks } from "./timelineCallbacks";
+
+interface UseTimelineEditPinningInput {
+ ppsRef: RefObject<number>;
+ fitPpsRef: RefObject<number>;
+ onMoveElement: TimelineEditCallbacks["onMoveElement"];
+ onMoveElements: TimelineEditCallbacks["onMoveElements"];
+ onResizeElement: TimelineEditCallbacks["onResizeElement"];
+ onResizeElements: TimelineEditCallbacks["onResizeElements"];
+ onFileDrop: TimelineDropCallbacks["onFileDrop"];
+ onAssetDrop: TimelineDropCallbacks["onAssetDrop"];
+ onBlockDrop: TimelineDropCallbacks["onBlockDrop"];
+}
+
+// Wrap every mutating timeline edit so the zoom pins to the current on-screen
+// scale right before the edit commits — the reload the edit triggers then keeps
+// the current scale instead of rescaling every clip (the blink-fix symptom).
+// Each wrapper forwards its args unchanged and preserves the original's absence
+// (an unset callback stays unset → the timeline's own fallbacks kick in).
+export function useTimelineEditPinning({
+ ppsRef,
+ fitPpsRef,
+ onMoveElement,
+ onMoveElements,
+ onResizeElement,
+ onResizeElements,
+ onFileDrop,
+ onAssetDrop,
+ onBlockDrop,
+}: UseTimelineEditPinningInput) {
+ const pinTimelineZoom = usePlayerStore((s) => s.pinTimelineZoom);
+ // Pin the timeline zoom to the current on-screen scale on the FIRST edit, so a
+ // duration change from that edit (drops/moves/deletes recompute the fit basis)
+ // stops rescaling every clip. `pinTimelineZoom` is a no-op once already pinned
+ // (or after a manual zoom), so the user's own zoom is never clobbered; Fit
+ // re-fits. Reads refs at call time for the latest scale.
+ const pinZoomBeforeEdit = useCallback(() => {
+ pinTimelineZoom(ppsRef.current, fitPpsRef.current);
+ }, [pinTimelineZoom, ppsRef, fitPpsRef]);
+
+ // Stable ref so useTimelineClipDrag can clear rangeSelection without circular dep
+ const setRangeSelectionRef = useRef<((sel: null) => void) | null>(null);
+
+ const pinnedOnMoveElement = useMemo(
+ () =>
+ onMoveElement &&
+ ((...args: Parameters<typeof onMoveElement>) => {
+ pinZoomBeforeEdit();
+ return onMoveElement(...args);
+ }),
+ [onMoveElement, pinZoomBeforeEdit],
+ );
+ const pinnedOnMoveElements = useMemo(
+ () =>
+ onMoveElements &&
+ ((...args: Parameters<typeof onMoveElements>) => {
+ pinZoomBeforeEdit();
+ return onMoveElements(...args);
+ }),
+ [onMoveElements, pinZoomBeforeEdit],
+ );
+ const pinnedOnResizeElement = useMemo(
+ () =>
+ onResizeElement &&
+ ((...args: Parameters<typeof onResizeElement>) => {
+ pinZoomBeforeEdit();
+ return onResizeElement(...args);
+ }),
+ [onResizeElement, pinZoomBeforeEdit],
+ );
+ const pinnedOnResizeElements = useMemo(
+ () =>
+ onResizeElements &&
+ ((...args: Parameters<typeof onResizeElements>) => {
+ pinZoomBeforeEdit();
+ return onResizeElements(...args);
+ }),
+ [onResizeElements, pinZoomBeforeEdit],
+ );
+ const pinnedOnFileDrop = useMemo(
+ () =>
+ onFileDrop &&
+ ((...args: Parameters<typeof onFileDrop>) => {
+ pinZoomBeforeEdit();
+ return onFileDrop(...args);
+ }),
+ [onFileDrop, pinZoomBeforeEdit],
+ );
+ const pinnedOnAssetDrop = useMemo(
+ () =>
+ onAssetDrop &&
+ ((...args: Parameters<typeof onAssetDrop>) => {
+ pinZoomBeforeEdit();
+ return onAssetDrop(...args);
+ }),
+ [onAssetDrop, pinZoomBeforeEdit],
+ );
+ const pinnedOnBlockDrop = useMemo(
+ () =>
+ onBlockDrop &&
+ ((...args: Parameters<typeof onBlockDrop>) => {
+ pinZoomBeforeEdit();
+ return onBlockDrop(...args);
+ }),
+ [onBlockDrop, pinZoomBeforeEdit],
+ );
+
+ return {
+ pinZoomBeforeEdit,
+ setRangeSelectionRef,
+ pinnedOnMoveElement,
+ pinnedOnMoveElements,
+ pinnedOnResizeElement,
+ pinnedOnResizeElements,
+ pinnedOnFileDrop,
+ pinnedOnAssetDrop,
+ pinnedOnBlockDrop,
+ };
+}
diff --git a/packages/studio/src/player/components/useTimelineGeometry.ts b/packages/studio/src/player/components/useTimelineGeometry.ts
new file mode 100644
index 0000000000..fb18810902
--- /dev/null
+++ b/packages/studio/src/player/components/useTimelineGeometry.ts
@@ -0,0 +1,129 @@
+import { useEffect, useMemo, useRef, type RefObject } from "react";
+import { usePlayerStore, type TimelineElement, type ZoomMode } from "../store/playerStore";
+import { getTimelinePixelsPerSecond } from "./timelineZoom";
+import {
+ DRAG_EXTEND_MARGIN_PX,
+ getTimelineDisplayContentWidth,
+ getTimelineFitPps,
+} from "./timelineLayout";
+import type { DraggedClipState, ResizingClipState } from "./useTimelineClipDrag";
+
+interface UseTimelineGeometryInput {
+ viewportWidth: number;
+ effectiveDuration: number;
+ zoomMode: ZoomMode;
+ manualZoomPercent: number;
+ ppsRef: RefObject<number>;
+ fitPpsRef: RefObject<number>;
+ draggedClip: DraggedClipState | null;
+ resizingClip: ResizingClipState | null;
+ expandedElements: TimelineElement[];
+ isDragging: RefObject<boolean>;
+ scrollRef: RefObject<HTMLDivElement | null>;
+ lastScrollLeftRef: RefObject<number>;
+}
+
+// Derive the timeline's horizontal geometry from the viewport, zoom, and any live
+// drag/resize preview: the pixels-per-second scale, the rendered content width
+// (CapCut-style over-extension while dragging/trimming), and the version key that
+// re-triggers dependent effects after an edit re-derives the elements.
+export function useTimelineGeometry({
+ viewportWidth,
+ effectiveDuration,
+ zoomMode,
+ manualZoomPercent,
+ ppsRef,
+ fitPpsRef,
+ draggedClip,
+ resizingClip,
+ expandedElements,
+ isDragging,
+ scrollRef,
+ lastScrollLeftRef,
+}: UseTimelineGeometryInput) {
+ // Fit pps maps at least MIN_TIMELINE_EXTENT_S onto the viewport, so short
+ // comps show a 60s ruler with usable empty space (see getTimelineFitPps).
+ const fitPps = getTimelineFitPps(viewportWidth, effectiveDuration);
+ const pps = getTimelinePixelsPerSecond(fitPps, zoomMode, manualZoomPercent);
+ ppsRef.current = pps;
+ const trackContentWidth = Math.max(0, effectiveDuration * pps);
+ // Drag-to-extend: while a clip is dragged, keep the rendered extent a margin
+ // past the ghost's end. Holding the pointer in the right edge zone then keeps
+ // auto-scroll stepping (scrollWidth grows with the ghost), so the timeline
+ // extends at auto-scroll pace — placing a clip farther than the timeline
+ // currently shows. Growth is bounded per frame by AUTO_SCROLL_MAX_SPEED (no
+ // fling); leaving the edge zone stops it; the extra width collapses when the
+ // drag ends (the composition itself only grows on commit, content-driven).
+ const dragGhostEndPx = draggedClip?.started
+ ? (draggedClip.previewStart + draggedClip.element.duration) * pps + DRAG_EXTEND_MARGIN_PX
+ : 0;
+ // Trim-to-extend: same mechanic for a right-edge RESIZE — the rendered extent
+ // tracks the trim preview's end so the edge auto-scroll zone always has room
+ // to keep stepping while the trim grows past the current timeline width.
+ const resizeGhostEndPx = resizingClip?.started
+ ? (resizingClip.previewStart + resizingClip.previewDuration) * pps + DRAG_EXTEND_MARGIN_PX
+ : 0;
+ // The timeline canvas always fills at least the viewport width AND the
+ // MIN_TIMELINE_EXTENT_S floor: the ruler + empty track lanes keep going into
+ // the space instead of leaving dead black — CapCut-style. Only the RENDERED
+ // extent grows; clip positions/durations are untouched.
+ const displayContentWidth = getTimelineDisplayContentWidth({
+ trackContentWidth,
+ viewportWidth,
+ pps,
+ dragGhostEndPx,
+ resizeGhostEndPx,
+ });
+ const displayDuration = pps > 0 ? displayContentWidth / pps : effectiveDuration;
+ const clipStateVersion = useMemo(
+ () =>
+ expandedElements
+ .map((el) => `${el.key ?? el.id}:${el.start}:${el.duration}:${el.track}`)
+ .join("|"),
+ [expandedElements],
+ );
+ const zoomModeRef = useRef(zoomMode);
+ zoomModeRef.current = zoomMode;
+ const manualZoomPercentRef = useRef(manualZoomPercent);
+ manualZoomPercentRef.current = manualZoomPercent;
+ fitPpsRef.current = fitPps;
+
+ // Restore the horizontal scroll offset after an edit re-derives the elements
+ // (clipStateVersion changes) so the reload doesn't jump the view. Only in manual
+ // (pinned) mode — fit mode hides the x-scrollbar (scrollLeft is always 0) — and
+ // never mid-drag (auto-scroll owns the offset then). rAF waits for the new layout
+ // so the clamp reads the post-resync scrollWidth. zoomMode is a legitimate dep:
+ // re-running on a mode flip is a no-op thanks to the guard.
+ useEffect(() => {
+ if (zoomMode !== "manual" || isDragging.current) return;
+ const el = scrollRef.current;
+ const target = lastScrollLeftRef.current;
+ if (!el || target <= 0) return;
+ const raf = requestAnimationFrame(() => {
+ const max = Math.max(0, el.scrollWidth - el.clientWidth);
+ const next = Math.min(target, max);
+ if (Math.abs(el.scrollLeft - next) > 0.5) el.scrollLeft = next;
+ });
+ return () => cancelAnimationFrame(raf);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [clipStateVersion, zoomMode]);
+ // Publish the live scale so edit handlers OUTSIDE <Timeline> (the keyboard-delete
+ // path) can pin the zoom via pinTimelineZoomToCurrent without threading geometry.
+ // In a useEffect (not the render body) so React-18 concurrent replay — Suspense
+ // retry, transitions, StrictMode double-invoke — can't double-publish. The write is
+ // idempotent (same pps/fitPps → same fields), so this is behavior-preserving; the
+ // effect placement is just the strictly-correct shape.
+ useEffect(() => {
+ usePlayerStore.getState().setTimelineScale(pps, fitPps);
+ }, [pps, fitPps]);
+
+ return {
+ pps,
+ fitPps,
+ displayContentWidth,
+ displayDuration,
+ clipStateVersion,
+ zoomModeRef,
+ manualZoomPercentRef,
+ };
+}
diff --git a/packages/studio/src/player/components/useTimelineMarqueeSelection.test.tsx b/packages/studio/src/player/components/useTimelineMarqueeSelection.test.tsx
deleted file mode 100644
index 525be9560a..0000000000
--- a/packages/studio/src/player/components/useTimelineMarqueeSelection.test.tsx
+++ /dev/null
@@ -1,231 +0,0 @@
-// @vitest-environment happy-dom
-
-import React, { act } from "react";
-import { createRoot } from "react-dom/client";
-import { afterEach, describe, expect, it } from "vitest";
-import type { TimelineElement } from "../store/playerStore";
-import { usePlayerStore } from "../store/playerStore";
-import { GUTTER, RULER_H, TRACK_H } from "./timelineLayout";
-import type { StackingTimelineLayer } from "./timelineTrackOrder";
-import { useTimelineMarqueeSelection } from "./useTimelineMarqueeSelection";
-
-(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-
-function element(id: string, start: number, duration: number, track: number): TimelineElement {
- return { id, tag: "div", start, duration, track };
-}
-
-function layer(id: string, elements: TimelineElement[]): StackingTimelineLayer {
- return {
- id,
- kind: "visual",
- contextKey: "",
- zIndex: 0,
- placementTrack: elements[0]?.track ?? 0,
- elements,
- };
-}
-
-function pointerEvent(type: string, init: MouseEventInit & { pointerId?: number }) {
- const event = new MouseEvent(type, { bubbles: true, cancelable: true, ...init });
- Object.defineProperty(event, "pointerId", { value: init.pointerId ?? 1 });
- return event;
-}
-
-function dispatchPointer(
- target: HTMLElement,
- type: "pointerdown" | "pointermove" | "pointerup",
- point: { x: number; y: number },
-) {
- target.dispatchEvent(pointerEvent(type, { button: 0, clientX: point.x, clientY: point.y }));
-}
-
-function dragMarquee(
- harness: ReturnType<typeof renderMarqueeHarness>,
- start: { x: number; y: number },
- end: { x: number; y: number },
- downTarget: HTMLElement = harness.scroll,
-) {
- dispatchPointer(downTarget, "pointerdown", start);
- dispatchPointer(harness.scroll, "pointermove", end);
- dispatchPointer(harness.scroll, "pointerup", end);
-}
-
-function renderMarqueeHarness(layers: StackingTimelineLayer[]) {
- const host = document.createElement("div");
- document.body.append(host);
- const layerOrder = layers.map((item) => item.id);
- const setShowPopover = () => {};
- const setRangeSelection = () => {};
- const seekedX: number[] = [];
-
- function Harness() {
- const scrollRef = React.useRef<HTMLDivElement | null>(null);
- const hook = useTimelineMarqueeSelection({
- scrollRef,
- ppsRef: { current: 100 },
- trackOrderRef: { current: layerOrder },
- timelineLayersRef: { current: layers },
- setShowPopover,
- setRangeSelectionRef: { current: setRangeSelection },
- seekFromX: (clientX: number) => seekedX.push(clientX),
- });
- return (
- <div
- ref={scrollRef}
- data-scroll="true"
- onPointerDown={(event) => {
- hook.handlePointerDown(event);
- }}
- onPointerMove={(event) => {
- hook.handlePointerMove(event);
- }}
- onPointerUp={(event) => {
- hook.handlePointerUp(event);
- }}
- >
- <button data-clip="true">clip</button>
- {hook.marqueeRect && <span data-marquee="true" />}
- </div>
- );
- }
-
- const root = createRoot(host);
- act(() => {
- root.render(<Harness />);
- });
- const scroll = host.querySelector<HTMLElement>("[data-scroll]");
- if (!scroll) throw new Error("Expected scroll host");
- Object.defineProperty(scroll, "clientWidth", { configurable: true, value: 160 });
- Object.defineProperty(scroll, "clientHeight", { configurable: true, value: 160 });
- Object.defineProperty(scroll, "scrollWidth", { configurable: true, value: 600 });
- Object.defineProperty(scroll, "scrollHeight", { configurable: true, value: 260 });
- scroll.getBoundingClientRect = () =>
- ({
- left: 0,
- top: 0,
- right: 160,
- bottom: 160,
- width: 160,
- height: 160,
- x: 0,
- y: 0,
- toJSON: () => ({}),
- }) as DOMRect;
-
- return {
- host,
- scroll,
- root,
- seekedX,
- clip: host.querySelector<HTMLElement>("[data-clip]")!,
- unmount() {
- act(() => root.unmount());
- },
- };
-}
-
-afterEach(() => {
- document.body.innerHTML = "";
- usePlayerStore.getState().reset();
-});
-
-describe("useTimelineMarqueeSelection", () => {
- it("selects clips intersecting an empty-lane drag rectangle", () => {
- const layers = [
- layer("lane-0", [element("first", 0.5, 0.5, 0)]),
- layer("lane-1", [element("second", 2, 0.5, 1)]),
- layer("lane-2", [element("third", 0.5, 0.5, 2)]),
- ];
- const harness = renderMarqueeHarness(layers);
- const start = { x: GUTTER + 10, y: RULER_H + 4 };
- const end = { x: GUTTER + 260, y: RULER_H + TRACK_H * 2 - 2 };
-
- act(() => {
- dispatchPointer(harness.scroll, "pointerdown", start);
- dispatchPointer(harness.scroll, "pointermove", end);
- });
- expect(harness.host.querySelector("[data-marquee]")).not.toBeNull();
-
- act(() => {
- dispatchPointer(harness.scroll, "pointerup", end);
- });
-
- expect([...usePlayerStore.getState().selectedElementIds]).toEqual(["first", "second"]);
- harness.unmount();
- });
-
- it("treats a sub-threshold empty-lane drag as a clear click that also seeks", () => {
- usePlayerStore.getState().setSelection(["selected"]);
- const harness = renderMarqueeHarness([layer("lane-0", [element("selected", 0, 1, 0)])]);
-
- act(() => {
- dragMarquee(harness, { x: GUTTER + 20, y: RULER_H + 4 }, { x: GUTTER + 21, y: RULER_H + 5 });
- });
-
- expect(usePlayerStore.getState().selectedElementIds.size).toBe(0);
- expect(harness.host.querySelector("[data-marquee]")).toBeNull();
- // A sub-threshold press still scrubs the playhead to the click, like a plain lane click.
- expect(harness.seekedX).toEqual([GUTTER + 20]);
- harness.unmount();
- });
-
- it("does not start from clips or the ruler", () => {
- usePlayerStore.getState().setSelection(["kept"]);
- const harness = renderMarqueeHarness([layer("lane-0", [element("kept", 0, 1, 0)])]);
-
- act(() => {
- dragMarquee(
- harness,
- { x: GUTTER + 20, y: RULER_H + 4 },
- { x: GUTTER + 80, y: RULER_H + 40 },
- harness.clip,
- );
- dragMarquee(harness, { x: GUTTER + 20, y: RULER_H - 2 }, { x: GUTTER + 80, y: RULER_H + 40 });
- });
-
- expect([...usePlayerStore.getState().selectedElementIds]).toEqual(["kept"]);
- expect(harness.host.querySelector("[data-marquee]")).toBeNull();
- harness.unmount();
- });
-
- it("clears selection when the released marquee hits no clips", () => {
- usePlayerStore.getState().setSelection(["selected"]);
- const harness = renderMarqueeHarness([layer("lane-0", [element("selected", 4, 1, 0)])]);
-
- act(() => {
- dragMarquee(harness, { x: GUTTER + 10, y: RULER_H + 4 }, { x: GUTTER + 80, y: RULER_H + 40 });
- });
-
- expect(usePlayerStore.getState().selectedElementIds.size).toBe(0);
- harness.unmount();
- });
-
- it("uses autoscroll position when resolving the released marquee", () => {
- const originalRaf = window.requestAnimationFrame;
- const originalCancel = window.cancelAnimationFrame;
- const callbacks: FrameRequestCallback[] = [];
- window.requestAnimationFrame = ((callback: FrameRequestCallback) => {
- callbacks.push(callback);
- return callbacks.length;
- }) as typeof window.requestAnimationFrame;
- window.cancelAnimationFrame = (() => {}) as typeof window.cancelAnimationFrame;
- const harness = renderMarqueeHarness([layer("lane-0", [element("reachable", 1.28, 0.2, 0)])]);
-
- try {
- act(() => {
- dispatchPointer(harness.scroll, "pointerdown", { x: GUTTER + 10, y: RULER_H + 4 });
- dispatchPointer(harness.scroll, "pointermove", { x: 155, y: RULER_H + 40 });
- callbacks.shift()?.(0);
- dispatchPointer(harness.scroll, "pointerup", { x: 155, y: RULER_H + 40 });
- });
-
- expect(harness.scroll.scrollLeft).toBeGreaterThan(0);
- expect([...usePlayerStore.getState().selectedElementIds]).toEqual(["reachable"]);
- harness.unmount();
- } finally {
- window.requestAnimationFrame = originalRaf;
- window.cancelAnimationFrame = originalCancel;
- }
- });
-});
diff --git a/packages/studio/src/player/components/useTimelineMarqueeSelection.ts b/packages/studio/src/player/components/useTimelineMarqueeSelection.ts
deleted file mode 100644
index bab1763154..0000000000
--- a/packages/studio/src/player/components/useTimelineMarqueeSelection.ts
+++ /dev/null
@@ -1,276 +0,0 @@
-import {
- useCallback,
- useEffect,
- useRef,
- useState,
- type PointerEvent as ReactPointerEvent,
- type RefObject,
-} from "react";
-import { usePlayerStore } from "../store/playerStore";
-import {
- resolveTimelineAutoScroll,
- selectTimelineElementsInMarquee,
- type TimelineMarqueeSelectionRect,
-} from "./timelineEditing";
-import { GUTTER, RULER_H, TRACK_H } from "./timelineLayout";
-import { TIMELINE_LAYER_GROUP_HEADER_H } from "./TimelineLayerGroupHeader";
-import type { StackingTimelineLayer, TimelineLayerId } from "./timelineTrackOrder";
-
-const MARQUEE_THRESHOLD_PX = 4;
-
-export interface TimelineMarqueeOverlayRect {
- left: number;
- top: number;
- width: number;
- height: number;
-}
-
-interface ActiveMarqueeGesture {
- pointerId: number;
- anchorClientX: number;
- anchorClientY: number;
- anchorX: number;
- anchorY: number;
- lastClientX: number;
- lastClientY: number;
- started: boolean;
-}
-
-interface UseTimelineMarqueeSelectionInput {
- scrollRef: RefObject<HTMLDivElement | null>;
- ppsRef: RefObject<number>;
- trackOrderRef: RefObject<TimelineLayerId[]>;
- timelineLayersRef: RefObject<StackingTimelineLayer[]>;
- disabled?: boolean;
- setShowPopover: (show: boolean) => void;
- setRangeSelectionRef: RefObject<((sel: null) => void) | null>;
- /** Canonical playhead seek, used to keep empty-lane clicks scrubbing the playhead. */
- seekFromX: (clientX: number) => void;
-}
-
-function getCanvasPoint(scroll: HTMLDivElement, clientX: number, clientY: number) {
- const rect = scroll.getBoundingClientRect();
- return {
- x: clientX - rect.left + scroll.scrollLeft,
- y: clientY - rect.top + scroll.scrollTop,
- };
-}
-
-function getMarqueeStartPoint(
- event: ReactPointerEvent<HTMLDivElement>,
- scroll: HTMLDivElement | null,
- disabled: boolean,
-) {
- if (disabled || event.button !== 0 || event.shiftKey || !scroll) return null;
- const target = event.target as HTMLElement;
- if (target.closest("[data-clip]")) return null;
- const point = getCanvasPoint(scroll, event.clientX, event.clientY);
- if (point.x < GUTTER || point.y < RULER_H) return null;
- return point;
-}
-
-function capturePointerIfAvailable(event: ReactPointerEvent<HTMLDivElement>) {
- const currentTarget = event.currentTarget as HTMLElement;
- if (typeof currentTarget.setPointerCapture === "function") {
- currentTarget.setPointerCapture(event.pointerId);
- }
-}
-
-function buildSelectionRect(
- active: ActiveMarqueeGesture,
- scroll: HTMLDivElement,
- pps: number,
-): { overlay: TimelineMarqueeOverlayRect; selection: TimelineMarqueeSelectionRect } {
- const current = getCanvasPoint(scroll, active.lastClientX, active.lastClientY);
- const left = Math.min(active.anchorX, current.x);
- const right = Math.max(active.anchorX, current.x);
- const top = Math.min(active.anchorY, current.y);
- const bottom = Math.max(active.anchorY, current.y);
- const overlayLeft = Math.max(GUTTER, left);
- const overlayTop = Math.max(RULER_H, top);
- const overlayRight = Math.max(overlayLeft, right);
- const overlayBottom = Math.max(overlayTop, bottom);
-
- // Hit-test must use the SAME pixels-per-second the overlay is drawn at, or the
- // selected time span diverges from the visible box at low zoom (pps < 1). Guard
- // only against a non-finite/zero pps (would yield NaN/Infinity), never floor it.
- const safePps = Number.isFinite(pps) && pps > 0 ? pps : 0;
- const timeFromX = (x: number) => (safePps > 0 ? Math.max(0, (x - GUTTER) / safePps) : 0);
-
- return {
- overlay: {
- left: overlayLeft,
- top: overlayTop,
- width: overlayRight - overlayLeft,
- height: overlayBottom - overlayTop,
- },
- selection: {
- startTime: timeFromX(left),
- endTime: timeFromX(right),
- top,
- bottom,
- },
- };
-}
-
-export function useTimelineMarqueeSelection({
- scrollRef,
- ppsRef,
- trackOrderRef,
- timelineLayersRef,
- disabled = false,
- setShowPopover,
- setRangeSelectionRef,
- seekFromX,
-}: UseTimelineMarqueeSelectionInput) {
- const activeRef = useRef<ActiveMarqueeGesture | null>(null);
- const pointerRef = useRef<{ clientX: number; clientY: number } | null>(null);
- const scrollRafRef = useRef(0);
- const [marqueeRect, setMarqueeRect] = useState<TimelineMarqueeOverlayRect | null>(null);
-
- const stopAutoScroll = useCallback(() => {
- pointerRef.current = null;
- if (scrollRafRef.current) {
- cancelAnimationFrame(scrollRafRef.current);
- scrollRafRef.current = 0;
- }
- }, []);
-
- const updateMarqueeRect = useCallback(() => {
- const active = activeRef.current;
- const scroll = scrollRef.current;
- if (!active || !scroll) return null;
- const rects = buildSelectionRect(active, scroll, ppsRef.current);
- setMarqueeRect(rects.overlay);
- return rects;
- }, [ppsRef, scrollRef]);
-
- const stepAutoScroll = useCallback(() => {
- scrollRafRef.current = 0;
- const pointer = pointerRef.current;
- const scroll = scrollRef.current;
- if (!pointer || !scroll || !activeRef.current) return;
-
- const delta = resolveTimelineAutoScroll(
- scroll.getBoundingClientRect(),
- pointer.clientX,
- pointer.clientY,
- );
- if (delta.x === 0 && delta.y === 0) return;
-
- const maxScrollLeft = Math.max(0, scroll.scrollWidth - scroll.clientWidth);
- const maxScrollTop = Math.max(0, scroll.scrollHeight - scroll.clientHeight);
- const nextScrollLeft = Math.max(0, Math.min(maxScrollLeft, scroll.scrollLeft + delta.x));
- const nextScrollTop = Math.max(0, Math.min(maxScrollTop, scroll.scrollTop + delta.y));
- if (nextScrollLeft === scroll.scrollLeft && nextScrollTop === scroll.scrollTop) return;
-
- scroll.scrollLeft = nextScrollLeft;
- scroll.scrollTop = nextScrollTop;
- updateMarqueeRect();
- scrollRafRef.current = requestAnimationFrame(stepAutoScroll);
- }, [scrollRef, updateMarqueeRect]);
-
- const syncAutoScroll = useCallback(
- (clientX: number, clientY: number) => {
- pointerRef.current = { clientX, clientY };
- const scroll = scrollRef.current;
- if (!scroll) return;
- const delta = resolveTimelineAutoScroll(scroll.getBoundingClientRect(), clientX, clientY);
- if (delta.x === 0 && delta.y === 0) {
- if (scrollRafRef.current) {
- cancelAnimationFrame(scrollRafRef.current);
- scrollRafRef.current = 0;
- }
- return;
- }
- if (!scrollRafRef.current) {
- scrollRafRef.current = requestAnimationFrame(stepAutoScroll);
- }
- },
- [scrollRef, stepAutoScroll],
- );
-
- const handlePointerDown = useCallback(
- (event: ReactPointerEvent<HTMLDivElement>) => {
- const point = getMarqueeStartPoint(event, scrollRef.current, disabled);
- if (!point) return false;
- capturePointerIfAvailable(event);
- activeRef.current = {
- pointerId: event.pointerId,
- anchorClientX: event.clientX,
- anchorClientY: event.clientY,
- anchorX: point.x,
- anchorY: point.y,
- lastClientX: event.clientX,
- lastClientY: event.clientY,
- started: false,
- };
- setShowPopover(false);
- setRangeSelectionRef.current?.(null);
- return true;
- },
- [disabled, scrollRef, setRangeSelectionRef, setShowPopover],
- );
-
- const handlePointerMove = useCallback(
- (event: ReactPointerEvent<HTMLDivElement>) => {
- const active = activeRef.current;
- if (!active || active.pointerId !== event.pointerId) return false;
- active.lastClientX = event.clientX;
- active.lastClientY = event.clientY;
- const distance = Math.hypot(
- event.clientX - active.anchorClientX,
- event.clientY - active.anchorClientY,
- );
- if (!active.started && distance < MARQUEE_THRESHOLD_PX) return true;
- active.started = true;
- updateMarqueeRect();
- syncAutoScroll(event.clientX, event.clientY);
- return true;
- },
- [syncAutoScroll, updateMarqueeRect],
- );
-
- const handlePointerUp = useCallback(
- (event?: ReactPointerEvent<HTMLDivElement>) => {
- const active = activeRef.current;
- if (!active || (event && active.pointerId !== event.pointerId)) return false;
- activeRef.current = null;
- stopAutoScroll();
- setMarqueeRect(null);
-
- if (!active.started) {
- // A press that never crossed the marquee threshold is a plain empty-lane
- // click: clear the selection AND scrub the playhead, matching the seek that
- // the range/playhead handler would have run had the marquee not claimed it.
- usePlayerStore.getState().clearSelection();
- seekFromX(active.anchorClientX);
- return true;
- }
-
- const scroll = scrollRef.current;
- if (!scroll) return true;
- const rects = buildSelectionRect(active, scroll, ppsRef.current);
- const selectedIds = selectTimelineElementsInMarquee({
- rect: rects.selection,
- layers: timelineLayersRef.current,
- layerOrder: trackOrderRef.current,
- rulerHeight: RULER_H,
- trackHeight: TRACK_H,
- groupHeaderHeight: TIMELINE_LAYER_GROUP_HEADER_H,
- });
- usePlayerStore.getState().setSelection(selectedIds);
- return true;
- },
- [ppsRef, scrollRef, seekFromX, stopAutoScroll, timelineLayersRef, trackOrderRef],
- );
-
- useEffect(() => stopAutoScroll, [stopAutoScroll]);
-
- return {
- marqueeRect,
- handlePointerDown,
- handlePointerMove,
- handlePointerUp,
- };
-}
diff --git a/packages/studio/src/player/components/useTimelinePlayhead.ts b/packages/studio/src/player/components/useTimelinePlayhead.ts
index 7fd6786b07..c24203377a 100644
--- a/packages/studio/src/player/components/useTimelinePlayhead.ts
+++ b/packages/studio/src/player/components/useTimelinePlayhead.ts
@@ -1,5 +1,5 @@
import { useRef, useCallback, useEffect, useLayoutEffect } from "react";
-import { liveTime, usePlayerStore, type ZoomMode } from "../store/playerStore";
+import { liveTime, type ZoomMode } from "../store/playerStore";
import { useMountEffect } from "../../hooks/useMountEffect";
import { getPinchTimelineZoomPercent } from "./timelineZoom";
import {
@@ -117,21 +117,9 @@ export function useTimelinePlayhead({
useMountEffect(() => {
const unsub = liveTime.subscribe((t) => {
if (!playheadRef.current || durationRef.current <= 0) return;
- const playheadX = getTimelinePlayheadLeft(t, ppsRef.current);
- playheadRef.current.style.left = `${playheadX}px`;
- const scroll = scrollRef.current;
- if (
- scroll &&
- !isDragging.current &&
- usePlayerStore.getState().isPlaying &&
- shouldAutoScrollTimeline(zoomModeRef.current, scroll.scrollWidth, scroll.clientWidth)
- ) {
- const edgeMargin = scroll.clientWidth * 0.12;
- if (playheadX > scroll.scrollLeft + scroll.clientWidth - edgeMargin)
- scroll.scrollLeft = playheadX - scroll.clientWidth * 0.15;
- else if (playheadX < scroll.scrollLeft + GUTTER)
- scroll.scrollLeft = Math.max(0, playheadX - GUTTER);
- }
+ // Playback deliberately does NOT scroll the viewport to chase the playhead —
+ // the user's scroll position is theirs; the playhead may run off-screen.
+ playheadRef.current.style.left = `${getTimelinePlayheadLeft(t, ppsRef.current)}px`;
});
return unsub;
});
diff --git a/packages/studio/src/player/components/useTimelineRangeSelection.ts b/packages/studio/src/player/components/useTimelineRangeSelection.ts
index 6183057e70..ca1dc2697f 100644
--- a/packages/studio/src/player/components/useTimelineRangeSelection.ts
+++ b/packages/studio/src/player/components/useTimelineRangeSelection.ts
@@ -1,8 +1,21 @@
-import { useRef, useState, useCallback } from "react";
-import { buildClipRangeSelection, type TimelineRangeSelection } from "./timelineEditing";
+import { useRef, useState, useCallback, useEffect } from "react";
+import {
+ buildClipRangeSelection,
+ applyTimelineAutoScrollStep,
+ resolveTimelineAutoScrollLoopAction,
+ type TimelineRangeSelection,
+} from "./timelineEditing";
import type { TimelineElement } from "../store/playerStore";
-import { liveTime } from "../store/playerStore";
+import { liveTime, usePlayerStore } from "../store/playerStore";
import { GUTTER } from "./timelineLayout";
+import {
+ computeMarqueeSelection,
+ getMarqueeRect,
+ isMarqueeDrag,
+ isTimelineRulerPress,
+ type MarqueeClipInput,
+} from "./timelineMarquee";
+import type { Rect } from "../../utils/marqueeGeometry";
interface UseTimelineRangeSelectionInput {
scrollRef: React.RefObject<HTMLDivElement | null>;
@@ -15,11 +28,69 @@ interface UseTimelineRangeSelectionInput {
dragScrollRaf: React.RefObject<number>;
isDragging: React.RefObject<boolean>;
setShowPopover: (v: boolean) => void;
+ elementsRef: React.RefObject<TimelineElement[]>;
+ trackOrderRef: React.RefObject<number[]>;
+ onSelectElement?: (element: TimelineElement | null) => void;
+}
+
+interface MarqueeDragState {
+ originX: number;
+ originY: number;
+ /** Pre-drag selection, restored on Escape-cancel. */
+ baseIds: Set<string>;
+ basePrimary: string | null;
+ /** Union new hits with baseIds (shift/cmd/ctrl at pointerdown). */
+ additive: boolean;
+ /** True once the pointer travelled past the click threshold. */
+ active: boolean;
+}
+
+function snapshotSelection(): { ids: Set<string>; primary: string | null } {
+ const s = usePlayerStore.getState();
+ const ids = new Set(s.selectedElementIds);
+ if (s.selectedElementId) ids.add(s.selectedElementId);
+ return { ids, primary: s.selectedElementId };
+}
+
+function toMarqueeClips(elements: TimelineElement[]): MarqueeClipInput[] {
+ return elements.map((el) => ({
+ id: el.key ?? el.id,
+ start: el.start,
+ duration: el.duration,
+ track: el.track,
+ }));
+}
+
+/**
+ * Compute the live selection for a marquee rect and commit it to the store.
+ * Shift held mid-drag (or cmd/ctrl at pointerdown) unions the new hits with the
+ * pre-drag selection (marquee.baseIds / basePrimary).
+ */
+function commitMarqueeSelection(
+ rect: Rect,
+ additive: boolean,
+ marquee: MarqueeDragState,
+ elements: TimelineElement[],
+ trackOrder: number[],
+ pps: number,
+): void {
+ const { ids, primaryId } = computeMarqueeSelection({
+ clips: toMarqueeClips(elements),
+ trackOrder,
+ pps,
+ marquee: rect,
+ baseSelection: additive ? marquee.baseIds : undefined,
+ });
+ const store = usePlayerStore.getState();
+ // Primary FIRST: setSelectedElementId collapses the multi-select set, so the set
+ // must be written after it or the marquee selection would be wiped every frame.
+ store.setSelectedElementId(primaryId ?? (additive ? marquee.basePrimary : null));
+ store.setSelectedElementIds(ids);
}
export function useTimelineRangeSelection({
scrollRef,
- ppsRef: _ppsRef,
+ ppsRef,
effectiveDuration: _effectiveDuration,
pps,
onSeek: _onSeek,
@@ -28,9 +99,15 @@ export function useTimelineRangeSelection({
dragScrollRaf,
isDragging,
setShowPopover,
+ elementsRef,
+ trackOrderRef,
+ onSelectElement,
}: UseTimelineRangeSelectionInput) {
const isRangeSelecting = useRef(false);
const rangeAnchorTime = useRef(0);
+ // Reactive mirror of the scrub gesture (isDragging is a ref, so it can't drive
+ // rendering). Drives the playhead head's filled-vs-hollow state.
+ const [isScrubbing, setIsScrubbing] = useState(false);
const [rangeSelection, setRangeSelection] = useState<TimelineRangeSelection | null>(null);
const shiftClickClipRef = useRef<{
element: TimelineElement;
@@ -41,55 +118,174 @@ export function useTimelineRangeSelection({
const seekRafRef = useRef(0);
const pendingClientXRef = useRef(0);
+ // Marquee (rubber-band) multi-select on the empty timeline body.
+ const marqueeRef = useRef<MarqueeDragState | null>(null);
+ const [marqueeRect, setMarqueeRect] = useState<Rect | null>(null);
+ // Edge auto-scroll during a marquee drag: last pointer position (client-space)
+ // + shift flag, re-applied each RAF frame while the view scrolls under a
+ // stationary pointer, so the marquee can extend past the visible area.
+ const marqueePointerRef = useRef<{ clientX: number; clientY: number; shiftKey: boolean } | null>(
+ null,
+ );
+ const marqueeScrollRaf = useRef(0);
+
+ /** Pointer position → canvas/content coordinates (same space as clip rects). */
+ const toContentPoint = useCallback(
+ (clientX: number, clientY: number): { x: number; y: number } | null => {
+ const el = scrollRef.current;
+ if (!el) return null;
+ const rect = el.getBoundingClientRect();
+ return {
+ x: clientX - rect.left + el.scrollLeft,
+ y: clientY - rect.top + el.scrollTop,
+ };
+ },
+ [scrollRef],
+ );
+
+ // Recompute the marquee rect + live selection for a client-space pointer.
+ // Content-space (folds in scrollLeft/scrollTop), so re-running it after the
+ // view scrolls naturally extends the rect toward the newly revealed area.
+ // Shared by the pointermove handler and the edge auto-scroll stepper.
+ const applyMarqueeAtClient = useCallback(
+ (clientX: number, clientY: number, shiftKey: boolean) => {
+ const marquee = marqueeRef.current;
+ if (!marquee) return;
+ const point = toContentPoint(clientX, clientY);
+ if (!point) return;
+ if (!marquee.active && !isMarqueeDrag(marquee.originX, marquee.originY, point.x, point.y)) {
+ return;
+ }
+ marquee.active = true;
+ const rect = getMarqueeRect(marquee.originX, marquee.originY, point.x, point.y);
+ setMarqueeRect(rect);
+ // Live selection: every clip the box currently covers. Shift held
+ // mid-drag (or cmd/ctrl at pointerdown) adds to the prior selection.
+ const additive = marquee.additive || shiftKey;
+ commitMarqueeSelection(
+ rect,
+ additive,
+ marquee,
+ elementsRef.current ?? [],
+ trackOrderRef.current ?? [],
+ ppsRef.current,
+ );
+ },
+ [toContentPoint, elementsRef, trackOrderRef, ppsRef],
+ );
+
+ const stopMarqueeAutoScroll = useCallback(() => {
+ marqueePointerRef.current = null;
+ if (marqueeScrollRaf.current) {
+ cancelAnimationFrame(marqueeScrollRaf.current);
+ marqueeScrollRaf.current = 0;
+ }
+ }, []);
+
+ // Edge auto-scroll while marquee-dragging: mirrors stepClipDragAutoScroll —
+ // scroll the container toward the edge zone the pointer is in, then re-run the
+ // marquee at the (unchanged) client pointer so the rect + selection extend
+ // under the scroll delta. Self-perpetuating RAF until the pointer leaves the
+ // edge zones or the gesture ends.
+ const stepMarqueeAutoScroll = useCallback(() => {
+ marqueeScrollRaf.current = 0;
+ const marquee = marqueeRef.current;
+ const pointer = marqueePointerRef.current;
+ const scroll = scrollRef.current;
+ if (!marquee || !pointer || !scroll) return;
+ if (!applyTimelineAutoScrollStep(scroll, pointer.clientX, pointer.clientY)) return;
+
+ // Re-run at the SAME client point: toContentPoint folds in the new scroll, so
+ // the marquee's moving corner tracks the revealed content.
+ applyMarqueeAtClient(pointer.clientX, pointer.clientY, pointer.shiftKey);
+ marqueeScrollRaf.current = requestAnimationFrame(stepMarqueeAutoScroll);
+ }, [scrollRef, applyMarqueeAtClient]);
+
+ const syncMarqueeAutoScroll = useCallback(
+ (clientX: number, clientY: number, shiftKey: boolean) => {
+ marqueePointerRef.current = { clientX, clientY, shiftKey };
+ const action = resolveTimelineAutoScrollLoopAction(
+ scrollRef.current,
+ clientX,
+ clientY,
+ marqueeScrollRaf.current !== 0,
+ );
+ if (action === "stop") {
+ cancelAnimationFrame(marqueeScrollRaf.current);
+ marqueeScrollRaf.current = 0;
+ } else if (action === "start") {
+ marqueeScrollRaf.current = requestAnimationFrame(stepMarqueeAutoScroll);
+ }
+ },
+ [scrollRef, stepMarqueeAutoScroll],
+ );
+
+ // Shift-press → start a time-range selection anchored at the pressed x.
+ const beginRangeSelection = useCallback(
+ (e: React.PointerEvent) => {
+ (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
+ isRangeSelecting.current = true;
+ setShowPopover(false);
+ const rect = scrollRef.current?.getBoundingClientRect();
+ if (rect) {
+ const x = e.clientX - rect.left + (scrollRef.current?.scrollLeft ?? 0) - GUTTER;
+ const time = Math.max(0, x / pps);
+ rangeAnchorTime.current = time;
+ setRangeSelection({ start: time, end: time, anchorX: e.clientX, anchorY: e.clientY });
+ }
+ },
+ [scrollRef, pps, setShowPopover],
+ );
+
const handlePointerDown = useCallback(
(e: React.PointerEvent) => {
if (e.button !== 0) return;
if (e.shiftKey) {
- (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
- isRangeSelecting.current = true;
- setShowPopover(false);
- const rect = scrollRef.current?.getBoundingClientRect();
- if (rect) {
- const x = e.clientX - rect.left + (scrollRef.current?.scrollLeft ?? 0) - GUTTER;
- const time = Math.max(0, x / pps);
- rangeAnchorTime.current = time;
- setRangeSelection({ start: time, end: time, anchorX: e.clientX, anchorY: e.clientY });
- }
+ beginRangeSelection(e);
return;
}
shiftClickClipRef.current = null;
if ((e.target as HTMLElement).closest("[data-clip]")) return;
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
- isDragging.current = true;
setRangeSelection(null);
setShowPopover(false);
- seekFromX(e.clientX);
+ const point = toContentPoint(e.clientX, e.clientY);
+ // Ruler press → scrub the playhead (the standard scrub surface). The
+ // ruler is sticky, so this decision uses VIEWPORT-space y — content-space
+ // y (which folds in scrollTop) breaks once the body is scrolled down and
+ // the stuck ruler visually overlays scrolled-away track rows.
+ const scrollRect = scrollRef.current?.getBoundingClientRect();
+ if (!point || !scrollRect || isTimelineRulerPress(e.clientY, scrollRect.top)) {
+ isDragging.current = true;
+ setIsScrubbing(true);
+ seekFromX(e.clientX);
+ return;
+ }
+ // Empty body press → pending marquee. A plain click (no drag past the
+ // threshold) deselects on pointerup; a drag draws the marquee. Never scrubs.
+ const base = snapshotSelection();
+ marqueeRef.current = {
+ originX: point.x,
+ originY: point.y,
+ baseIds: base.ids,
+ basePrimary: base.primary,
+ additive: e.metaKey || e.ctrlKey,
+ active: false,
+ };
},
- [seekFromX, pps, scrollRef, isDragging, setShowPopover],
+ [beginRangeSelection, seekFromX, scrollRef, isDragging, setShowPopover, toContentPoint],
);
- const handlePointerMove = useCallback(
- (e: React.PointerEvent) => {
- if (isRangeSelecting.current) {
- const rect = scrollRef.current?.getBoundingClientRect();
- if (rect) {
- const x = e.clientX - rect.left + (scrollRef.current?.scrollLeft ?? 0) - GUTTER;
- setRangeSelection((prev) =>
- prev
- ? { ...prev, end: Math.max(0, x / pps), anchorX: e.clientX, anchorY: e.clientY }
- : null,
- );
- }
- return;
- }
- if (!isDragging.current) return;
- pendingClientXRef.current = e.clientX;
+ // Scrub-drag update: live playhead feedback (liveTime) + RAF-throttled seek.
+ const updateScrubDrag = useCallback(
+ (clientX: number) => {
+ pendingClientXRef.current = clientX;
// Update the playhead visual immediately via liveTime for smooth feedback,
// then RAF-throttle the full seek (adapter + React state sync).
const el = scrollRef.current;
if (el) {
const rect = el.getBoundingClientRect();
- const x = e.clientX - rect.left + el.scrollLeft - GUTTER;
+ const x = clientX - rect.left + el.scrollLeft - GUTTER;
if (x >= 0) {
const dur = el.scrollWidth / pps;
liveTime.notify(Math.max(0, Math.min(dur, x / pps)));
@@ -105,40 +301,135 @@ export function useTimelineRangeSelection({
});
}
},
- [seekFromX, autoScrollDuringDrag, pps, scrollRef, isDragging],
+ [scrollRef, pps, seekFromX, autoScrollDuringDrag, isDragging],
+ );
+
+ const handlePointerMove = useCallback(
+ (e: React.PointerEvent) => {
+ if (isRangeSelecting.current) {
+ const rect = scrollRef.current?.getBoundingClientRect();
+ if (rect) {
+ const x = e.clientX - rect.left + (scrollRef.current?.scrollLeft ?? 0) - GUTTER;
+ setRangeSelection((prev) =>
+ prev
+ ? { ...prev, end: Math.max(0, x / pps), anchorX: e.clientX, anchorY: e.clientY }
+ : null,
+ );
+ }
+ return;
+ }
+ const marquee = marqueeRef.current;
+ if (marquee) {
+ applyMarqueeAtClient(e.clientX, e.clientY, e.shiftKey);
+ // Edge auto-scroll: once the drag is live, scroll when the pointer nears
+ // a viewport edge so the marquee can extend past the visible area.
+ if (marquee.active) syncMarqueeAutoScroll(e.clientX, e.clientY, e.shiftKey);
+ return;
+ }
+ if (!isDragging.current) return;
+ updateScrubDrag(e.clientX);
+ },
+ [pps, scrollRef, isDragging, applyMarqueeAtClient, syncMarqueeAutoScroll, updateScrubDrag],
+ );
+
+ // Release of a shift time-range gesture: keep a real range (or a shift-click
+ // clip range), otherwise clear it.
+ const finishRangeSelection = useCallback(() => {
+ isRangeSelecting.current = false;
+ const pendingShiftClick = shiftClickClipRef.current;
+ shiftClickClipRef.current = null;
+ setRangeSelection((prev) => {
+ if (prev && pendingShiftClick && Math.abs(prev.end - prev.start) <= 0.2) {
+ setShowPopover(true);
+ return buildClipRangeSelection(pendingShiftClick.element, pendingShiftClick);
+ }
+ if (prev && Math.abs(prev.end - prev.start) > 0.2) {
+ setShowPopover(true);
+ return prev;
+ }
+ return null;
+ });
+ }, [setShowPopover]);
+
+ // Release of a marquee gesture: plain click deselects; a real drag keeps the
+ // live selection and notifies the primary element.
+ const finishMarquee = useCallback(
+ (marquee: MarqueeDragState) => {
+ marqueeRef.current = null;
+ stopMarqueeAutoScroll();
+ setMarqueeRect(null);
+ const store = usePlayerStore.getState();
+ if (!marquee.active) {
+ // Plain click on empty body (click-away): deselect everything.
+ store.setSelectedElementId(null);
+ store.clearSelectedElementIds();
+ onSelectElement?.(null);
+ return;
+ }
+ const primaryKey = store.selectedElementId;
+ const primary =
+ (elementsRef.current ?? []).find((el) => (el.key ?? el.id) === primaryKey) ?? null;
+ onSelectElement?.(primary);
+ },
+ [stopMarqueeAutoScroll, elementsRef, onSelectElement],
);
const handlePointerUp = useCallback(() => {
if (isRangeSelecting.current) {
- isRangeSelecting.current = false;
- const pendingShiftClick = shiftClickClipRef.current;
- shiftClickClipRef.current = null;
- setRangeSelection((prev) => {
- if (prev && pendingShiftClick && Math.abs(prev.end - prev.start) <= 0.2) {
- setShowPopover(true);
- return buildClipRangeSelection(pendingShiftClick.element, pendingShiftClick);
- }
- if (prev && Math.abs(prev.end - prev.start) > 0.2) {
- setShowPopover(true);
- return prev;
- }
- return null;
- });
+ finishRangeSelection();
+ return;
+ }
+ const marquee = marqueeRef.current;
+ if (marquee) {
+ finishMarquee(marquee);
return;
}
+ if (!isDragging.current) return;
if (seekRafRef.current) {
cancelAnimationFrame(seekRafRef.current);
seekRafRef.current = 0;
}
seekFromX(pendingClientXRef.current);
isDragging.current = false;
+ setIsScrubbing(false);
cancelAnimationFrame(dragScrollRaf.current);
- }, [isDragging, dragScrollRaf, setShowPopover, seekFromX]);
+ }, [isDragging, dragScrollRaf, seekFromX, finishRangeSelection, finishMarquee]);
+
+ // Escape: cancel an in-flight marquee (restores the pre-drag selection);
+ // otherwise clear any lingering multi-selection.
+ useEffect(() => {
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.key !== "Escape") return;
+ const store = usePlayerStore.getState();
+ const marquee = marqueeRef.current;
+ if (marquee) {
+ marqueeRef.current = null;
+ stopMarqueeAutoScroll();
+ setMarqueeRect(null);
+ if (marquee.active) {
+ // Primary FIRST (see commitMarqueeSelection): it collapses the set, so
+ // restore the pre-drag primary before repopulating the base ids.
+ store.setSelectedElementId(marquee.basePrimary);
+ store.setSelectedElementIds(marquee.baseIds);
+ }
+ return;
+ }
+ // Escape with no marquee clears the whole selection — primary AND set.
+ // setSelectedElementId(null) also collapses the multi-select set.
+ if (store.selectedElementId || store.selectedElementIds.size > 0) {
+ store.setSelectedElementId(null);
+ }
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, [stopMarqueeAutoScroll]);
return {
rangeSelection,
setRangeSelection,
shiftClickClipRef,
+ marqueeRect,
+ isScrubbing,
handlePointerDown,
handlePointerMove,
handlePointerUp,
diff --git a/packages/studio/src/player/components/useTimelineStackingSync.test.tsx b/packages/studio/src/player/components/useTimelineStackingSync.test.tsx
new file mode 100644
index 0000000000..7428ebef70
--- /dev/null
+++ b/packages/studio/src/player/components/useTimelineStackingSync.test.tsx
@@ -0,0 +1,67 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { describe, expect, it, vi } from "vitest";
+import type { TimelineElement } from "../store/playerStore";
+import { mountReactHarness } from "../../hooks/domSelectionTestHarness";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ actions: null as null | {
+ previewIframeRef: { current: HTMLIFrameElement | null };
+ handleDomZIndexReorderCommit: ReturnType<typeof vi.fn>;
+ },
+}));
+
+vi.mock("../../contexts/DomEditContext", () => ({
+ useDomEditActionsContextOptional: () => mocks.actions,
+}));
+vi.mock("../../contexts/StudioContext", () => ({
+ useStudioShellContextOptional: () => ({ activeCompPath: "nested.html" }),
+}));
+
+import { useTimelineStackingSync } from "./useTimelineStackingSync";
+
+describe("useTimelineStackingSync", () => {
+ it("forwards resolved entries and the lane gesture coalesce key", async () => {
+ const iframe = document.createElement("iframe");
+ document.body.appendChild(iframe);
+ const node = iframe.contentDocument!.createElement("div");
+ node.setAttribute("data-hf-id", "hf-a");
+ iframe.contentDocument!.body.appendChild(node);
+ const commit = vi.fn().mockResolvedValue(undefined);
+ mocks.actions = { previewIframeRef: { current: iframe }, handleDomZIndexReorderCommit: commit };
+ const element: TimelineElement = {
+ id: "a",
+ key: "a",
+ hfId: "hf-a",
+ tag: "div",
+ start: 0,
+ duration: 2,
+ track: 0,
+ sourceFile: "nested.html",
+ };
+ let apply: ((patches: Array<{ key: string; zIndex: number }>, key?: string) => unknown) | null =
+ null;
+ function Harness() {
+ apply = useTimelineStackingSync({
+ expandedElementsRef: { current: [element] },
+ }).applyStackingPatches;
+ return null;
+ }
+ const root = mountReactHarness(<Harness />);
+
+ await act(async () => {
+ await apply!([{ key: "a", zIndex: 8 }], "clip-lane-move:7");
+ });
+
+ expect(commit).toHaveBeenCalledWith(
+ [expect.objectContaining({ element: node, zIndex: 8, sourceFile: "nested.html" })],
+ "clip-lane-move:7",
+ );
+ act(() => root.unmount());
+ mocks.actions = null;
+ iframe.remove();
+ });
+});
diff --git a/packages/studio/src/player/components/useTimelineStackingSync.ts b/packages/studio/src/player/components/useTimelineStackingSync.ts
new file mode 100644
index 0000000000..65d7c827e4
--- /dev/null
+++ b/packages/studio/src/player/components/useTimelineStackingSync.ts
@@ -0,0 +1,83 @@
+import { useCallback, type RefObject } from "react";
+import type { TimelineElement } from "../store/playerStore";
+import { useDomEditActionsContextOptional } from "../../contexts/DomEditContext";
+import { useStudioShellContextOptional } from "../../contexts/StudioContext";
+import { findElementForSelection } from "../../components/editor/domEditingElement";
+import { readEffectiveZIndex } from "../../components/editor/canvasContextMenuZOrder";
+import type { StackingPatch } from "./timelineStackingSync";
+
+interface UseTimelineStackingSyncInput {
+ expandedElementsRef: RefObject<TimelineElement[]>;
+}
+
+// Lane ↔ stacking unification (research/STAGE3-NEEDED-WIRING.md). Provision the
+// two deps commitDraggedClipMove accepts so a lane-change drag also patches the
+// edited clip's z-index. Both read the SAME preview iframe + z-order persist path
+// the canvas right-click menu / LayersPanel use, so a timeline lane move and a
+// menu z-edit produce one shared inline-style commit shape. Optional contexts:
+// outside the NLE (standalone <Timeline>) these are null ⇒ deps undefined ⇒ the
+// commit's z-sync is a no-op (backward compatible).
+export function useTimelineStackingSync({ expandedElementsRef }: UseTimelineStackingSyncInput) {
+ const domEditActions = useDomEditActionsContextOptional();
+ const shell = useStudioShellContextOptional();
+ const zSyncPreviewIframeRef = domEditActions?.previewIframeRef ?? null;
+ const handleDomZIndexReorderCommit = domEditActions?.handleDomZIndexReorderCommit;
+ const zSyncActiveCompPath = shell?.activeCompPath ?? null;
+
+ // Resolve a TimelineElement to its live iframe HTMLElement via the same
+ // hfId ?? id ?? selector[selectorIndex] resolver the timeline's DOM patches use.
+ const resolveIframeElement = useCallback(
+ (el: TimelineElement): HTMLElement | null => {
+ const doc = zSyncPreviewIframeRef?.current?.contentDocument ?? null;
+ if (!doc) return null;
+ return findElementForSelection(
+ doc,
+ {
+ hfId: el.hfId,
+ id: el.domId ?? el.id,
+ selector: el.selector,
+ selectorIndex: el.selectorIndex,
+ sourceFile: el.sourceFile,
+ },
+ zSyncActiveCompPath,
+ );
+ },
+ [zSyncPreviewIframeRef, zSyncActiveCompPath],
+ );
+
+ const readClipZIndex = useCallback(
+ (el: TimelineElement): number => {
+ const node = resolveIframeElement(el);
+ return node ? readEffectiveZIndex(node) : 0;
+ },
+ [resolveIframeElement],
+ );
+
+ const applyStackingPatches = useCallback(
+ (patches: StackingPatch[], coalesceKey?: string) => {
+ if (!handleDomZIndexReorderCommit) return;
+ const entries = patches.flatMap((p) => {
+ const el = expandedElementsRef.current.find((e) => (e.key ?? e.id) === p.key);
+ const node = el && resolveIframeElement(el);
+ if (!el || !node) return [];
+ return [
+ {
+ element: node,
+ zIndex: p.zIndex,
+ id: el.domId ?? el.id,
+ selector: el.selector,
+ selectorIndex: el.selectorIndex,
+ sourceFile: el.sourceFile ?? zSyncActiveCompPath ?? "index.html",
+ },
+ ];
+ });
+ if (entries.length) return handleDomZIndexReorderCommit(entries, coalesceKey);
+ },
+ [handleDomZIndexReorderCommit, resolveIframeElement, zSyncActiveCompPath, expandedElementsRef],
+ );
+
+ // Engage the z-sync only when the persist path is present (inside the NLE).
+ const zSyncEnabled = Boolean(handleDomZIndexReorderCommit && zSyncPreviewIframeRef);
+
+ return { readClipZIndex, applyStackingPatches, zSyncEnabled };
+}
diff --git a/packages/studio/src/player/hooks/useExpandedTimelineElements.ts b/packages/studio/src/player/hooks/useExpandedTimelineElements.ts
index 473fc88d82..8ddbb21503 100644
--- a/packages/studio/src/player/hooks/useExpandedTimelineElements.ts
+++ b/packages/studio/src/player/hooks/useExpandedTimelineElements.ts
@@ -192,12 +192,9 @@ function domSiblingClips(
start: host.start,
duration: host.duration,
track: host.track,
- zIndex: 0,
- stackingContextId: host.stackingContextId ?? host.domId ?? host.id ?? null,
kind: "element",
tagName: null,
compositionId: null,
- compositionAncestors: host.compositionAncestors ?? [],
parentCompositionId: host.id ?? null,
compositionSrc: host.compositionSrc ?? null,
assetUrl: null,
diff --git a/packages/studio/src/player/hooks/usePlaybackKeyboard.ts b/packages/studio/src/player/hooks/usePlaybackKeyboard.ts
index cd13c869eb..6e7ee1098b 100644
--- a/packages/studio/src/player/hooks/usePlaybackKeyboard.ts
+++ b/packages/studio/src/player/hooks/usePlaybackKeyboard.ts
@@ -9,6 +9,7 @@
import { useRef, useCallback } from "react";
import { useCaptionStore } from "../../captions/store";
import { shouldIgnorePlaybackShortcutEvent, SHUTTLE_SPEEDS } from "../lib/playbackShortcuts";
+import { canvasNudgeKeysClaimed } from "../../utils/canvasNudgeGate";
import { usePlayerStore } from "../store/playerStore";
import { stepFrameTime, STUDIO_PREVIEW_FPS } from "../lib/time";
import type { PlaybackAdapter } from "../lib/playbackTypes";
@@ -97,6 +98,10 @@ export function usePlaybackKeyboard({
togglePlay();
return;
}
+ // A nudgeable canvas selection owns the arrow keys (DomEditOverlay moves
+ // the element); frame-stepping would double-handle the same keystroke.
+ const arrowStep = e.code === "ArrowLeft" || e.code === "ArrowRight";
+ if (arrowStep && canvasNudgeKeysClaimed()) return;
if (e.code === "ArrowLeft") {
e.preventDefault();
stepFrames(e.shiftKey ? -10 : -1);
diff --git a/packages/studio/src/player/hooks/useTimelinePlayer.ts b/packages/studio/src/player/hooks/useTimelinePlayer.ts
index 70414c5771..4ca1b452c3 100644
--- a/packages/studio/src/player/hooks/useTimelinePlayer.ts
+++ b/packages/studio/src/player/hooks/useTimelinePlayer.ts
@@ -3,6 +3,7 @@ import { usePlayerStore, liveTime, type TimelineElement } from "../store/playerS
import { useMountEffect } from "../../hooks/useMountEffect";
import { usePlaybackKeyboard } from "./usePlaybackKeyboard";
import { useTimelineSyncCallbacks } from "./useTimelineSyncCallbacks";
+import { useTimelinePlayerLoop } from "./useTimelinePlayerLoop";
export type { ClipManifestClip } from "../lib/playbackTypes";
export { createStaticSeekPlaybackAdapter } from "../lib/playbackAdapter";
@@ -15,7 +16,6 @@ export {
parseTimelineFromDOM,
readTimelineDurationFromDocument,
resolveStandaloneRootCompositionSrc,
- resolveIframe,
} from "../lib/timelineDOM";
export {
shouldIgnorePlaybackShortcutEvent,
@@ -36,6 +36,7 @@ import {
mergeTimelineElementsPreservingDowngrades,
parseTimelineFromDOM,
} from "../lib/timelineDOM";
+import { normalizeToZones } from "../components/timelineZones";
import {
setPreviewMediaMuted,
setPreviewPlaybackRate,
@@ -90,12 +91,17 @@ export function useTimelinePlayer() {
// applyCachedSourceDurations re-applies the cached probe duration: re-derived
// elements (e.g. after a clip move) can arrive without sourceDuration, which
// otherwise makes trimmed waveforms lose their window.
- const mergedElements = applyCachedSourceDurations(
- mergeTimelineElementsPreservingDowngrades(
- state.elements,
- elements,
- state.duration,
- resolvedDuration,
+ // Enforced CapCut zoning (overlay → main → audio): normalize track indices
+ // on every discovery. Idempotent — already-zoned input is returned as-is, so
+ // drops persist zoned indices and reloads re-zone to the same (no drift).
+ const mergedElements = normalizeToZones(
+ applyCachedSourceDurations(
+ mergeTimelineElementsPreservingDowngrades(
+ state.elements,
+ elements,
+ state.duration,
+ resolvedDuration,
+ ),
),
);
@@ -207,49 +213,14 @@ export function useTimelinePlayer() {
}
}, []);
- const stopReverseLoop = useCallback(() => {
- cancelAnimationFrame(reverseRafRef.current);
- }, []);
-
- const startRAFLoop = useCallback(() => {
- // fallow-ignore-next-line complexity
- const tick = () => {
- const adapter = getAdapter();
- if (adapter) {
- const rawTime = adapter.getTime();
- const dur = adapter.getDuration();
- const time = dur > 0 ? Math.min(rawTime, dur) : rawTime;
- liveTime.notify(time); // direct DOM updates, no React re-render
- const { inPoint, outPoint } = usePlayerStore.getState();
- const rawLoopEnd = outPoint !== null ? Math.min(outPoint, dur) : dur;
- const rawLoopStart = inPoint !== null ? inPoint : 0;
- const loopEnd = rawLoopStart < rawLoopEnd ? rawLoopEnd : dur;
- const loopStart = rawLoopStart < rawLoopEnd ? rawLoopStart : 0;
- if (time >= loopEnd) {
- if (usePlayerStore.getState().loopEnabled && dur > 0) {
- // keepPlaying skips the adapter's implicit pause; play() below is then a no-op.
- adapter.seek(loopStart, { keepPlaying: true });
- liveTime.notify(loopStart);
- adapter.play();
- setIsPlaying(true);
- rafRef.current = requestAnimationFrame(tick);
- return;
- }
- if (adapter.isPlaying()) adapter.pause();
- setCurrentTime(time); // sync Zustand once at end
- setIsPlaying(false);
- cancelAnimationFrame(rafRef.current);
- return;
- }
- }
- rafRef.current = requestAnimationFrame(tick);
- };
- rafRef.current = requestAnimationFrame(tick);
- }, [getAdapter, setCurrentTime, setIsPlaying]);
+ const { startRAFLoop, stopRAFLoop, stopReverseLoop } = useTimelinePlayerLoop({
+ rafRef,
+ reverseRafRef,
+ getAdapter,
+ setCurrentTime,
+ setIsPlaying,
+ });
- const stopRAFLoop = useCallback(() => {
- cancelAnimationFrame(rafRef.current);
- }, []);
const applyPlaybackRate = useCallback((rate: number) => {
const iframe = iframeRef.current;
if (!iframe) return;
@@ -463,10 +434,24 @@ export function useTimelinePlayer() {
applyPreviewAudioState,
});
const saveSeekPosition = useCallback(() => {
- const adapter = getAdapter();
- pendingSeekRef.current = adapter
- ? adapter.getTime()
- : (usePlayerStore.getState().currentTime ?? 0);
+ // Never DEGRADE the saved position. Overlapping reloads (e.g. an external
+ // file drop = upload reload + insert reload back-to-back) call this while
+ // the iframe from the FIRST reload is mid-teardown: getAdapter() can still
+ // return that dying document's adapter, whose getTime() reads 0 — and the
+ // store's currentTime can lag the visual playhead. Overwriting the
+ // still-unconsumed pendingSeek with either value is exactly how the
+ // playhead used to end up at 0 after a Finder drop (verified live via a
+ // currentTime write-trace). So: while a refresh is already in flight and a
+ // save exists, keep it; otherwise trust the live adapter, then the store.
+ const refreshInFlight = isRefreshingRef.current && pendingSeekRef.current != null;
+ if (!refreshInFlight) {
+ const adapter = getAdapter();
+ if (adapter) {
+ pendingSeekRef.current = adapter.getTime();
+ } else if (pendingSeekRef.current == null) {
+ pendingSeekRef.current = usePlayerStore.getState().currentTime ?? 0;
+ }
+ }
isRefreshingRef.current = true;
stopRAFLoop();
stopReverseLoop();
@@ -476,6 +461,16 @@ export function useTimelinePlayer() {
const iframe = iframeRef.current;
if (!iframe) return;
saveSeekPosition();
+ // Hide the iframe across the full reload so the user never sees the reloading
+ // document's RAW DOM (every clip stacked and visible) in the window between the
+ // new document parsing and the runtime initializing + seeking. initializeAdapter
+ // reveals it again right after its restore seek renders the correct frame.
+ // Tradeoff: this shows the parent stage background (a brief "freeze"/blank, on
+ // the order of the reload time ~100-300ms) INSTEAD of the all-clips flash. A
+ // blank is far less jarring than a burst of every asset appearing at once.
+ // Only the FULL-reload edits (drops/inserts) hit this — timing edits now take
+ // the soft-reload path and never touch refreshPlayer.
+ iframe.style.visibility = "hidden";
const src = iframe.src;
const url = new URL(src, window.location.origin);
url.searchParams.set("_t", String(Date.now()));
diff --git a/packages/studio/src/player/hooks/useTimelinePlayerLoop.ts b/packages/studio/src/player/hooks/useTimelinePlayerLoop.ts
new file mode 100644
index 0000000000..bda3d50601
--- /dev/null
+++ b/packages/studio/src/player/hooks/useTimelinePlayerLoop.ts
@@ -0,0 +1,85 @@
+/**
+ * The forward playback loop for the timeline player.
+ *
+ * Owns the three requestAnimationFrame lifecycle callbacks that drive (and stop)
+ * playback:
+ * - startRAFLoop — the forward tick: advance liveTime, honour in/out loop
+ * points + loopEnabled, and pause + sync the store at the end.
+ * - stopRAFLoop — cancel the forward tick.
+ * - stopReverseLoop — cancel the reverse-shuttle tick (owned by the parent hook).
+ *
+ * Called unconditionally at the top level of useTimelinePlayer so its useCallback
+ * hooks run in a stable order; every dependency is passed in as an argument.
+ */
+
+import { useCallback } from "react";
+import { liveTime, usePlayerStore } from "../store/playerStore";
+import type { PlaybackAdapter } from "../lib/playbackTypes";
+
+interface UseTimelinePlayerLoopParams {
+ rafRef: React.MutableRefObject<number>;
+ reverseRafRef: React.MutableRefObject<number>;
+ getAdapter: () => PlaybackAdapter | null;
+ setCurrentTime: (v: number) => void;
+ setIsPlaying: (v: boolean) => void;
+}
+
+interface UseTimelinePlayerLoopResult {
+ startRAFLoop: () => void;
+ stopRAFLoop: () => void;
+ stopReverseLoop: () => void;
+}
+
+export function useTimelinePlayerLoop({
+ rafRef,
+ reverseRafRef,
+ getAdapter,
+ setCurrentTime,
+ setIsPlaying,
+}: UseTimelinePlayerLoopParams): UseTimelinePlayerLoopResult {
+ const stopReverseLoop = useCallback(() => {
+ cancelAnimationFrame(reverseRafRef.current);
+ }, [reverseRafRef]);
+
+ const startRAFLoop = useCallback(() => {
+ // fallow-ignore-next-line complexity
+ const tick = () => {
+ const adapter = getAdapter();
+ if (adapter) {
+ const rawTime = adapter.getTime();
+ const dur = adapter.getDuration();
+ const time = dur > 0 ? Math.min(rawTime, dur) : rawTime;
+ liveTime.notify(time); // direct DOM updates, no React re-render
+ const { inPoint, outPoint } = usePlayerStore.getState();
+ const rawLoopEnd = outPoint !== null ? Math.min(outPoint, dur) : dur;
+ const rawLoopStart = inPoint !== null ? inPoint : 0;
+ const loopEnd = rawLoopStart < rawLoopEnd ? rawLoopEnd : dur;
+ const loopStart = rawLoopStart < rawLoopEnd ? rawLoopStart : 0;
+ if (time >= loopEnd) {
+ if (usePlayerStore.getState().loopEnabled && dur > 0) {
+ // keepPlaying skips the adapter's implicit pause; play() below is then a no-op.
+ adapter.seek(loopStart, { keepPlaying: true });
+ liveTime.notify(loopStart);
+ adapter.play();
+ setIsPlaying(true);
+ rafRef.current = requestAnimationFrame(tick);
+ return;
+ }
+ if (adapter.isPlaying()) adapter.pause();
+ setCurrentTime(time); // sync Zustand once at end
+ setIsPlaying(false);
+ cancelAnimationFrame(rafRef.current);
+ return;
+ }
+ }
+ rafRef.current = requestAnimationFrame(tick);
+ };
+ rafRef.current = requestAnimationFrame(tick);
+ }, [rafRef, getAdapter, setCurrentTime, setIsPlaying]);
+
+ const stopRAFLoop = useCallback(() => {
+ cancelAnimationFrame(rafRef.current);
+ }, [rafRef]);
+
+ return { startRAFLoop, stopRAFLoop, stopReverseLoop };
+}
diff --git a/packages/studio/src/player/index.ts b/packages/studio/src/player/index.ts
index d8c516d98a..72e50a2bcd 100644
--- a/packages/studio/src/player/index.ts
+++ b/packages/studio/src/player/index.ts
@@ -6,11 +6,12 @@ export { VideoThumbnail } from "./components/VideoThumbnail";
export { CompositionThumbnail } from "./components/CompositionThumbnail";
// Hooks
-export { useTimelinePlayer, resolveIframe } from "./hooks/useTimelinePlayer";
+export { useTimelinePlayer } from "./hooks/useTimelinePlayer";
+export { resolveIframe } from "./lib/timelineDOM";
// Store
export { usePlayerStore, liveTime } from "./store/playerStore";
-export type { TimelineElement, ZoomMode } from "./store/playerStore";
+export type { SelectElementOptions, TimelineElement } from "./store/playerStore";
// Utils
export { formatTime } from "./lib/time";
diff --git a/packages/studio/src/player/lib/time.test.ts b/packages/studio/src/player/lib/time.test.ts
index 343ae0f26a..ac319177b0 100644
--- a/packages/studio/src/player/lib/time.test.ts
+++ b/packages/studio/src/player/lib/time.test.ts
@@ -3,26 +3,26 @@ import { formatFrameTime, frameToSeconds, secondsToFrame, stepFrameTime, formatT
describe("formatTime", () => {
it("formats zero seconds", () => {
- expect(formatTime(0)).toBe("0:00");
+ expect(formatTime(0)).toBe("00:00");
});
// fallow-ignore-next-line code-duplication
it("formats seconds less than a minute", () => {
- expect(formatTime(5)).toBe("0:05");
- expect(formatTime(30)).toBe("0:30");
- expect(formatTime(59)).toBe("0:59");
+ expect(formatTime(5)).toBe("00:05");
+ expect(formatTime(30)).toBe("00:30");
+ expect(formatTime(59)).toBe("00:59");
});
it("formats exact minutes", () => {
- expect(formatTime(60)).toBe("1:00");
- expect(formatTime(120)).toBe("2:00");
+ expect(formatTime(60)).toBe("01:00");
+ expect(formatTime(120)).toBe("02:00");
expect(formatTime(600)).toBe("10:00");
});
it("formats minutes and seconds", () => {
- expect(formatTime(65)).toBe("1:05");
- expect(formatTime(90)).toBe("1:30");
- expect(formatTime(125)).toBe("2:05");
+ expect(formatTime(65)).toBe("01:05");
+ expect(formatTime(90)).toBe("01:30");
+ expect(formatTime(125)).toBe("02:05");
});
it("formats large values (over an hour)", () => {
@@ -32,28 +32,28 @@ describe("formatTime", () => {
});
it("floors fractional seconds", () => {
- expect(formatTime(0.9)).toBe("0:00");
- expect(formatTime(1.5)).toBe("0:01");
- expect(formatTime(59.99)).toBe("0:59");
- expect(formatTime(60.5)).toBe("1:00");
+ expect(formatTime(0.9)).toBe("00:00");
+ expect(formatTime(1.5)).toBe("00:01");
+ expect(formatTime(59.99)).toBe("00:59");
+ expect(formatTime(60.5)).toBe("01:00");
});
- it("pads single-digit seconds with leading zero", () => {
- expect(formatTime(1)).toBe("0:01");
- expect(formatTime(61)).toBe("1:01");
+ it("pads single-digit minutes and seconds with leading zeros", () => {
+ expect(formatTime(1)).toBe("00:01");
+ expect(formatTime(61)).toBe("01:01");
expect(formatTime(609)).toBe("10:09");
});
it("guards against negative values", () => {
- expect(formatTime(-1)).toBe("0:00");
+ expect(formatTime(-1)).toBe("00:00");
});
it("guards against NaN", () => {
- expect(formatTime(NaN)).toBe("0:00");
+ expect(formatTime(NaN)).toBe("00:00");
});
it("guards against Infinity", () => {
- expect(formatTime(Infinity)).toBe("0:00");
+ expect(formatTime(Infinity)).toBe("00:00");
});
});
diff --git a/packages/studio/src/player/lib/time.ts b/packages/studio/src/player/lib/time.ts
index 0f90e84674..6795de056d 100644
--- a/packages/studio/src/player/lib/time.ts
+++ b/packages/studio/src/player/lib/time.ts
@@ -1,10 +1,14 @@
export const STUDIO_PREVIEW_FPS = 30;
export function formatTime(time: number): string {
- if (!Number.isFinite(time) || time < 0) return "0:00";
+ if (!Number.isFinite(time) || time < 0) return "00:00";
const mins = Math.floor(time / 60);
const secs = Math.floor(time % 60);
- return `${mins}:${secs.toString().padStart(2, "0")}`;
+ // Zero-pad minutes as well as seconds so every readout is a stable-width
+ // MM:SS (e.g. "00:44", not "0:44"). Minutes past 99 keep their extra digits
+ // ("120:00"); an hours-style H:MM:SS grouping is applied by callers that need
+ // it (see formatTimelineTickLabel), never here.
+ return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
}
export function secondsToFrame(time: number, fps = STUDIO_PREVIEW_FPS): number {
diff --git a/packages/studio/src/player/lib/timelineDOM.test.ts b/packages/studio/src/player/lib/timelineDOM.test.ts
index ff919b87e8..ac3ad76037 100644
--- a/packages/studio/src/player/lib/timelineDOM.test.ts
+++ b/packages/studio/src/player/lib/timelineDOM.test.ts
@@ -4,8 +4,13 @@ import {
createTimelineElementFromManifestClip,
parseTimelineFromDOM,
createImplicitTimelineLayersFromDOM,
- buildStandaloneRootTimelineElement,
+ mergeTimelineElementsPreservingDowngrades,
} from "./timelineDOM";
+import type { TimelineElement } from "../store/playerStore";
+
+function el(id: string, extra: Partial<TimelineElement> = {}): TimelineElement {
+ return { id, tag: "img", start: 0, duration: 5, track: 0, ...extra };
+}
function makeDoc(html: string): Document {
const d = document.implementation.createHTMLDocument();
@@ -13,29 +18,6 @@ function makeDoc(html: string): Document {
return d;
}
-function makeLiveDoc(html: string): Document {
- document.head.innerHTML = "";
- document.body.innerHTML = html;
- return document;
-}
-
-function mockComputedZIndex(doc: Document, zIndexById: ReadonlyMap<string, string>): void {
- const win = doc.defaultView;
- if (!win) throw new Error("Expected document window");
- const original = win.getComputedStyle.bind(win);
- Object.defineProperty(win, "getComputedStyle", {
- configurable: true,
- value: (element: Element, pseudoElt?: string | null) => {
- const style = original(element, pseudoElt);
- const zIndex = zIndexById.get(element.id);
- if (zIndex != null) {
- Object.defineProperty(style, "zIndex", { configurable: true, value: zIndex });
- }
- return style;
- },
- });
-}
-
describe("parseTimelineFromDOM — hfId from data-hf-id", () => {
it("harvests hfId from a data-start element that has data-hf-id", () => {
const doc = makeDoc(`
@@ -126,58 +108,6 @@ describe("parseTimelineFromDOM — hfId from data-hf-id", () => {
expect(element.hidden).toBe(true);
});
-
- it("captures the effective z-index from the live element, not the runtime inline-only value", () => {
- // The runtime reports inline-only z-index (0 for CSS-rule authored z-index),
- // which must NOT override the live element's effective z-index — otherwise
- // the timeline collapses every CSS-styled clip to a z=0 tie and mis-orders.
- const doc = makeDoc(`
- <div data-composition-id="root">
- <div id="hero" class="clip" data-start="0" data-duration="5" style="z-index: 30"></div>
- </div>
- `);
- const hostEl = doc.getElementById("hero");
-
- const element = createTimelineElementFromManifestClip({
- clip: {
- id: "hero",
- label: "Hero",
- kind: "element",
- tagName: "div",
- start: 0,
- duration: 5,
- track: 0,
- zIndex: 0,
- compositionId: null,
- parentCompositionId: null,
- compositionSrc: null,
- assetUrl: null,
- },
- fallbackIndex: 0,
- doc,
- hostEl,
- });
-
- expect(element.zIndex).toBe(30);
- expect(element.hasExplicitZIndex).toBe(true);
- });
-
- it("marks parsed inline, CSS-rule, and auto z-index authorship accurately", () => {
- const doc = makeLiveDoc(`
- <div data-composition-id="root">
- <div id="inline" class="clip" data-start="0" data-duration="2" style="z-index: 3"></div>
- <div id="rule" class="clip" data-start="0" data-duration="2"></div>
- <div id="auto" class="clip" data-start="0" data-duration="2"></div>
- </div>
- `);
- mockComputedZIndex(doc, new Map([["rule", "12"]]));
-
- const elements = parseTimelineFromDOM(doc, 10);
-
- expect(elements.find((el) => el.id === "inline")?.hasExplicitZIndex).toBe(true);
- expect(elements.find((el) => el.id === "rule")?.hasExplicitZIndex).toBe(true);
- expect(elements.find((el) => el.id === "auto")?.hasExplicitZIndex).toBe(false);
- });
});
describe("createImplicitTimelineLayersFromDOM — hfId from data-hf-id", () => {
@@ -211,31 +141,28 @@ describe("createImplicitTimelineLayersFromDOM — hfId from data-hf-id", () => {
expect(layers).toEqual([]);
});
+});
- it("marks implicit layer CSS z-index authorship from computed style", () => {
- const doc = makeLiveDoc(`
- <div data-composition-id="root">
- <div id="layer" class="clip"></div>
- </div>
- `);
- mockComputedZIndex(doc, new Map([["layer", "8"]]));
-
- const layers = createImplicitTimelineLayersFromDOM(doc, 10);
-
- expect(layers[0]?.zIndex).toBe(8);
- expect(layers[0]?.hasExplicitZIndex).toBe(true);
+describe("mergeTimelineElementsPreservingDowngrades — genuine removal vs transient downgrade", () => {
+ it("drops a removed TOP-LEVEL element (undo of a split) instead of ghosting it", () => {
+ const current = [el("a"), el("a-split")]; // post-split store: original + clone
+ const next = [el("a")]; // fresh scan of the reverted file: clone gone
+ const merged = mergeTimelineElementsPreservingDowngrades(current, next, 30, 30);
+ expect(merged.map((e) => e.id)).toEqual(["a"]);
});
-});
-describe("buildStandaloneRootTimelineElement", () => {
- it("marks the standalone root as auto z-index", () => {
- const root = buildStandaloneRootTimelineElement({
- compositionId: "root",
- tagName: "div",
- rootDuration: 10,
- iframeSrc: "/preview/comp/index.html",
- });
+ it("still preserves an enriched sub-composition child a bare re-scan drops", () => {
+ const current = [el("a"), el("sub-child", { compositionSrc: "sub.html" })];
+ const next = [el("a")]; // bare DOM scan misses the enriched sub-comp child
+ const merged = mergeTimelineElementsPreservingDowngrades(current, next, 30, 30);
+ expect(merged.map((e) => e.id).sort()).toEqual(["a", "sub-child"]);
+ });
- expect(root?.hasExplicitZIndex).toBe(false);
+ it("trusts the fresh scan fully when it is not shorter", () => {
+ const current = [el("a"), el("b", { compositionSrc: "sub.html" })];
+ const next = [el("a"), el("c")];
+ expect(
+ mergeTimelineElementsPreservingDowngrades(current, next, 30, 30).map((e) => e.id),
+ ).toEqual(["a", "c"]);
});
});
diff --git a/packages/studio/src/player/lib/timelineDOM.ts b/packages/studio/src/player/lib/timelineDOM.ts
index cfc1825a08..55dad9bf9a 100644
--- a/packages/studio/src/player/lib/timelineDOM.ts
+++ b/packages/studio/src/player/lib/timelineDOM.ts
@@ -10,7 +10,6 @@
import type { TimelineElement } from "../store/playerStore";
import type { ClipManifestClip } from "./playbackTypes";
-import { getElementZIndex, hasExplicitZIndex } from "./layerOrdering";
import {
resolveMediaElement,
applyMediaMetadataFromElement,
@@ -24,6 +23,7 @@ import {
buildTimelineElementIdentity,
getTimelineElementIdentity,
isTimelineIgnoredElement,
+ readTimelineElementZIndex,
} from "./timelineElementHelpers";
// Re-export helpers that were previously public from this module so that
@@ -66,49 +66,6 @@ function resolveClipTag(clip: ClipManifestClip): string {
return clip.tagName || clip.kind || "div";
}
-function resolveDomCompositionContext(
- element: Element,
- root: Element | null,
-): {
- parentCompositionId: string | null;
- compositionAncestors: string[];
- stackingContextId: string | null;
-} {
- const ancestors: string[] = [];
- let parentCompositionId: string | null = null;
- let cursor = element.parentElement;
- while (cursor) {
- const compositionId = cursor.getAttribute("data-composition-id");
- if (compositionId) {
- ancestors.push(compositionId);
- if (!parentCompositionId && cursor !== root) {
- parentCompositionId = compositionId;
- }
- }
- cursor = cursor.parentElement;
- }
- const compositionAncestors = ancestors.reverse();
- return {
- parentCompositionId,
- compositionAncestors,
- stackingContextId: parentCompositionId ?? compositionAncestors[0] ?? null,
- };
-}
-
-function isHTMLElement(element: Element | null): element is HTMLElement {
- if (!element) return false;
- const HtmlElementCtor = element.ownerDocument.defaultView?.HTMLElement ?? globalThis.HTMLElement;
- return typeof HtmlElementCtor !== "undefined" && element instanceof HtmlElementCtor;
-}
-
-function getTimelineElementZIndex(element: Element | null): number | undefined {
- return isHTMLElement(element) ? getElementZIndex(element) : undefined;
-}
-
-function getTimelineElementHasExplicitZIndex(element: Element | null): boolean {
- return isHTMLElement(element) ? hasExplicitZIndex(element) : false;
-}
-
// fallow-ignore-next-line complexity
export function createTimelineElementFromManifestClip(params: {
clip: ClipManifestClip;
@@ -130,14 +87,6 @@ export function createTimelineElementFromManifestClip(params: {
let sourceFile: string | undefined;
let hfId: string | undefined;
- const domContext = hostEl
- ? resolveDomCompositionContext(hostEl, doc?.querySelector("[data-composition-id]") ?? null)
- : null;
- const compositionAncestors = clip.compositionAncestors ?? domContext?.compositionAncestors;
- const parentCompositionId = clip.parentCompositionId ?? domContext?.parentCompositionId;
- const stackingContextId =
- clip.stackingContextId ?? parentCompositionId ?? compositionAncestors?.[0] ?? null;
-
if (hostEl) {
domId = hostEl.id || undefined;
hfId = hostEl.getAttribute("data-hf-id") || undefined;
@@ -164,15 +113,6 @@ export function createTimelineElementFromManifestClip(params: {
start: clip.start,
duration: clip.duration,
track: clip.track,
- // Prefer the effective (computed) z-index read from the live element — the
- // same read the reorder commit uses — so CSS-rule z-index (not just inline)
- // is captured. clip.zIndex from the runtime is inline-only (0 for CSS rules),
- // so it can only serve as a fallback when the element isn't live.
- zIndex: getTimelineElementZIndex(hostEl) ?? clip.zIndex ?? 0,
- hasExplicitZIndex: getTimelineElementHasExplicitZIndex(hostEl),
- stackingContextId,
- parentCompositionId,
- compositionAncestors,
domId,
hfId,
selector,
@@ -185,6 +125,7 @@ export function createTimelineElementFromManifestClip(params: {
if (hostEl.hasAttribute("data-hidden")) entry.hidden = true;
const timelineRole = hostEl.getAttribute("data-timeline-role");
if (timelineRole) entry.timelineRole = timelineRole;
+ entry.zIndex = readTimelineElementZIndex(hostEl);
}
if (clip.assetUrl) entry.src = clip.assetUrl;
if (clip.kind === "composition" && clip.compositionId) {
@@ -207,8 +148,6 @@ export function createTimelineElementFromManifestClip(params: {
}
}
if (hostEl) {
- entry.zIndex = getTimelineElementZIndex(hostEl) ?? entry.zIndex;
- entry.hasExplicitZIndex = getTimelineElementHasExplicitZIndex(hostEl);
entry.domId = hostEl.id || undefined;
entry.hfId = hostEl.getAttribute("data-hf-id") || undefined;
entry.selector = getTimelineElementSelector(hostEl);
@@ -269,10 +208,10 @@ export function createImplicitTimelineLayersFromDOM(
});
if (existingKeys.has(identity.key) || existingKeys.has(identity.id)) continue;
- const compositionContext = resolveDomCompositionContext(child, rootComp);
layers.push({
domId: child.id || undefined,
hfId: child.getAttribute("data-hf-id") || undefined,
+ zIndex: readTimelineElementZIndex(child),
duration: rootDuration,
id: identity.id,
key: identity.key,
@@ -281,11 +220,6 @@ export function createImplicitTimelineLayersFromDOM(
selectorIndex,
sourceFile,
start: 0,
- zIndex: getTimelineElementZIndex(child),
- hasExplicitZIndex: getTimelineElementHasExplicitZIndex(child),
- stackingContextId: compositionContext.stackingContextId,
- parentCompositionId: compositionContext.parentCompositionId,
- compositionAncestors: compositionContext.compositionAncestors,
tag: child.tagName.toLowerCase(),
timingSource: "implicit",
track: maxTrack + 1 + layers.length,
@@ -347,7 +281,6 @@ export function parseTimelineFromDOM(doc: Document, rootDuration: number): Timel
selectorIndex,
sourceFile,
});
- const compositionContext = resolveDomCompositionContext(el, rootComp);
const entry: TimelineElement = {
id: identity.id,
label,
@@ -356,17 +289,13 @@ export function parseTimelineFromDOM(doc: Document, rootDuration: number): Timel
start,
duration: dur,
track: isNaN(track) ? 0 : track,
- zIndex: getTimelineElementZIndex(el),
- hasExplicitZIndex: getTimelineElementHasExplicitZIndex(el),
- stackingContextId: compositionContext.stackingContextId,
- parentCompositionId: compositionContext.parentCompositionId,
- compositionAncestors: compositionContext.compositionAncestors,
domId: el.id || undefined,
hfId: el.getAttribute("data-hf-id") || undefined,
selector,
selectorIndex,
sourceFile,
timingSource: "authored",
+ zIndex: readTimelineElementZIndex(el),
};
const mediaEl = resolveMediaElement(el);
@@ -437,7 +366,14 @@ export function mergeTimelineElementsPreservingDowngrades(
const nextIdentities = new Set(nextElements.map(getTimelineElementIdentity));
const preserved = currentElements.filter(
- (element) => !nextIdentities.has(getTimelineElementIdentity(element)),
+ (element) =>
+ !nextIdentities.has(getTimelineElementIdentity(element)) &&
+ // Only preserve enriched sub-composition children (compositionSrc set),
+ // which a bare DOM re-scan legitimately drops and enrichMissingCompositions
+ // re-adds. A TOP-LEVEL element missing from the fresh scan was genuinely
+ // removed (undo of a split, a delete), so let it go — otherwise undoing a
+ // split leaves a ghost clip in the timeline even though the file is reverted.
+ element.compositionSrc != null,
);
if (preserved.length === 0) return nextElements;
return [...nextElements, ...preserved];
@@ -481,11 +417,6 @@ export function buildStandaloneRootTimelineElement(params: {
start: 0,
duration: params.rootDuration,
track: 0,
- zIndex: 0,
- hasExplicitZIndex: false,
- stackingContextId: params.compositionId,
- parentCompositionId: null,
- compositionAncestors: [params.compositionId],
compositionSrc,
selector: params.selector,
selectorIndex: params.selectorIndex,
diff --git a/packages/studio/src/player/lib/timelineElementHelpers.ts b/packages/studio/src/player/lib/timelineElementHelpers.ts
index f582530821..a9eb60425e 100644
--- a/packages/studio/src/player/lib/timelineElementHelpers.ts
+++ b/packages/studio/src/player/lib/timelineElementHelpers.ts
@@ -15,6 +15,31 @@ import { isFinitePositive } from "./playbackAdapter";
// Duration attribute helpers
// ---------------------------------------------------------------------------
+/**
+ * Read a host element's effective CSS stacking order for the timeline's reverse
+ * z→lane mapping. Prefers the inline `style.zIndex` (what the canvas context
+ * menu and LayersPanel z-edits write via handleDomZIndexReorderCommit), falls
+ * 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.
+ */
+export function readTimelineElementZIndex(el: Element): number {
+ const html = el as HTMLElement;
+ const parseZ = (value: string | null | undefined): number | null => {
+ if (value == null || value === "" || value === "auto") return null;
+ const n = Number.parseInt(value, 10);
+ return Number.isFinite(n) ? n : null;
+ };
+ const fromInline = parseZ(html.style?.zIndex);
+ if (fromInline != null) return fromInline;
+ const view = el.ownerDocument?.defaultView;
+ if (view?.getComputedStyle) {
+ const fromComputed = parseZ(view.getComputedStyle(html).zIndex);
+ if (fromComputed != null) return fromComputed;
+ }
+ return 0;
+}
+
function readDurationAttribute(el: Element | null | undefined): number {
if (!el) return 0;
const duration =
@@ -36,14 +61,20 @@ export function isTimelineIgnoredElement(el: Element): boolean {
);
}
-export function readTimelineDurationFromDocument(doc: Document | null | undefined): number {
+/**
+ * Furthest clip end (start + RAW `data-duration`) over every non-root clip in the
+ * document. Reads the authored attribute, NOT any runtime-computed value — so it
+ * is immune to the runtime's clamp that truncates a clip's live duration to the
+ * composition length. This is the source of truth for content-driven duration:
+ * computing it from the store instead would feed the truncated value back in and
+ * make the composition length ratchet down (research HANDOFF-3 §6.1 feedback loop).
+ */
+export function furthestClipEndFromDocument(doc: Document | null | undefined): number {
if (!doc) return 0;
- const rootDuration = readDurationAttribute(doc.querySelector("[data-composition-id]"));
- if (rootDuration > 0) return rootDuration;
-
+ const root = doc.querySelector("[data-composition-id]");
let maxEnd = 0;
for (const node of Array.from(doc.querySelectorAll("[data-start]"))) {
- if (isTimelineIgnoredElement(node)) continue;
+ if (node === root || isTimelineIgnoredElement(node)) continue;
const start = Number.parseFloat(node.getAttribute("data-start") ?? "");
const duration = readDurationAttribute(node);
if (!Number.isFinite(start) || start < 0 || duration <= 0) continue;
@@ -52,6 +83,24 @@ export function readTimelineDurationFromDocument(doc: Document | null | undefine
return maxEnd;
}
+export function readTimelineDurationFromDocument(doc: Document | null | undefined): number {
+ if (!doc) return 0;
+ const rootDuration = readDurationAttribute(doc.querySelector("[data-composition-id]"));
+ if (rootDuration > 0) return rootDuration;
+ return furthestClipEndFromDocument(doc);
+}
+
+/**
+ * Furthest clip end parsed straight from a composition SOURCE STRING (the HTML
+ * being saved). Uses raw `data-duration`, so it is the correct input for syncing
+ * the root duration after an edit — reading the store instead would use the
+ * runtime-truncated durations and shrink the composition (the feedback loop).
+ */
+export function furthestClipEndFromSource(source: string): number {
+ if (!source) return 0;
+ return furthestClipEndFromDocument(new DOMParser().parseFromString(source, "text/html"));
+}
+
// ---------------------------------------------------------------------------
// DOM element type guards
// ---------------------------------------------------------------------------
diff --git a/packages/studio/src/player/lib/timelineIframeHelpers.ts b/packages/studio/src/player/lib/timelineIframeHelpers.ts
index 77fe7d1a1e..6fa45bf2c4 100644
--- a/packages/studio/src/player/lib/timelineIframeHelpers.ts
+++ b/packages/studio/src/player/lib/timelineIframeHelpers.ts
@@ -18,6 +18,7 @@ import {
getTimelineElementSelectorIndex,
getTimelineElementDisplayLabel,
buildTimelineElementIdentity,
+ readTimelineElementZIndex,
} from "./timelineElementHelpers";
// ---------------------------------------------------------------------------
@@ -377,6 +378,7 @@ export function buildMissingCompositionElements(
selector,
selectorIndex,
sourceFile,
+ zIndex: readTimelineElementZIndex(el),
};
if (compSrc) {
entry.compositionSrc = compSrc;
diff --git a/packages/studio/src/player/store/playerStore.ts b/packages/studio/src/player/store/playerStore.ts
index ac7fcf0d43..2d537bc80f 100644
--- a/packages/studio/src/player/store/playerStore.ts
+++ b/packages/studio/src/player/store/playerStore.ts
@@ -3,6 +3,7 @@ import type { MusicBeatAnalysis } from "@hyperframes/core/beats";
import type { BeatEditState } from "../../utils/beatEditing";
import type { ClipManifestClip } from "../lib/playbackTypes";
import { readStudioUiPreferences, writeStudioUiPreferences } from "../../utils/studioUiPreferences";
+import { computePinnedZoomPercent } from "../components/timelineZoom";
/** Minimal keyframe cache types — mirrors GsapKeyframesData without pulling in Node-only gsap-parser. */
export interface KeyframeCacheEntry {
@@ -75,6 +76,10 @@ export interface TimelineElement {
export type ZoomMode = "fit" | "manual";
type TimelineTool = "select" | "razor";
+export interface SelectElementOptions {
+ preserveSet?: boolean;
+}
+
function resolveElementSelection(
ids: Iterable<string>,
anchor?: string | null,
@@ -142,6 +147,25 @@ interface PlayerState {
/** Multi-select: additional selected elements beyond selectedElementId. */
selectedElementIds: Set<string>;
+ clearSelectedElementIds: () => void;
+ /** Replace the whole multi-selection at once (marquee live updates). */
+ setSelectedElementIds: (ids: Set<string>) => void;
+ /** Timeline magnet toggle — when false, clip drags/trims/drops never snap. */
+ timelineSnapEnabled: boolean;
+ setTimelineSnapEnabled: (enabled: boolean) => void;
+ /**
+ * Pin the timeline zoom to its current visual scale before a duration-changing
+ * edit, so a subsequent duration change (which recomputes fit-pps) stops
+ * rescaling every clip. No-op once already pinned (mode is "manual").
+ */
+ pinTimelineZoom: (currentPixelsPerSecond: number, fitPixelsPerSecond: number) => void;
+ /**
+ * The timeline's live pixels-per-second + fit basis, published by <Timeline> on
+ * every render. Non-reactive scratch state (never read as a render input).
+ */
+ timelinePps: number;
+ timelineFitPps: number;
+ setTimelineScale: (pps: number, fitPps: number) => void;
setSelection: (ids: Iterable<string>, anchor?: string | null) => void;
addSelectedElementId: (id: string) => void;
toggleSelectedElementId: (id: string) => void;
@@ -160,7 +184,7 @@ interface PlayerState {
setTimelineReady: (ready: boolean) => void;
setBeatDragging: (dragging: boolean) => void;
setElements: (elements: TimelineElement[]) => void;
- setSelectedElementId: (id: string | null) => void;
+ setSelectedElementId: (id: string | null, options?: SelectElementOptions) => void;
/** Move the selection anchor within an active multi-selection without collapsing it. */
setSelectionAnchor: (id: string | null) => void;
updateElement: (
@@ -260,6 +284,8 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({
loopEnabled: false,
zoomMode: "fit",
manualZoomPercent: 100,
+ timelinePps: 100,
+ timelineFitPps: 100,
inPoint: null,
outPoint: null,
@@ -383,6 +409,32 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({
},
setLoopEnabled: (enabled) => set({ loopEnabled: enabled }),
setZoomMode: (mode) => set({ zoomMode: mode }),
+ clearSelectedElementIds: () => set({ selectedElementIds: new Set() }),
+ setSelectedElementIds: (ids: Set<string>) => set({ selectedElementIds: new Set(ids) }),
+ timelineSnapEnabled: readStudioUiPreferences().timelineSnapEnabled ?? true,
+ setTimelineSnapEnabled: (enabled) => {
+ writeStudioUiPreferences({ timelineSnapEnabled: enabled });
+ set({ timelineSnapEnabled: enabled });
+ },
+ pinTimelineZoom: (currentPixelsPerSecond, fitPixelsPerSecond) =>
+ set((s) => {
+ // Already pinned (or the user manually zoomed) — never clobber that.
+ if (s.zoomMode === "manual") return {};
+ const percent = computePinnedZoomPercent(currentPixelsPerSecond, fitPixelsPerSecond);
+ writeStudioUiPreferences({
+ timelineZoomMode: "manual",
+ timelineManualZoomPercent: percent,
+ });
+ return { zoomMode: "manual", manualZoomPercent: percent };
+ }),
+ setTimelineScale: (pps, fitPps) => {
+ // Non-reactive publish: mutate in place + reuse the same object identity so no
+ // subscriber re-renders (these fields are never a render input, only read
+ // imperatively before pinning).
+ const state = get();
+ state.timelinePps = pps;
+ state.timelineFitPps = fitPps;
+ },
setInPoint: (time) =>
set((state) => {
const t = time !== null && Number.isFinite(time) ? time : null;
@@ -414,9 +466,16 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({
// A genuine single selection: always collapse the set to just this element. User
// intent (timeline click, preview click via applyDomSelection) flows here; DOM sync
// echoes that must preserve a group go through setSelectionAnchor instead.
- setSelectedElementId: (id) =>
+ setSelectedElementId: (id, options) =>
set((s) => {
- const selectedElementIds = id ? new Set([id]) : new Set<string>();
+ const preserveSet = Boolean(options?.preserveSet && id && s.selectedElementIds.has(id));
+ const selectedElementIds = preserveSet
+ ? new Set(s.selectedElementIds)
+ : options?.preserveSet
+ ? new Set<string>()
+ : id
+ ? new Set([id])
+ : new Set<string>();
// Selecting a different element drops any active keyframe selection — otherwise
// a stale activeKeyframePct from a prior diamond click would force the next drag
// to "modify" a keyframe on the new element. A diamond click sets the pct AFTER
diff --git a/packages/studio/src/styles/studio.css b/packages/studio/src/styles/studio.css
index 05bd0b90b1..99ebd0cd27 100644
--- a/packages/studio/src/styles/studio.css
+++ b/packages/studio/src/styles/studio.css
@@ -141,6 +141,22 @@ body {
opacity: 1;
}
+/* Audio clips read as a distinct kind — a persistent violet tint vs the teal-
+ accented visual clips — so the audio zone at the bottom is visually separate
+ at a glance (the timeline's kinds: visual on top, audio below). */
+.timeline-clip.is-audio {
+ background-color: rgba(167, 139, 250, 0.16);
+ border-color: rgba(167, 139, 250, 0.4);
+}
+
+.timeline-clip.is-audio.is-hovered {
+ background-color: rgba(167, 139, 250, 0.24);
+}
+
+.timeline-clip.is-audio.is-dragging {
+ background-color: rgba(60, 52, 84, 0.96);
+}
+
.timeline-clip.is-hovered {
background-color: rgba(255, 255, 255, 0.09);
}
@@ -158,9 +174,20 @@ body {
}
.timeline-clip.is-dragging {
+ /* Solid background so the picked-up clip reads clearly while dragging — audio
+ clips (waveform drawn on a separate layer) would otherwise look transparent. */
+ background-color: rgba(38, 42, 52, 0.96);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
}
+/* Keep the white selection outline while dragging (a plain box-shadow alone gets
+ overridden by .is-dragging's drop shadow, so re-state both together). */
+.timeline-clip.is-selected.is-dragging {
+ box-shadow:
+ 0 0 0 1.5px rgba(255, 255, 255, 0.85),
+ 0 8px 24px rgba(0, 0, 0, 0.4);
+}
+
.timeline-clip[data-active].is-selected.is-dragging {
box-shadow:
0 0 0 1.5px rgba(255, 255, 255, 0.85),
diff --git a/packages/studio/src/utils/assetPreviewStore.ts b/packages/studio/src/utils/assetPreviewStore.ts
new file mode 100644
index 0000000000..44e807bc54
--- /dev/null
+++ b/packages/studio/src/utils/assetPreviewStore.ts
@@ -0,0 +1,33 @@
+/**
+ * Tiny Zustand slice that carries the "asset preview overlay" state.
+ *
+ * When a user clicks an asset card that has NOT yet been added to the
+ * timeline the overlay fires up: a dark scrim + centered media element
+ * (img / video / audio) + filename label rendered inside PreviewPane.
+ *
+ * State lives here so AssetsTab (sidebar) and PreviewPane (preview column)
+ * can communicate without prop-drilling through the multi-layer EditorShell
+ * tree. The store is project-scoped: NLEProvider (NLEContext.tsx) clears it
+ * whenever `projectId` changes, so a preview opened in one project can't
+ * bleed into another (the overlay itself stays mounted across project
+ * switches — EditorShell isn't keyed by projectId).
+ */
+import { create } from "zustand";
+
+interface AssetPreviewState {
+ /** Project-relative asset path currently being previewed, or null. */
+ previewAsset: string | null;
+ /** projectId for which the preview was opened (used to build the serve URL). */
+ previewProjectId: string | null;
+ /** Open a media preview for the given asset. */
+ setPreviewAsset: (asset: string, projectId: string) => void;
+ /** Close the preview overlay. */
+ clearPreviewAsset: () => void;
+}
+
+export const useAssetPreviewStore = create<AssetPreviewState>((set) => ({
+ previewAsset: null,
+ previewProjectId: null,
+ setPreviewAsset: (asset, projectId) => set({ previewAsset: asset, previewProjectId: projectId }),
+ clearPreviewAsset: () => set({ previewAsset: null, previewProjectId: null }),
+}));
diff --git a/packages/studio/src/utils/blockInstaller.ts b/packages/studio/src/utils/blockInstaller.ts
index daf636a7f1..89cd45b2eb 100644
--- a/packages/studio/src/utils/blockInstaller.ts
+++ b/packages/studio/src/utils/blockInstaller.ts
@@ -2,9 +2,10 @@ import type { RegistryItem } from "@hyperframes/core/registry";
import type { TimelineElement } from "../player";
import {
insertTimelineAssetIntoSource,
- resolveTimelineAssetInitialGeometry,
+ resolveTimelineAssetCompositionSize,
} from "./timelineAssetDrop";
import { collectHtmlIds } from "./studioHelpers";
+import { generateId } from "./generateId";
import { formatTimelineAttributeNumber } from "../player/components/timelineEditing";
import { saveProjectFilesWithHistory } from "./studioFileHistory";
import type { EditHistoryKind } from "./editHistory";
@@ -120,7 +121,9 @@ export async function addBlockToProject(
);
const isBlock = block.type === "hyperframes:block";
- const hostDims = resolveTimelineAssetInitialGeometry(originalContent);
+ const { width: hostWidth, height: hostHeight } =
+ resolveTimelineAssetCompositionSize(originalContent);
+ const hostDims = { left: 0, top: 0, width: hostWidth, height: hostHeight };
const currentTime = opts.currentTime ?? 0;
const start = placement
@@ -152,6 +155,11 @@ export async function addBlockToProject(
const subCompHtml = [
`<div`,
+ // A stable id (+ hf-id) is what authored sub-comps carry; without it the
+ // timeline can't dedup the host and renders duplicate clips that multiply
+ // on every interaction. Matches the authored-comp shape.
+ ` id="${compId}"`,
+ ` data-hf-id="hf-${generateId()}"`,
` data-composition-id="${compId}"`,
` data-composition-src="${compositionFile}"`,
` data-start="${formatTimelineAttributeNumber(start)}"`,
diff --git a/packages/studio/src/utils/editHistory.test.ts b/packages/studio/src/utils/editHistory.test.ts
index b2642e0f18..86a3a32e1c 100644
--- a/packages/studio/src/utils/editHistory.test.ts
+++ b/packages/studio/src/utils/editHistory.test.ts
@@ -209,6 +209,41 @@ describe("edit history", () => {
expect(state.undo[0].files["index.html"].after).toBe("c");
});
+ it("merges a lane-change move with its z-reorder past the default window via entry coalesceMs", () => {
+ // The z entry records only after the move persist's round-trip — often >300ms.
+ // Both sides pass coalesceMs: 5000 with the shared gesture key so the pair
+ // still folds into ONE undo step.
+ const move = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Move timeline clips",
+ kind: "timeline",
+ coalesceKey: "clip-lane-move:1",
+ coalesceMs: 5000,
+ files: { "index.html": { before: "a", after: "b" } },
+ now: 100,
+ id: "move-entry",
+ });
+ const zReorder = buildEditHistoryEntry({
+ projectId: "project-1",
+ label: "Reorder layers",
+ kind: "manual",
+ coalesceKey: "clip-lane-move:1",
+ coalesceMs: 5000,
+ files: { "index.html": { before: "b", after: "c" } },
+ now: 500,
+ id: "z-entry",
+ });
+
+ const state = pushEditHistoryEntry(
+ pushEditHistoryEntry(createEmptyEditHistory(), move),
+ zReorder,
+ );
+
+ expect(state.undo).toHaveLength(1);
+ expect(state.undo[0].files["index.html"].before).toBe("a");
+ expect(state.undo[0].files["index.html"].after).toBe("c");
+ });
+
it("folds a slow GSAP follow-up into the timing edit via a per-entry coalesceMs override", () => {
const timing = buildEditHistoryEntry({
projectId: "project-1",
diff --git a/packages/studio/src/utils/gsapSoftReload.test.ts b/packages/studio/src/utils/gsapSoftReload.test.ts
index 25e07edd97..6dae557369 100644
--- a/packages/studio/src/utils/gsapSoftReload.test.ts
+++ b/packages/studio/src/utils/gsapSoftReload.test.ts
@@ -1,7 +1,12 @@
// @vitest-environment happy-dom
import { describe, it, expect, vi } from "vitest";
-import { applySoftReload, ensureMotionPathPluginLoaded } from "./gsapSoftReload";
+import {
+ applySoftReload,
+ ensureMotionPathPluginLoaded,
+ diffSoftReloadableRestore,
+ applyUndoRestoreToPreview,
+} from "./gsapSoftReload";
const SCRIPT_TEXT = `
window.__timelines = window.__timelines || {};
@@ -447,3 +452,116 @@ 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 63012108ca..cf265b891a 100644
--- a/packages/studio/src/utils/gsapSoftReload.ts
+++ b/packages/studio/src/utils/gsapSoftReload.ts
@@ -183,6 +183,159 @@ 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) ?? "");
+ }
+}
+
+/**
+ * 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 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).
+ */
+export function applyUndoRestoreToPreview(
+ 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.
+ try {
+ win.__player?.seek?.(currentTime);
+ win.__hfStudioManualEditsApply?.();
+ } catch {
+ reloadPreview();
+ return "full";
+ }
+ return "soft";
+}
+
export function applySoftReload(
iframe: HTMLIFrameElement | null,
scriptText: string,
diff --git a/packages/studio/src/utils/mediaTypes.ts b/packages/studio/src/utils/mediaTypes.ts
index 2bd97cf869..c6030bc41f 100644
--- a/packages/studio/src/utils/mediaTypes.ts
+++ b/packages/studio/src/utils/mediaTypes.ts
@@ -1,9 +1,10 @@
-export const IMAGE_EXT = /\.(jpg|jpeg|png|gif|webp|svg|ico)$/i;
+export const IMAGE_EXT = /\.(jpg|jpeg|png|gif|webp|avif|svg|ico)$/i;
export const VIDEO_EXT = /\.(mp4|webm|mov)$/i;
export const AUDIO_EXT = /\.(mp3|wav|ogg|m4a|aac)$/i;
export const FONT_EXT = /\.(woff|woff2|ttf|ttc|otf|eot)$/i;
export const LUT_EXT = /\.cube$/i;
-export const MEDIA_EXT = /\.(mp4|webm|mov|mp3|wav|ogg|m4a|aac|jpg|jpeg|png|gif|webp|svg|ico)$/i;
+export const MEDIA_EXT =
+ /\.(mp4|webm|mov|mp3|wav|ogg|m4a|aac|jpg|jpeg|png|gif|webp|avif|svg|ico)$/i;
export function isMediaFile(path: string): boolean {
return MEDIA_EXT.test(path);
diff --git a/packages/studio/src/utils/resizeDebug.ts b/packages/studio/src/utils/resizeDebug.ts
new file mode 100644
index 0000000000..1e6172ce3f
--- /dev/null
+++ b/packages/studio/src/utils/resizeDebug.ts
@@ -0,0 +1,55 @@
+// Resize/gesture diagnostics — grep [hf-resize]. Off by default; opt in per
+// session with `localStorage.setItem("hf-resize-debug", "1")` (then reload).
+// Granular per-move/per-gesture tracing that complements the always-on
+// [hf-commit] transaction telemetry in gestureTransaction.ts.
+let moveN = 0;
+let enabled: boolean | null = null;
+
+function isEnabled(): boolean {
+ if (enabled === null) {
+ try {
+ enabled = localStorage.getItem("hf-resize-debug") === "1";
+ } catch {
+ enabled = false;
+ }
+ }
+ return enabled;
+}
+
+export function logResize(stage: string, data: Record<string, unknown>): void {
+ if (!isEnabled()) return;
+ console.log(
+ `[hf-resize] ${JSON.stringify({ stage, t: Math.round(performance.now()), ...data })}`,
+ );
+}
+
+/** Per-pointermove logging, throttled: first move then every 8th. */
+export function logResizeMove(data: Record<string, unknown>): void {
+ if (!isEnabled()) return;
+ moveN += 1;
+ if (moveN % 8 === 1) logResize("move", { n: moveN, ...data });
+}
+
+export function resetResizeMoveLog(): void {
+ moveN = 0;
+}
+
+/** Snapshot the element's live geometry now and again after 200ms (jump detector). */
+export function logResizeSettle(el: HTMLElement, tag: string): void {
+ if (!isEnabled()) return;
+ const snap = (phase: string) => {
+ const r = el.getBoundingClientRect();
+ const cs = el.ownerDocument.defaultView?.getComputedStyle(el);
+ logResize("settle", {
+ tag,
+ phase,
+ rect: { x: r.x, y: r.y, w: r.width, h: r.height },
+ cssW: cs?.width,
+ cssH: cs?.height,
+ transform: cs?.transform,
+ inlineStyle: el.getAttribute("style"),
+ });
+ };
+ snap("t0");
+ setTimeout(() => snap("t200"), 200);
+}
diff --git a/packages/studio/src/utils/rootDuration.test.ts b/packages/studio/src/utils/rootDuration.test.ts
index 795941ce54..b0f5ee8603 100644
--- a/packages/studio/src/utils/rootDuration.test.ts
+++ b/packages/studio/src/utils/rootDuration.test.ts
@@ -1,5 +1,10 @@
+// @vitest-environment jsdom
import { describe, expect, it } from "vitest";
-import { extendRootDurationInSource } from "./rootDuration";
+import {
+ extendRootDurationInSource,
+ patchRootCompositionDuration,
+ readRootCompositionDuration,
+} from "./rootDuration";
describe("extendRootDurationInSource", () => {
it("extends data-duration when the new end is bigger than the root duration", () => {
@@ -31,4 +36,88 @@ describe("extendRootDurationInSource", () => {
expect(patched).toContain(`<div data-duration="3"></div>`);
expect(patched).toContain(`<div data-composition-id="main" data-duration="7"></div>`);
});
+
+ // Reviewer round-2 finding #3: the old regex was attribute-ORDER-dependent and
+ // double-quotes-only, so these hand-authored variants silently no-op'd.
+ it("extends when data-duration is declared BEFORE data-composition-id", () => {
+ const source = `<div data-duration="4" data-composition-id="main"></div>`;
+ expect(extendRootDurationInSource(source, 9)).toBe(
+ `<div data-duration="9" data-composition-id="main"></div>`,
+ );
+ });
+
+ it("extends when attributes use single quotes", () => {
+ const source = `<div data-composition-id='main' data-duration='4'></div>`;
+ expect(extendRootDurationInSource(source, 9)).toBe(
+ `<div data-composition-id='main' data-duration='9'></div>`,
+ );
+ });
+
+ it("extends with swapped order AND single quotes AND extra whitespace", () => {
+ const source = `<div data-duration = '4' data-composition-id = 'main' >x</div>`;
+ expect(extendRootDurationInSource(source, 9)).toBe(
+ `<div data-duration = '9' data-composition-id = 'main' >x</div>`,
+ );
+ });
+});
+
+describe("readRootCompositionDuration", () => {
+ it("reads the root duration regardless of attribute order or quote style", () => {
+ expect(
+ readRootCompositionDuration(`<div data-composition-id="main" data-duration="4"></div>`),
+ ).toBe(4);
+ expect(
+ readRootCompositionDuration(`<div data-duration="4" data-composition-id="main"></div>`),
+ ).toBe(4);
+ expect(
+ readRootCompositionDuration(`<div data-composition-id='main' data-duration='4.5'></div>`),
+ ).toBe(4.5);
+ });
+
+ it("reads the FIRST composition when several are present", () => {
+ const source = [
+ `<div data-composition-id="root" data-duration="10"></div>`,
+ `<div data-composition-id="nested" data-duration="2"></div>`,
+ ].join("\n");
+ expect(readRootCompositionDuration(source)).toBe(10);
+ });
+
+ it("returns null when there is no composition root", () => {
+ expect(readRootCompositionDuration(`<div data-duration="4"></div>`)).toBeNull();
+ });
+
+ it("returns null when the root has no data-duration attribute", () => {
+ expect(readRootCompositionDuration(`<div data-composition-id="main"></div>`)).toBeNull();
+ });
+});
+
+describe("patchRootCompositionDuration", () => {
+ it("rewrites only the root's data-duration value, preserving surrounding bytes", () => {
+ const source = [
+ `<!doctype html>`,
+ `<div data-composition-id="main" data-duration="4" data-width="640">`,
+ ` <img src="a.png" data-duration="3" />`,
+ `</div>`,
+ ].join("\n");
+ const patched = patchRootCompositionDuration(source, "8");
+ expect(patched).toBe(
+ [
+ `<!doctype html>`,
+ `<div data-composition-id="main" data-duration="8" data-width="640">`,
+ ` <img src="a.png" data-duration="3" />`,
+ `</div>`,
+ ].join("\n"),
+ );
+ });
+
+ it("keeps single-quote style when rewriting", () => {
+ expect(
+ patchRootCompositionDuration(`<div data-composition-id='main' data-duration='4'></div>`, "8"),
+ ).toBe(`<div data-composition-id='main' data-duration='8'></div>`);
+ });
+
+ it("is a no-op when the root has no data-duration attribute", () => {
+ const source = `<div data-composition-id="main"></div>`;
+ expect(patchRootCompositionDuration(source, "8")).toBe(source);
+ });
});
diff --git a/packages/studio/src/utils/rootDuration.ts b/packages/studio/src/utils/rootDuration.ts
index 0a9350425e..32724c6a72 100644
--- a/packages/studio/src/utils/rootDuration.ts
+++ b/packages/studio/src/utils/rootDuration.ts
@@ -1,17 +1,80 @@
import { formatTimelineAttributeNumber } from "../player/components/timelineEditing";
-export function extendRootDurationInSource(source: string, newEnd: number): string {
- const rootDurMatch = source.match(
- /(<[^>]*data-composition-id="[^"]*"[^>]*data-duration=")([^"]*)(")/,
+/**
+ * Matches the opening tag of the ROOT composition element — the first tag that
+ * carries a `data-composition-id` attribute, regardless of where the attribute
+ * sits in the tag or how its value is quoted. `[^>]*` keeps the match inside a
+ * single tag, so the first hit is the first composition in document order (the
+ * same element `doc.querySelector("[data-composition-id]")` resolves to).
+ */
+const ROOT_COMPOSITION_OPEN_TAG_RE = /<[^>]*\bdata-composition-id(?=[\s=/>])[^>]*>/i;
+
+/**
+ * Matches a `data-duration="..."` attribute inside a single opening tag. Quote
+ * style is captured (backreferenced), so both `"` and `'` round-trip, and the
+ * `\s*` around `=` tolerates author whitespace.
+ */
+const DATA_DURATION_ATTR_RE = /(\bdata-duration\s*=\s*)(["'])[^"']*\2/i;
+
+/**
+ * Read the ROOT composition's raw `data-duration`.
+ *
+ * Parses the source with DOMParser and locates the root the same way the rest of
+ * the timeline code does — the first `[data-composition-id]` element in document
+ * order — then reads its `data-duration`. Because it works on the parsed tree,
+ * attribute order and quote style are irrelevant, unlike the previous
+ * order-dependent, double-quotes-only regex.
+ *
+ * Returns `null` when there is no root composition or the root has no
+ * `data-duration` attribute at all. When the attribute is present but not a
+ * number the parsed `NaN` is returned as-is, so callers reproduce the old
+ * regex's "attribute matched but value unusable" behavior.
+ *
+ * Deterministic and render-safe: DOMParser is the only DOM global used.
+ */
+export function readRootCompositionDuration(source: string): number | null {
+ const root = new DOMParser()
+ .parseFromString(source, "text/html")
+ .querySelector("[data-composition-id]");
+ const raw = root?.getAttribute("data-duration");
+ if (raw == null) return null;
+ return Number.parseFloat(raw);
+}
+
+/**
+ * Rewrite the ROOT composition's `data-duration` value, preserving the rest of
+ * the document byte-for-byte.
+ *
+ * We deliberately do NOT re-serialize the parsed Document: a DOMParser round-trip
+ * injects `<html>/<head>/<body>`, forces double quotes, self-closes void
+ * elements, and drops the original indentation — it reformats unrelated markup.
+ * Instead we locate the root opening tag and rewrite only its `data-duration`
+ * value in place, keeping the author's quote style. The targeted splice is
+ * attribute-order-, quote-, and whitespace-agnostic.
+ *
+ * No-op (returns `source` unchanged) when there is no root composition tag or the
+ * root tag has no `data-duration` attribute to replace.
+ */
+export function patchRootCompositionDuration(source: string, newValue: string): string {
+ const rootTag = ROOT_COMPOSITION_OPEN_TAG_RE.exec(source);
+ if (!rootTag) return source;
+ const patchedTag = rootTag[0].replace(
+ DATA_DURATION_ATTR_RE,
+ (_full, prefix: string, quote: string) => `${prefix}${quote}${newValue}${quote}`,
);
- if (rootDurMatch) {
- const rootDur = parseFloat(rootDurMatch[2]!);
- if (newEnd > rootDur) {
- return source.replace(
- rootDurMatch[0],
- `${rootDurMatch[1]}${formatTimelineAttributeNumber(newEnd)}${rootDurMatch[3]}`,
- );
- }
- }
- return source;
+ if (patchedTag === rootTag[0]) return source;
+ return (
+ source.slice(0, rootTag.index) + patchedTag + source.slice(rootTag.index + rootTag[0].length)
+ );
+}
+
+/**
+ * Grow-only ratchet: extend the root composition's `data-duration` to `newEnd`
+ * when `newEnd` is larger than the current root duration. No-op otherwise (and
+ * when there is no root duration to compare against).
+ */
+export function extendRootDurationInSource(source: string, newEnd: number): string {
+ const current = readRootCompositionDuration(source);
+ if (current == null || !(newEnd > current)) return source;
+ return patchRootCompositionDuration(source, formatTimelineAttributeNumber(newEnd));
}
diff --git a/packages/studio/src/utils/sdkCutover.ts b/packages/studio/src/utils/sdkCutover.ts
index c13ca519e2..6f23880fa2 100644
--- a/packages/studio/src/utils/sdkCutover.ts
+++ b/packages/studio/src/utils/sdkCutover.ts
@@ -18,6 +18,7 @@ export interface CutoverDeps {
label: string;
kind: EditHistoryKind;
coalesceKey?: string;
+ coalesceMs?: number;
files: Record<string, { before: string; after: string }>;
}) => Promise<void>;
};
@@ -84,6 +85,8 @@ function wrongCompositionFile(deps: CutoverDeps, targetPath: string): boolean {
interface CutoverOptions {
label?: string;
coalesceKey?: string;
+ /** Coalesce window (ms); Infinity folds across a slow round-trip. */
+ coalesceMs?: number;
/** Skip the preview reload (mirrors the server path's skipRefresh). */
skipRefresh?: boolean;
}
@@ -110,6 +113,7 @@ export async function persistSdkSerialize(
label: options?.label ?? "Edit layer",
kind: "manual",
...(options?.coalesceKey ? { coalesceKey: options.coalesceKey } : {}),
+ ...(options?.coalesceMs != null ? { coalesceMs: options.coalesceMs } : {}),
files: { [targetPath]: { before: originalContent, after } },
});
if (deps.refresh) deps.refresh(after);
diff --git a/packages/studio/src/utils/studioFileHistory.ts b/packages/studio/src/utils/studioFileHistory.ts
index 95e0a2a395..de65254b56 100644
--- a/packages/studio/src/utils/studioFileHistory.ts
+++ b/packages/studio/src/utils/studioFileHistory.ts
@@ -1,25 +1,55 @@
+import type { MutableRefObject } from "react";
import type { EditHistoryKind } from "./editHistory";
+import { createStudioSaveHttpError } from "./studioSaveDiagnostics";
+
+export interface RecordEditInput {
+ label: string;
+ kind: EditHistoryKind;
+ coalesceKey?: string;
+ coalesceMs?: number;
+ files: Record<string, { before: string; after: string }>;
+}
+
+export interface DomEditCommitBaseParams {
+ activeCompPath: string | null;
+ showToast: (message: string, tone?: "error" | "info") => void;
+ writeProjectFile: (path: string, content: string) => Promise<void>;
+ domEditSaveTimestampRef: MutableRefObject<number>;
+ editHistory: { recordEdit: (entry: RecordEditInput) => Promise<void> };
+ projectIdRef: MutableRefObject<string | null>;
+ reloadPreview: () => void;
+ clearDomSelection: () => void;
+}
interface SaveProjectFilesWithHistoryInput {
projectId: string;
label: string;
kind: EditHistoryKind;
coalesceKey?: string;
+ coalesceMs?: number;
files: Record<string, string>;
readFile: (path: string) => Promise<string>;
writeFile: (path: string, content: string) => Promise<void>;
- recordEdit: (entry: {
- label: string;
- kind: EditHistoryKind;
- coalesceKey?: string;
- files: Record<string, { before: string; after: string }>;
- }) => Promise<void>;
+ recordEdit: (entry: RecordEditInput) => Promise<void>;
+}
+
+export async function readProjectFileContent(pid: string, path: string): Promise<string> {
+ const response = await fetch(`/api/projects/${pid}/files/${encodeURIComponent(path)}`);
+ if (!response.ok) {
+ throw await createStudioSaveHttpError(response, `Failed to read ${path}`);
+ }
+ const data = (await response.json()) as { content?: string };
+ if (typeof data.content !== "string") {
+ throw new Error(`Missing file contents for ${path}`);
+ }
+ return data.content;
}
export async function saveProjectFilesWithHistory({
label,
kind,
coalesceKey,
+ coalesceMs,
files,
readFile,
writeFile,
@@ -43,7 +73,7 @@ export async function saveProjectFilesWithHistory({
writtenPaths.push(path);
}
- await recordEdit({ label, kind, coalesceKey, files: snapshots });
+ await recordEdit({ label, kind, coalesceKey, coalesceMs, files: snapshots });
} catch (error) {
try {
for (const path of writtenPaths.reverse()) {
diff --git a/packages/studio/src/utils/studioHelpers.ts b/packages/studio/src/utils/studioHelpers.ts
index 0565eea2ca..7b4ba8a479 100644
--- a/packages/studio/src/utils/studioHelpers.ts
+++ b/packages/studio/src/utils/studioHelpers.ts
@@ -308,3 +308,65 @@ export async function resolveDroppedAssetDuration(
media.load();
return duration;
}
+
+export async function resolveDroppedAssetDimensions(
+ projectId: string,
+ assetPath: string,
+ kind: TimelineAssetKind,
+): Promise<{ width: number; height: number } | null> {
+ if (kind === "audio") return null;
+ const src = `/api/projects/${projectId}/preview/${assetPath}`;
+
+ if (kind === "image") {
+ return new Promise((resolve) => {
+ const img = new Image();
+ const timeout = window.setTimeout(() => resolve(null), 3000);
+ img.addEventListener(
+ "load",
+ () => {
+ window.clearTimeout(timeout);
+ resolve(
+ img.naturalWidth > 0 && img.naturalHeight > 0
+ ? { width: img.naturalWidth, height: img.naturalHeight }
+ : null,
+ );
+ },
+ { once: true },
+ );
+ img.addEventListener(
+ "error",
+ () => {
+ window.clearTimeout(timeout);
+ resolve(null);
+ },
+ { once: true },
+ );
+ img.src = src;
+ });
+ }
+
+ return new Promise((resolve) => {
+ const video = document.createElement("video");
+ video.preload = "metadata";
+ const timeout = window.setTimeout(() => resolve(null), 3000);
+ const finalize = (value: { width: number; height: number } | null) => {
+ window.clearTimeout(timeout);
+ video.src = "";
+ video.load();
+ resolve(value);
+ };
+ video.addEventListener(
+ "loadedmetadata",
+ () => {
+ finalize(
+ video.videoWidth > 0 && video.videoHeight > 0
+ ? { width: video.videoWidth, height: video.videoHeight }
+ : null,
+ );
+ },
+ { once: true },
+ );
+ video.addEventListener("error", () => finalize(null), { once: true });
+ video.src = src;
+ });
+}
diff --git a/packages/studio/src/utils/studioPreviewHelpers.test.ts b/packages/studio/src/utils/studioPreviewHelpers.test.ts
index 4114a03a58..fc22535c13 100644
--- a/packages/studio/src/utils/studioPreviewHelpers.test.ts
+++ b/packages/studio/src/utils/studioPreviewHelpers.test.ts
@@ -25,6 +25,15 @@ function stubRect(el: Element, rect: DOMRect): void {
el.getBoundingClientRect = () => rect;
}
+/** Create and attach a preview iframe, returning it with its (asserted) document. */
+function createPreviewIframe(): { iframe: HTMLIFrameElement; doc: Document } {
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ const doc = iframe.contentDocument;
+ if (!doc) throw new Error("Expected iframe document");
+ return { iframe, doc };
+}
+
describe("coversComposition (full-bleed canvas-pick exclusion)", () => {
const viewport = { width: 1920, height: 1080 };
@@ -106,10 +115,7 @@ describe("pauseStudioPreviewPlayback", () => {
describe("getPreviewTargetFromPointer", () => {
it("skips candidates hidden from author hit-testing by inherited pointer-events:none", () => {
- const iframe = document.createElement("iframe");
- document.body.append(iframe);
- const doc = iframe.contentDocument;
- if (!doc) throw new Error("Expected iframe document");
+ const { iframe, doc } = createPreviewIframe();
doc.body.innerHTML = `
<main id="scene" data-composition-id="scene">
@@ -141,10 +147,7 @@ describe("getPreviewTargetFromPointer", () => {
});
it("honors a CSS-class pointer-events:auto opt-in under a pointer-events:none ancestor", () => {
- const iframe = document.createElement("iframe");
- document.body.append(iframe);
- const doc = iframe.contentDocument;
- if (!doc) throw new Error("Expected iframe document");
+ const { iframe, doc } = createPreviewIframe();
doc.head.innerHTML = `<style>.clickable { pointer-events: auto; }</style>`;
doc.body.innerHTML = `
@@ -172,4 +175,58 @@ describe("getPreviewTargetFromPointer", () => {
iframe.remove();
});
+
+ it("selects a full-bleed <video> instead of skipping to the element behind it", () => {
+ const { iframe, doc } = createPreviewIframe();
+
+ doc.body.innerHTML = `
+ <main id="scene" data-composition-id="scene">
+ <div id="backdrop"></div>
+ <video id="hero"></video>
+ </main>
+ `;
+
+ const scene = doc.getElementById("scene");
+ const backdrop = doc.getElementById("backdrop");
+ const hero = doc.getElementById("hero");
+ if (!scene || !backdrop || !hero) throw new Error("Expected preview fixture elements");
+
+ stubRect(iframe, domRect(0, 0, 400, 300));
+ stubRect(scene, domRect(0, 0, 400, 300));
+ stubRect(backdrop, domRect(0, 0, 400, 300));
+ // Full-bleed hero video painted on top of a full-bleed backdrop.
+ stubRect(hero, domRect(0, 0, 400, 300));
+ doc.elementsFromPoint = () => [hero, backdrop, scene];
+
+ // Before the fix the video was full-bleed-excluded and the picker fell through
+ // to the backdrop (or null). It must now return the video itself.
+ expect(getPreviewTargetFromPointer(iframe, 200, 150, "index.html")).toBe(hero);
+
+ iframe.remove();
+ });
+
+ it("still excludes a full-bleed non-media container so clicks reach inner content", () => {
+ const { iframe, doc } = createPreviewIframe();
+
+ doc.body.innerHTML = `
+ <main id="scene" data-composition-id="scene">
+ <div id="wrapper"><h1 id="headline">Title</h1></div>
+ </main>
+ `;
+
+ const scene = doc.getElementById("scene");
+ const wrapper = doc.getElementById("wrapper");
+ const headline = doc.getElementById("headline");
+ if (!scene || !wrapper || !headline) throw new Error("Expected preview fixture elements");
+
+ stubRect(iframe, domRect(0, 0, 400, 300));
+ stubRect(scene, domRect(0, 0, 400, 300));
+ stubRect(wrapper, domRect(0, 0, 400, 300));
+ stubRect(headline, domRect(40, 40, 160, 48));
+ doc.elementsFromPoint = () => [headline, wrapper, scene];
+
+ expect(getPreviewTargetFromPointer(iframe, 80, 64, "index.html")).toBe(headline);
+
+ iframe.remove();
+ });
});
diff --git a/packages/studio/src/utils/studioPreviewHelpers.ts b/packages/studio/src/utils/studioPreviewHelpers.ts
index 9f76b59cb5..d67a8c678a 100644
--- a/packages/studio/src/utils/studioPreviewHelpers.ts
+++ b/packages/studio/src/utils/studioPreviewHelpers.ts
@@ -21,6 +21,15 @@ interface PreviewLocalPointer {
// should remain canvas-selectable.
const FULL_BLEED_RATIO = 0.95;
+// Media leaves (a hero/background video, a full-bleed image, an <svg>/<canvas>
+// backdrop) ARE the content a user clicks — they must stay canvas-selectable even
+// at full-bleed. Only empty containers (scene wrappers, layout backdrops) get
+// excluded. Without this, a full-bleed <video> is skipped and the click lands on
+// whatever sits behind it — the reported "can't select videos / selects the layer
+// behind" bug (and the "needs a second click" symptom, where the first click
+// resolves through the video to nothing and only the hover fallback recovers).
+const FULL_BLEED_SELECTABLE_MEDIA_TAGS = new Set(["video", "img", "canvas", "svg"]);
+
export function coversComposition(
elRect: { width: number; height: number },
viewport: DomEditViewport,
@@ -33,6 +42,7 @@ export function coversComposition(
}
function isFullBleedTarget(el: HTMLElement, viewport: DomEditViewport): boolean {
+ if (FULL_BLEED_SELECTABLE_MEDIA_TAGS.has(el.tagName.toLowerCase())) return false;
return coversComposition(el.getBoundingClientRect(), viewport);
}
diff --git a/packages/studio/src/utils/studioTelemetry.ts b/packages/studio/src/utils/studioTelemetry.ts
index d72b148209..c73add7afc 100644
--- a/packages/studio/src/utils/studioTelemetry.ts
+++ b/packages/studio/src/utils/studioTelemetry.ts
@@ -42,7 +42,10 @@ function getSessionProperties(): EventProperties {
viewport_width: window.innerWidth,
viewport_height: window.innerHeight,
user_agent: navigator.userAgent,
- url_hash: location.hash.replace(/#project\//, ""),
+ // Route slug only — drop the query string, which carries the current
+ // selection (selId / selSelector are the user's own element ids/CSS
+ // selectors) and other view state we must not send to analytics.
+ url_hash: location.hash.replace(/#project\//, "").split("?")[0],
};
}
diff --git a/packages/studio/src/utils/studioUrlState.test.ts b/packages/studio/src/utils/studioUrlState.test.ts
index 4a3149413e..1123d9bcb9 100644
--- a/packages/studio/src/utils/studioUrlState.test.ts
+++ b/packages/studio/src/utils/studioUrlState.test.ts
@@ -79,7 +79,6 @@ function renderStudioUrlStateHarness(
previewIframeRef: { current: null },
rightPanelTab: "renders",
rightCollapsed: true,
- timelineVisible: true,
activeCompPathHydrated: true,
domEditSelection: null,
buildDomSelectionFromTarget: () => Promise.resolve(null),
diff --git a/packages/studio/src/utils/timelineAssetDrop.ts b/packages/studio/src/utils/timelineAssetDrop.ts
index 30abc5cfa6..5194f5899b 100644
--- a/packages/studio/src/utils/timelineAssetDrop.ts
+++ b/packages/studio/src/utils/timelineAssetDrop.ts
@@ -1,4 +1,5 @@
import { AUDIO_EXT, IMAGE_EXT, VIDEO_EXT } from "./mediaTypes";
+import { patchRootCompositionDuration, readRootCompositionDuration } from "./rootDuration";
import { roundToCenti } from "./rounding";
import { COMPOSITION_ROOT_OPEN_TAG_RE } from "./compositionPatterns";
@@ -98,6 +99,8 @@ export function resolveTimelineAssetInitialGeometry(source: string): {
export function buildTimelineAssetInsertHtml(input: {
id: string;
+ /** Stable hf-id stamped as data-hf-id by the NLE drop path (optional in the legacy path). */
+ hfId?: string;
assetPath: string;
kind: TimelineAssetKind;
start: number;
@@ -136,3 +139,62 @@ export function insertTimelineAssetIntoSource(source: string, assetHtml: string)
.join("\n");
return `${source.slice(0, insertAt)}\n${childIndent}${indented}${source.slice(insertAt)}`;
}
+
+/**
+ * Set the composition root's `data-duration` to `contentEnd` (grow OR shrink) so the
+ * timeline length tracks content — the content-driven counterpart to
+ * extendCompositionDurationIfNeeded's grow-only ratchet. Used after edits that can
+ * reduce the furthest clip end (delete/trim). No-op when `contentEnd` is not > 0, so
+ * an empty timeline keeps its declared duration instead of collapsing to 0.
+ */
+export function setCompositionDurationToContent(source: string, contentEnd: number): string {
+ if (!Number.isFinite(contentEnd) || contentEnd <= 0) return source;
+ const rootDur = readRootCompositionDuration(source);
+ if (rootDur == null) return source;
+ const next = roundToCenti(contentEnd);
+ if (rootDur === next) return source;
+ return patchRootCompositionDuration(source, String(next));
+}
+
+export function extendCompositionDurationIfNeeded(source: string, requiredEnd: number): string {
+ const rootDur = readRootCompositionDuration(source);
+ if (rootDur == null || !Number.isFinite(rootDur) || requiredEnd <= rootDur) return source;
+ return patchRootCompositionDuration(source, String(roundToCenti(requiredEnd)));
+}
+
+/**
+ * Set the composition root's `data-duration` to `contentEnd` (grow OR shrink) so the
+ * timeline length tracks content — the content-driven counterpart to
+ * extendCompositionDurationIfNeeded's grow-only ratchet. Used after edits that can
+ * reduce the furthest clip end (delete/trim). No-op when `contentEnd` is not > 0, so
+ * an empty timeline keeps its declared duration instead of collapsing to 0.
+ */
+export function fitTimelineAssetGeometry(
+ natural: { width: number; height: number } | null,
+ comp: { width: number; height: number },
+): { left: number; top: number; width: number; height: number } {
+ if (!natural || natural.width <= 0 || natural.height <= 0) {
+ return { left: 0, top: 0, width: comp.width, height: comp.height };
+ }
+ const scale = Math.min(1, comp.width / natural.width, comp.height / natural.height);
+ const width = Math.round(natural.width * scale);
+ const height = Math.round(natural.height * scale);
+ return {
+ left: Math.round((comp.width - width) / 2),
+ top: Math.round((comp.height - height) / 2),
+ width,
+ height,
+ };
+}
+
+export function resolveTimelineAssetCompositionSize(source: string): {
+ width: number;
+ height: number;
+} {
+ const width = Number.parseFloat(source.match(/\bdata-width=(["'])([^"']+)\1/i)?.[2] ?? "");
+ const height = Number.parseFloat(source.match(/\bdata-height=(["'])([^"']+)\1/i)?.[2] ?? "");
+ return {
+ width: Number.isFinite(width) && width > 0 ? Math.round(width) : 640,
+ height: Number.isFinite(height) && height > 0 ? Math.round(height) : 360,
+ };
+}
diff --git a/packages/studio/src/utils/timelineDiscovery.test.ts b/packages/studio/src/utils/timelineDiscovery.test.ts
deleted file mode 100644
index 5174cb1d04..0000000000
--- a/packages/studio/src/utils/timelineDiscovery.test.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import { describe, expect, it } from "vitest";
-import {
- TIMELINE_TOGGLE_SHORTCUT_LABEL,
- getTimelineToggleTitle,
- shouldHandleTimelineToggleHotkey,
-} from "./timelineDiscovery";
-
-describe("shouldHandleTimelineToggleHotkey", () => {
- it("accepts Shift+T when focus is not inside an editor", () => {
- expect(
- shouldHandleTimelineToggleHotkey({
- key: "T",
- shiftKey: true,
- metaKey: false,
- ctrlKey: false,
- altKey: false,
- target: {
- tagName: "DIV",
- isContentEditable: false,
- closest: () => null,
- },
- } as KeyboardEvent),
- ).toBe(true);
- });
-
- it("ignores the shortcut inside text inputs", () => {
- expect(
- shouldHandleTimelineToggleHotkey({
- key: "t",
- shiftKey: true,
- metaKey: false,
- ctrlKey: false,
- altKey: false,
- target: {
- tagName: "TEXTAREA",
- isContentEditable: false,
- closest: () => null,
- },
- } as KeyboardEvent),
- ).toBe(false);
- });
-
- it("ignores the shortcut inside contenteditable editors", () => {
- expect(
- shouldHandleTimelineToggleHotkey({
- key: "t",
- shiftKey: true,
- metaKey: false,
- ctrlKey: false,
- altKey: false,
- target: {
- tagName: "DIV",
- isContentEditable: true,
- closest: () => null,
- },
- } as KeyboardEvent),
- ).toBe(false);
- });
-
- it("requires Shift without other modifiers", () => {
- expect(
- shouldHandleTimelineToggleHotkey({
- key: "t",
- shiftKey: false,
- metaKey: false,
- ctrlKey: false,
- altKey: false,
- target: null,
- } as KeyboardEvent),
- ).toBe(false);
-
- expect(
- shouldHandleTimelineToggleHotkey({
- key: "t",
- shiftKey: true,
- metaKey: true,
- ctrlKey: false,
- altKey: false,
- target: null,
- } as KeyboardEvent),
- ).toBe(false);
- });
-});
-
-describe("getTimelineToggleTitle", () => {
- it("includes the shortcut in both show and hide titles", () => {
- expect(getTimelineToggleTitle(true)).toContain(TIMELINE_TOGGLE_SHORTCUT_LABEL);
- expect(getTimelineToggleTitle(false)).toContain(TIMELINE_TOGGLE_SHORTCUT_LABEL);
- });
-});
diff --git a/packages/studio/src/utils/timelineDiscovery.ts b/packages/studio/src/utils/timelineDiscovery.ts
index f4027953e1..a6428ba0ce 100644
--- a/packages/studio/src/utils/timelineDiscovery.ts
+++ b/packages/studio/src/utils/timelineDiscovery.ts
@@ -1,9 +1,3 @@
-export const TIMELINE_TOGGLE_SHORTCUT_LABEL = "Shift+T";
-type TimelineToggleHotkeyEvent = Pick<
- KeyboardEvent,
- "key" | "shiftKey" | "metaKey" | "ctrlKey" | "altKey" | "target"
->;
-
interface EditableTargetLike {
tagName?: string;
isContentEditable?: boolean;
@@ -28,14 +22,3 @@ export function isEditableTarget(target: EventTarget | null): boolean {
),
);
}
-
-export function shouldHandleTimelineToggleHotkey(event: TimelineToggleHotkeyEvent): boolean {
- if (event.metaKey || event.ctrlKey || event.altKey) return false;
- if (!event.shiftKey) return false;
- if (event.key.toLowerCase() !== "t") return false;
- return !isEditableTarget(event.target);
-}
-
-export function getTimelineToggleTitle(timelineVisible: boolean): string {
- return `${timelineVisible ? "Hide" : "Show"} timeline editor (${TIMELINE_TOGGLE_SHORTCUT_LABEL})`;
-}