Skip to content

Write HTML. Render video. Built for agents.

fix(studio): keep clips on their row through group, ungroup, and composition recovery (#4068)

Miguel Ángela8d44b25963b
diff --git a/packages/studio-server/src/helpers/sourceMutation.ts b/packages/studio-server/src/helpers/sourceMutation.ts
index a9394bb4fd..5760cd3918 100644
--- a/packages/studio-server/src/helpers/sourceMutation.ts
+++ b/packages/studio-server/src/helpers/sourceMutation.ts
@@ -293,10 +293,16 @@ function resolveElementTiming(el: Element): {
return { start: timing.start ?? 0, duration: timing.duration ?? 0 };
}
-function setElementDuration(el: Element, start: number, duration: number): void {
+function setElementDuration(
+ el: Element,
+ start: number,
+ duration: number,
+ trackIndex?: number,
+): void {
writeClipTiming(el, {
start: Math.round(start * 1000) / 1000,
duration: Math.round(duration * 1000) / 1000,
+ ...(trackIndex != null ? { trackIndex } : {}),
});
}
@@ -312,6 +318,11 @@ export function splitElementInHtml(
playbackStart?: number;
playbackRate?: number;
stampPlaybackStart?: boolean;
+ // The element's current resolved track (authored, or the runtime's
+ // positional-index fallback when unauthored). Stamped onto both halves so
+ // inserting the clone can't shift either one to a different row — see
+ // parseAuthoredTrack's fallback in core/runtime/timeline.ts.
+ track?: number;
},
): SplitElementResult {
const { document, wrappedFragment } = parseSourceDocument(source);
@@ -363,7 +374,7 @@ export function splitElementInHtml(
// Descendants carry their own data-hf-id; leaving them duplicates the id of
// every nested node (e.g. an inner <span>), so strip them on the clone too.
for (const node of clone.querySelectorAll("[data-hf-id]")) node.removeAttribute("data-hf-id");
- setElementDuration(clone, splitTime, secondDuration);
+ setElementDuration(clone, splitTime, secondDuration, fallbackTiming?.track);
// Keep the "clip" class — the runtime uses it to control visibility
// based on data-start/data-duration timing.
@@ -401,7 +412,7 @@ export function splitElementInHtml(
// Trim the original element's duration. A GSAP element had no data-start; stamp
// it so the runtime windows the first half (visibility selects on [data-start]).
- setElementDuration(el, start, firstDuration);
+ setElementDuration(el, start, firstDuration, fallbackTiming?.track);
// Insert clone after original
if (el.nextSibling) {
@@ -453,6 +464,10 @@ export interface ElementRebase {
target: SourceMutationTarget;
left: number;
top: number;
+ /** The member's current resolved track (authored, or the runtime's
+ * positional-index fallback). Stamped explicitly so moving it into the
+ * wrapper can't shift its computed row — same hazard split closes. */
+ track?: number;
}
function getInlineStylePx(el: Element, property: string): number {
@@ -530,11 +545,11 @@ export function wrapElementsInHtml(
const memberSet = new Set<Element>(els);
const ordered = Array.from(parent.children).filter((c): c is HTMLElement => memberSet.has(c));
- // Map each member to its rebased left/top (resolved against the same document).
- const rebaseByEl = new Map<Element, { left: number; top: number }>();
+ // Map each member to its rebased left/top and track (resolved against the same document).
+ const rebaseByEl = new Map<Element, { left: number; top: number; track?: number }>();
for (const rebase of rebases) {
const el = findTargetElement(document, rebase.target);
- if (el) rebaseByEl.set(el, { left: rebase.left, top: rebase.top });
+ if (el) rebaseByEl.set(el, { left: rebase.left, top: rebase.top, track: rebase.track });
}
const wrapper = document.createElement("div");
@@ -569,6 +584,7 @@ export function wrapElementsInHtml(
for (const el of ordered) {
const rebase = rebaseByEl.get(el);
if (rebase) setInlineLeftTop(el, rebase.left, rebase.top);
+ if (rebase?.track != null) writeClipTiming(el, { trackIndex: Math.round(rebase.track) });
wrapper.appendChild(el); // appendChild moves the node, preserving order
}
@@ -579,9 +595,62 @@ export function wrapElementsInHtml(
};
}
+export interface UnwrapChildTrack {
+ target: SourceMutationTarget;
+ /** The child's current resolved track, same hazard and fix as wrap's members. */
+ track?: number;
+}
+
+// Only children actually inside the group and given a resolved track qualify —
+// same hazard and fix as wrap's members, scoped to this group's own children.
+function buildChildTrackMap(
+ document: Document,
+ group: Element,
+ childTracks: UnwrapChildTrack[],
+): Map<Element, number> {
+ const trackByEl = new Map<Element, number>();
+ for (const entry of childTracks) {
+ const el = findTargetElement(document, entry.target);
+ if (el && group.contains(el) && entry.track != null) trackByEl.set(el, entry.track);
+ }
+ return trackByEl;
+}
+
+// Undoes the wrap-side rebase (child absolute = child rebased + wrapper
+// origin), stamps each child's resolved track where one was given, and moves
+// every child back into the parent ahead of the wrapper — preserving order.
+function relocateGroupChildren(
+ group: Element,
+ parent: Element,
+ wLeft: number,
+ wTop: number,
+ trackByEl: Map<Element, number>,
+): Array<{ id: string; cx: number; cy: number }> {
+ const members: Array<{ id: string; cx: number; cy: number }> = [];
+ for (const child of Array.from(group.children)) {
+ if (isHTMLElement(child)) {
+ const newLeft = getInlineStylePx(child, "left") + wLeft;
+ const newTop = getInlineStylePx(child, "top") + wTop;
+ setInlineLeftTop(child, newLeft, newTop);
+ const track = trackByEl.get(child);
+ if (track != null) writeClipTiming(child, { trackIndex: Math.round(track) });
+ if (child.id) {
+ members.push({
+ id: child.id,
+ cx: newLeft + getInlineStylePx(child, "width") / 2,
+ cy: newTop + getInlineStylePx(child, "height") / 2,
+ });
+ }
+ }
+ parent.insertBefore(child, group);
+ }
+ return members;
+}
+
export function unwrapElementsFromHtml(
source: string,
groupTarget: SourceMutationTarget,
+ childTracks: UnwrapChildTrack[] = [],
): UnwrapElementsResult {
const { document, wrappedFragment } = parseSourceDocument(source);
const group = findTargetElement(document, groupTarget);
@@ -595,6 +664,8 @@ export function unwrapElementsFromHtml(
const parent = group.parentElement;
if (!parent) return { html: source, unwrapped: false };
+ const trackByEl = buildChildTrackMap(document, group, childTracks);
+
// Undo the rebase: child absolute position = child (rebased) + wrapper origin.
const wLeft = getInlineStylePx(group, "left");
const wTop = getInlineStylePx(group, "top");
@@ -603,23 +674,7 @@ export function unwrapElementsFromHtml(
cy: wTop + getInlineStylePx(group, "height") / 2,
};
- // Move children back to the wrapper's slot, preserving order.
- const members: Array<{ id: string; cx: number; cy: number }> = [];
- for (const child of Array.from(group.children)) {
- if (isHTMLElement(child)) {
- const newLeft = getInlineStylePx(child, "left") + wLeft;
- const newTop = getInlineStylePx(child, "top") + wTop;
- setInlineLeftTop(child, newLeft, newTop);
- if (child.id) {
- members.push({
- id: child.id,
- cx: newLeft + getInlineStylePx(child, "width") / 2,
- cy: newTop + getInlineStylePx(child, "height") / 2,
- });
- }
- }
- parent.insertBefore(child, group);
- }
+ const members = relocateGroupChildren(group, parent, wLeft, wTop, trackByEl);
const groupId = group.id || undefined;
group.remove();
diff --git a/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts b/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts
index dd37a0334f..967d9f1be2 100644
--- a/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts
+++ b/packages/studio-server/src/helpers/sourceMutationSplitAndGroup.test.ts
@@ -1,3 +1,4 @@
+// fallow-ignore-file code-duplication
import { parseHTML } from "linkedom";
import { describe, expect, it } from "vitest";
import {
@@ -32,6 +33,20 @@ describe("splitElementInHtml", () => {
expect(result.html).toContain('data-duration="4"');
});
+ it("pins both halves to the caller-supplied track so an unauthored clip's split half can't drift to a new row", () => {
+ // #box has no data-track-index/data-layer — this is the common, unauthored
+ // case that relies on the runtime's positional-index fallback. Without an
+ // explicit stamp, splitting only the clone changes DOM sibling order and
+ // the runtime resolves the clone to a different fallback track.
+ const result = splitElementInHtml(source, { id: "box" }, 3, "box-split", {
+ start: 1,
+ duration: 6,
+ track: 2,
+ });
+ expect(result.matched).toBe(true);
+ expect(result.html.match(/data-track-index="2"/g)).toHaveLength(2);
+ });
+
it("canonicalizes legacy timing attributes on both split halves", () => {
const legacy = source.replace(
'data-start="1" data-duration="6"',
@@ -253,6 +268,19 @@ describe("wrapElementsInHtml / unwrapElementsFromHtml", () => {
);
});
+ it("stamps each member's resolved track so grouping an unauthored clip can't drift it to a new row", () => {
+ const rebasesWithTrack = [
+ { target: { id: "title" }, left: 0, top: 50, track: 1 },
+ { target: { id: "logo" }, left: 40, top: 150, track: 3 },
+ { target: { id: "badge" }, left: 140, top: 0 },
+ ];
+ const { html } = wrapElementsInHtml(FIXTURE, TARGETS, "Group 1", BBOX, rebasesWithTrack);
+ const { document } = parseHTML(html);
+ expect(requireElement(document, "#title").getAttribute("data-track-index")).toBe("1");
+ expect(requireElement(document, "#logo").getAttribute("data-track-index")).toBe("3");
+ expect(requireElement(document, "#badge").hasAttribute("data-track-index")).toBe(false);
+ });
+
it("round-trips: unwrap restores original structure and coordinates", () => {
const wrapped = wrapElementsInHtml(FIXTURE, TARGETS, "Group 1", BBOX, REBASES).html;
const { html, unwrapped } = unwrapElementsFromHtml(wrapped, {
@@ -281,6 +309,23 @@ describe("wrapElementsInHtml / unwrapElementsFromHtml", () => {
);
});
+ it("stamps each child's resolved track on ungroup so it can't drift to a new row when it moves back out of the wrapper", () => {
+ const wrapped = wrapElementsInHtml(FIXTURE, TARGETS, "Group 1", BBOX, REBASES).html;
+ const childTracks = [
+ { target: { id: "title" }, track: 1 },
+ { target: { id: "logo" }, track: 3 },
+ ];
+ const { html } = unwrapElementsFromHtml(
+ wrapped,
+ { selector: '[data-hf-group="Group 1"]' },
+ childTracks,
+ );
+ const { document } = parseHTML(html);
+ expect(requireElement(document, "#title").getAttribute("data-track-index")).toBe("1");
+ expect(requireElement(document, "#logo").getAttribute("data-track-index")).toBe("3");
+ expect(requireElement(document, "#badge").hasAttribute("data-track-index")).toBe(false);
+ });
+
it("rejects members that do not share a single parent", () => {
const split = `<!doctype html><html><body><div data-composition-id="main"><div id="a" style="position:absolute;left:0;top:0"></div><section><div id="b" style="position:absolute;left:0;top:0"></div></section></div></body></html>`;
const result = wrapElementsInHtml(split, [{ id: "a" }, { id: "b" }], "Group 1", BBOX, [
diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts
index 0756132ec2..139d78ca7d 100644
--- a/packages/studio-server/src/routes/files.ts
+++ b/packages/studio-server/src/routes/files.ts
@@ -201,6 +201,7 @@ interface AtomicCutTarget {
playbackStart?: number;
playbackRate?: number;
isComposition?: boolean;
+ track?: number;
}
interface AtomicCutFileRequest {
@@ -209,6 +210,10 @@ interface AtomicCutFileRequest {
targets: AtomicCutTarget[];
}
+function isOptionalInteger(value: unknown): value is number | undefined {
+ return value === undefined || Number.isInteger(value);
+}
+
function isAtomicCutTarget(value: unknown): value is AtomicCutTarget {
if (!value || typeof value !== "object") return false;
const target = value as Partial<AtomicCutTarget>;
@@ -218,7 +223,8 @@ function isAtomicCutTarget(value: unknown): value is AtomicCutTarget {
Number.isFinite(target.splitTime) &&
Number.isFinite(target.elementStart) &&
Number.isFinite(target.elementDuration) &&
- Number(target.elementDuration) > 0
+ Number(target.elementDuration) > 0 &&
+ isOptionalInteger(target.track)
);
}
@@ -2106,6 +2112,7 @@ async function foldAtomicCutFile(
playbackStart: cut.playbackStart,
playbackRate: cut.playbackRate,
stampPlaybackStart: cut.isComposition,
+ track: cut.track,
});
if (!split.matched || !split.newId) {
return c.json(
@@ -2938,7 +2945,8 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
typeof r?.left === "number" &&
Number.isFinite(r.left) &&
typeof r?.top === "number" &&
- Number.isFinite(r.top),
+ Number.isFinite(r.top) &&
+ isOptionalInteger(r?.track),
);
if (!allNumeric) {
return c.json({ error: "bbox and rebase coordinates must be finite numbers" }, 400);
@@ -2992,16 +3000,29 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
const ctx = await resolveFileMutationContext(c, adapter, "unwrap-elements");
if ("error" in ctx) return ctx.error;
- const parsed = await parseMutationBody<{ target?: MutationTarget }>(c);
+ const parsed = await parseMutationBody<{
+ target?: MutationTarget;
+ childTracks?: Array<{ target?: MutationTarget; track?: number }>;
+ }>(c);
if ("error" in parsed) return parsed.error;
+ const rawChildTracks = parsed.body.childTracks ?? [];
+ if (!rawChildTracks.every((entry) => isOptionalInteger(entry?.track))) {
+ return c.json({ error: "childTracks track must be a finite integer" }, 400);
+ }
+ const childTracks = rawChildTracks
+ .filter((entry): entry is { target: MutationTarget; track?: number } =>
+ Boolean(entry?.target),
+ )
+ .map((entry) => ({ target: entry.target, track: entry.track }));
+
let originalContent: string;
try {
originalContent = readFileSync(ctx.absPath, "utf-8");
} catch {
return c.json({ error: "not found" }, 404);
}
- const result = unwrapElementsFromHtml(originalContent, parsed.target);
+ const result = unwrapElementsFromHtml(originalContent, parsed.target, childTracks);
if (!result.unwrapped) {
return c.json({ ok: false, changed: false, content: originalContent, path: ctx.filePath });
}
diff --git a/packages/studio/src/hooks/useAppHotkeys.test.ts b/packages/studio/src/hooks/useAppHotkeys.test.ts
index eeeb7387eb..d0d0d5e403 100644
--- a/packages/studio/src/hooks/useAppHotkeys.test.ts
+++ b/packages/studio/src/hooks/useAppHotkeys.test.ts
@@ -277,3 +277,25 @@ describe("dispatchModifierKey — Cmd+C/Cmd+V arbitration", () => {
expect(e.defaultPrevented).toBe(false);
});
});
+
+describe('dispatchPlainKey — "A" returns to select while the razor is armed', () => {
+ afterEach(() => {
+ usePlayerStore.setState({ activeTool: "select" });
+ });
+
+ it("returns to the select tool, matching CapCut's keybinding", () => {
+ usePlayerStore.setState({ activeTool: "razor" });
+ const e = press("a");
+ dispatchPlainKey(e, "a", callbacks());
+ expect(usePlayerStore.getState().activeTool).toBe("select");
+ expect(e.defaultPrevented).toBe(true);
+ });
+
+ it("does not intercept plain \"a\" when the razor isn't armed, leaving playback's seek-to-in-point live", () => {
+ usePlayerStore.setState({ activeTool: "select" });
+ const e = press("a");
+ dispatchPlainKey(e, "a", callbacks());
+ expect(usePlayerStore.getState().activeTool).toBe("select");
+ expect(e.defaultPrevented).toBe(false);
+ });
+});
diff --git a/packages/studio/src/hooks/useAppHotkeys.ts b/packages/studio/src/hooks/useAppHotkeys.ts
index 7081a301da..9241c10734 100644
--- a/packages/studio/src/hooks/useAppHotkeys.ts
+++ b/packages/studio/src/hooks/useAppHotkeys.ts
@@ -300,6 +300,18 @@ export function dispatchPlainKey(event: KeyboardEvent, key: string, cb: HotkeyCa
return;
}
+ // CapCut returns to the select tool with "A". Scoped to the razor being
+ // armed; usePlaybackKeyboard.ts's own "A" (seek to in-point) checks the
+ // same activeTool to stay out of the way.
+ if (key === "a" && !event.shiftKey && !event.altKey) {
+ const { activeTool, setActiveTool } = usePlayerStore.getState();
+ if (activeTool === "razor") {
+ event.preventDefault();
+ setActiveTool("select");
+ return;
+ }
+ }
+
if (event.key === "Escape") {
const { activeTool, selectedElementId, setActiveTool, setSelectedElementId } =
usePlayerStore.getState();
diff --git a/packages/studio/src/hooks/useDomEditSession.ts b/packages/studio/src/hooks/useDomEditSession.ts
index 6b09cf7395..ffa72cce03 100644
--- a/packages/studio/src/hooks/useDomEditSession.ts
+++ b/packages/studio/src/hooks/useDomEditSession.ts
@@ -1,7 +1,6 @@
import { useCallback } from "react";
import { trackStudioEvent } from "../utils/studioTelemetry";
import { isAudioDomElement } from "../utils/timelineInspector";
-import type { SelectElementOptions, TimelineElement } from "../player";
import type { ImportedFontAsset } from "../components/editor/fontAssets";
import type { RightPanelTab } from "../utils/studioHelpers";
import type { PatchTarget } from "../utils/sourcePatcher";
@@ -23,23 +22,13 @@ import { useKeyframeEaseCommits } from "./useKeyframeEaseCommits";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import { membersForDelete } from "./domEditDeleteMembers";
import type { RecordEditInput } from "./domEditDeleteMembers";
+import type { DomEditTimelineParams } from "./useDomSelectionTypes";
// Re-exported: the delete rule lives in its own module now, and callers (and its
// own test) have always imported it from here.
export { membersForDelete };
-export interface UseDomEditSessionParams {
- projectId: string | null;
- activeCompPath: string | null;
- compIdToSrc: Map<string, string>;
- captionEditMode: boolean;
+export interface UseDomEditSessionParams extends DomEditTimelineParams {
compositionLoading: boolean;
- previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>;
- timelineElements: TimelineElement[];
- getTimelineSelectionSet: () => ReadonlySet<string>;
- setSelectedTimelineElementId: (id: string | null, options?: SelectElementOptions) => void;
- setTimelineSelectionSet: (ids: Set<string>) => void;
- setRightCollapsed: (collapsed: boolean) => void;
- setRightPanelTab: (tab: RightPanelTab) => void;
showToast: (message: string, tone?: "error" | "info") => void;
isRecordingRef?: React.RefObject<boolean>;
refreshPreviewDocumentVersion: () => void;
@@ -326,6 +315,7 @@ export function useDomEditSession({
reloadPreview,
clearDomSelection,
forceReloadSdkSession,
+ timelineElements,
});
const handleDomEditElementDelete = useCallback(
diff --git a/packages/studio/src/hooks/useDomSelectionTypes.ts b/packages/studio/src/hooks/useDomSelectionTypes.ts
index 7cbb3d5a0e..85f21f8d86 100644
--- a/packages/studio/src/hooks/useDomSelectionTypes.ts
+++ b/packages/studio/src/hooks/useDomSelectionTypes.ts
@@ -20,10 +20,11 @@ export interface ResolveDomSelectionOptions {
exactTarget?: boolean;
}
-export interface UseDomSelectionParams {
+// Shared by every hook that needs the project/timeline/panel context a DOM
+// edit session is built around — useDomEditSession has its own superset.
+export interface DomEditTimelineParams {
projectId: string | null;
activeCompPath: string | null;
- isMasterView: boolean;
compIdToSrc: Map<string, string>;
captionEditMode: boolean;
previewIframeRef: MutableRefObject<HTMLIFrameElement | null>;
@@ -34,6 +35,10 @@ export interface UseDomSelectionParams {
setTimelineSelectionSet: (ids: Set<string>) => void;
setRightCollapsed: (collapsed: boolean) => void;
setRightPanelTab: (tab: RightPanelTab) => void;
+}
+
+export interface UseDomSelectionParams extends DomEditTimelineParams {
+ isMasterView: boolean;
previewIframe: HTMLIFrameElement | null;
refreshKey: number;
rightPanelTab: RightPanelTab;
diff --git a/packages/studio/src/hooks/useGroupCommits.test.ts b/packages/studio/src/hooks/useGroupCommits.test.ts
new file mode 100644
index 0000000000..dc3c57fad8
--- /dev/null
+++ b/packages/studio/src/hooks/useGroupCommits.test.ts
@@ -0,0 +1,98 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from "vitest";
+import type { TimelineElement } from "../player";
+import { computeGroupGeometry, resolveGroupChildTracks } from "./useGroupCommits";
+import { makeSelection } from "./domSelectionTestHarness";
+
+const timelineElement = (over: Partial<TimelineElement> = {}): TimelineElement => ({
+ id: "clip",
+ domId: "clip",
+ tag: "div",
+ start: 0,
+ duration: 4,
+ track: 0,
+ timingSource: "authored",
+ sourceFile: "index.html",
+ ...over,
+});
+
+describe("computeGroupGeometry — track threading", () => {
+ it("carries each member's authored track onto its rebase entry, so the server can pin it through the wrap", () => {
+ const elA = document.createElement("div");
+ elA.id = "clip-a";
+ const elB = document.createElement("div");
+ elB.id = "clip-b";
+ const members = [makeSelection("A", elA), makeSelection("B", elB)];
+ const timelineElements = [
+ timelineElement({ id: "clip-a", domId: "clip-a", authoredTrack: 2 }),
+ timelineElement({ id: "clip-b", domId: "clip-b" }),
+ ];
+
+ const { rebases } = computeGroupGeometry(members, timelineElements);
+
+ expect(rebases[0]?.track).toBe(2);
+ expect(rebases[1]?.track).toBe(0);
+ });
+});
+
+describe("resolveGroupChildTracks", () => {
+ it("resolves each child's authored track by DOM id, so ungroup can pin it through the unwrap", () => {
+ const group = document.createElement("div");
+ group.id = "group-1";
+ const childA = document.createElement("div");
+ childA.id = "child-a";
+ const childB = document.createElement("div");
+ childB.id = "child-b";
+ group.append(childA, childB);
+
+ const timelineElements = [
+ timelineElement({ id: "child-a", domId: "child-a", authoredTrack: 1 }),
+ timelineElement({ id: "child-b", domId: "child-b" }),
+ ];
+
+ const result = resolveGroupChildTracks(makeSelection("Group 1", group), timelineElements);
+
+ expect(result).toEqual([
+ { target: { id: "child-a", hfId: undefined }, track: 1 },
+ { target: { id: "child-b", hfId: undefined }, track: 0 },
+ ]);
+ });
+
+ it("resolves a child's track by hfId when it has no DOM id, so an unauthored ungroup child can't drift to a new row", () => {
+ const group = document.createElement("div");
+ group.id = "group-1";
+ const child = document.createElement("div");
+ child.setAttribute("data-hf-id", "hf-child-a");
+ group.append(child);
+
+ const timelineElements = [timelineElement({ hfId: "hf-child-a", authoredTrack: 3 })];
+
+ const result = resolveGroupChildTracks(makeSelection("Group 1", group), timelineElements);
+
+ expect(result).toEqual([{ target: { id: undefined, hfId: "hf-child-a" }, track: 3 }]);
+ });
+
+ it("skips a child with neither a DOM id nor an hfId", () => {
+ const group = document.createElement("div");
+ const anonymous = document.createElement("div");
+ group.append(anonymous);
+
+ const result = resolveGroupChildTracks(makeSelection("Group 1", group), []);
+
+ expect(result).toEqual([]);
+ });
+
+ it("falls back to the runtime's resolved track for an implicit child with no authoredTrack", () => {
+ const group = document.createElement("div");
+ group.id = "group-1";
+ const child = document.createElement("div");
+ child.id = "child-a";
+ group.append(child);
+
+ const timelineElements = [timelineElement({ id: "child-a", domId: "child-a", track: 3 })];
+
+ const result = resolveGroupChildTracks(makeSelection("Group 1", group), timelineElements);
+
+ expect(result).toEqual([{ target: { id: "child-a", hfId: undefined }, track: 3 }]);
+ });
+});
diff --git a/packages/studio/src/hooks/useGroupCommits.ts b/packages/studio/src/hooks/useGroupCommits.ts
index 8cd94e7c18..133623c955 100644
--- a/packages/studio/src/hooks/useGroupCommits.ts
+++ b/packages/studio/src/hooks/useGroupCommits.ts
@@ -5,13 +5,24 @@ import {
saveProjectFilesWithHistory,
type DomEditCommitBaseParams,
} from "../utils/studioFileHistory";
-import { buildDomEditPatchTarget, type DomEditSelection } from "../components/editor/domEditing";
+import {
+ buildDomEditPatchTarget,
+ readHfId,
+ type DomEditSelection,
+} from "../components/editor/domEditing";
import { studioWriteHeaders } from "../utils/studioFileVersion";
+import {
+ findMatchingTimelineElementId,
+ resolveElementTrack,
+ type ElementMatchSelection,
+} from "../utils/studioHelpers";
+import type { TimelineElement } from "../player";
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;
+ timelineElements: TimelineElement[];
}
interface PatchTarget {
@@ -24,7 +35,21 @@ interface PatchTarget {
interface GroupGeometry {
bbox: { left: number; top: number; width: number; height: number };
targets: PatchTarget[];
- rebases: Array<{ target: PatchTarget; left: number; top: number }>;
+ rebases: Array<{ target: PatchTarget; left: number; top: number; track?: number }>;
+}
+
+// The member's current resolved track (authored, or the runtime's positional-
+// index fallback). Threaded through so the server can stamp it explicitly —
+// same hazard and fix as the razor split.
+function resolveAuthoredTrack(
+ selection: ElementMatchSelection,
+ timelineElements: TimelineElement[],
+): number | undefined {
+ const id = findMatchingTimelineElementId(selection, timelineElements);
+ if (!id) return undefined;
+ const match = timelineElements.find((el) => (el.key ?? el.id) === id);
+ if (!match) return undefined;
+ return resolveElementTrack(match);
}
// Wrapper sits at the members' bounding box top-left; each member is rebased so
@@ -32,13 +57,17 @@ interface GroupGeometry {
// composition space (transforms excluded), exactly the space the rebase formula
// `left_new = left_old - W.left` operates in — GSAP x/y and offset vars are
// transform deltas and stay correct without adjustment.
-function computeGroupGeometry(members: DomEditSelection[]): GroupGeometry {
+export function computeGroupGeometry(
+ members: DomEditSelection[],
+ timelineElements: TimelineElement[],
+): GroupGeometry {
const boxes = members.map((m) => ({
target: buildDomEditPatchTarget(m),
left: m.element.offsetLeft,
top: m.element.offsetTop,
right: m.element.offsetLeft + m.element.offsetWidth,
bottom: m.element.offsetTop + m.element.offsetHeight,
+ track: resolveAuthoredTrack(m, timelineElements),
}));
const left = Math.min(...boxes.map((b) => b.left));
const top = Math.min(...boxes.map((b) => b.top));
@@ -47,10 +76,37 @@ function computeGroupGeometry(members: DomEditSelection[]): GroupGeometry {
return {
bbox: { left, top, width, height },
targets: boxes.map((b) => b.target),
- rebases: boxes.map((b) => ({ target: b.target, left: b.left - left, top: b.top - top })),
+ rebases: boxes.map((b) => ({
+ target: b.target,
+ left: b.left - left,
+ top: b.top - top,
+ track: b.track,
+ })),
};
}
+// Ungroup re-derives each child's track from the raw DOM (no DomEditSelection
+// exists per child); matches by id, falling back to hfId for a child with no
+// authored id. A child with neither keeps its current track, unstamped.
+export function resolveGroupChildTracks(
+ group: DomEditSelection,
+ timelineElements: TimelineElement[],
+): Array<{ target: PatchTarget; track?: number }> {
+ const sourceFile = group.sourceFile || "index.html";
+ const result: Array<{ target: PatchTarget; track?: number }> = [];
+ for (const child of Array.from(group.element.children)) {
+ const id = (child as HTMLElement).id || undefined;
+ const hfId = readHfId(child);
+ if (!id && !hfId) continue;
+ const track = resolveAuthoredTrack(
+ { id, hfId, sourceFile, isCompositionHost: false },
+ timelineElements,
+ );
+ result.push({ target: buildDomEditPatchTarget({ id, hfId }), track });
+ }
+ return result;
+}
+
// Shared read → mutate-route → save-with-history → reload pipeline for both
// wrap (group) and unwrap (ungroup). Mirrors the structural-mutation pattern in
// useElementLifecycleOps (delete). Returns the route's JSON, or throws.
@@ -103,7 +159,7 @@ async function commitStructuralMutation(
}
export function useGroupCommits(params: UseGroupCommitsParams) {
- const { activeCompPath, showToast, projectIdRef } = params;
+ const { activeCompPath, showToast, projectIdRef, timelineElements } = params;
const groupSelection = useCallback(
async (members: DomEditSelection[]): Promise<string | null> => {
@@ -121,7 +177,7 @@ export function useGroupCommits(params: UseGroupCommitsParams) {
// Auto-name "Group N" by the count of existing groups in the document.
const doc = members[0].element.ownerDocument;
const groupId = `Group ${doc.querySelectorAll("[data-hf-group]").length + 1}`;
- const { bbox, targets, rebases } = computeGroupGeometry(members);
+ const { bbox, targets, rebases } = computeGroupGeometry(members, timelineElements);
try {
const data = await commitStructuralMutation(
@@ -138,7 +194,7 @@ export function useGroupCommits(params: UseGroupCommitsParams) {
return null;
}
},
- [activeCompPath, projectIdRef, showToast, params],
+ [activeCompPath, projectIdRef, showToast, params, timelineElements],
);
const ungroupSelection = useCallback(
@@ -146,13 +202,14 @@ export function useGroupCommits(params: UseGroupCommitsParams) {
const pid = projectIdRef.current;
if (!pid) return;
const targetPath = group.sourceFile || activeCompPath || "index.html";
+ const childTracks = resolveGroupChildTracks(group, timelineElements);
try {
await commitStructuralMutation(
pid,
targetPath,
"unwrap-elements",
- { target: buildDomEditPatchTarget(group) },
+ { target: buildDomEditPatchTarget(group), childTracks },
"Ungroup elements",
params,
);
@@ -160,7 +217,7 @@ export function useGroupCommits(params: UseGroupCommitsParams) {
showToast(error instanceof Error ? error.message : "Failed to ungroup elements", "error");
}
},
- [activeCompPath, projectIdRef, showToast, params],
+ [activeCompPath, projectIdRef, showToast, params, timelineElements],
);
return { groupSelection, ungroupSelection };
diff --git a/packages/studio/src/player/hooks/usePlaybackKeyboard.test.ts b/packages/studio/src/player/hooks/usePlaybackKeyboard.test.ts
index dc61a3b472..92362ea117 100644
--- a/packages/studio/src/player/hooks/usePlaybackKeyboard.test.ts
+++ b/packages/studio/src/player/hooks/usePlaybackKeyboard.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment happy-dom
+// fallow-ignore-file code-duplication
import React, { act, useEffect } from "react";
import { createRoot } from "react-dom/client";
@@ -171,6 +172,39 @@ describe("usePlaybackKeyboard — keyboard layout independence (#834)", () => {
expect(spies.play).toHaveBeenCalledTimes(1);
});
+
+ it("'A' does not seek to the in-point while the razor tool is armed, so it's free for the razor's own return-to-select binding", () => {
+ const { dispatch, spies } = setupHook();
+ usePlayerStore.setState({ inPoint: 1.5, activeTool: "razor" });
+
+ act(() => {
+ dispatch(keydown({ code: "KeyA", key: "a" }));
+ });
+
+ expect(spies.seek).not.toHaveBeenCalled();
+ });
+
+ it("'A' still seeks to the in-point when the razor tool isn't armed", () => {
+ const { dispatch, spies } = setupHook();
+ usePlayerStore.setState({ inPoint: 1.5, activeTool: "select" });
+
+ act(() => {
+ dispatch(keydown({ code: "KeyA", key: "a" }));
+ });
+
+ expect(spies.seek).toHaveBeenCalledWith(1.5, { keepPlaying: true });
+ });
+
+ it("Shift+A still seeks to the in-point while the razor is armed, since only plain A exits the razor", () => {
+ const { dispatch, spies } = setupHook();
+ usePlayerStore.setState({ inPoint: 1.5, activeTool: "razor" });
+
+ act(() => {
+ dispatch(keydown({ code: "KeyA", key: "a", shiftKey: true }));
+ });
+
+ expect(spies.seek).toHaveBeenCalledWith(1.5, { keepPlaying: true });
+ });
});
describe("usePlaybackKeyboard — mute & loop shortcuts (#905)", () => {
diff --git a/packages/studio/src/player/hooks/usePlaybackKeyboard.ts b/packages/studio/src/player/hooks/usePlaybackKeyboard.ts
index 6ebb561679..3059d1ee46 100644
--- a/packages/studio/src/player/hooks/usePlaybackKeyboard.ts
+++ b/packages/studio/src/player/hooks/usePlaybackKeyboard.ts
@@ -26,6 +26,14 @@ interface UsePlaybackKeyboardParams {
seek: (time: number, options?: { keepPlaying?: boolean }) => void;
}
+// The razor tool owns plain "a" (return to select) while it's armed; this
+// can't rely on defaultPrevented since both listeners register on window and
+// fire in an order this hook doesn't control. Shift+A and Alt+A are left for
+// the in-point seek below, since only plain A means "exit the razor".
+function shouldRazorClaimPlainA(e: KeyboardEvent): boolean {
+ return !e.shiftKey && !e.altKey && usePlayerStore.getState().activeTool === "razor";
+}
+
export function usePlaybackKeyboard({
iframeRef,
shuttleDirectionRef,
@@ -79,6 +87,10 @@ export function usePlaybackKeyboard({
}
}, [play, pause]);
+ // Pre-existing dispatcher, already over the complexity gate before this
+ // branch's one-line "a" fix touched it. A real fix is a dispatch-table
+ // rewrite, out of scope here; the branch this PR changed is its own function.
+ // fallow-ignore-next-line complexity
const handlePlaybackKeyDown = useCallback(
(e: KeyboardEvent) => {
if (e.defaultPrevented) return;
@@ -161,6 +173,7 @@ export function usePlaybackKeyboard({
return;
}
if (key === "a") {
+ if (shouldRazorClaimPlainA(e)) return;
e.preventDefault();
seek(usePlayerStore.getState().inPoint ?? 0, { keepPlaying: true });
return;
diff --git a/packages/studio/src/player/lib/timelineIframeHelpers.test.ts b/packages/studio/src/player/lib/timelineIframeHelpers.test.ts
index a2d21e8e3a..143b58fb81 100644
--- a/packages/studio/src/player/lib/timelineIframeHelpers.test.ts
+++ b/packages/studio/src/player/lib/timelineIframeHelpers.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment jsdom
+// fallow-ignore-file code-duplication
import { describe, expect, it, vi } from "vitest";
import {
applyPreviewAudioFlags,
@@ -54,6 +55,27 @@ describe("buildMissingCompositionElements — hfId (R7)", () => {
expect(entry).toBeDefined();
expect(entry?.hfId).toBeUndefined();
});
+
+ it("carries the resolved track onto authoredTrack, so splitting a recovered composition host can't drift to a new row", () => {
+ const doc = makeDoc(`
+ <div data-composition-id="root">
+ <div
+ data-composition-id="scene-c"
+ data-composition-src="scenes/c.html"
+ data-track-index="2"
+ data-start="0"
+ data-duration="5"
+ ></div>
+ </div>
+ `);
+
+ const { missing } = buildMissingCompositionElements(doc, window as IframeWindow, [], 10);
+ const entry = missing[0];
+
+ expect(entry).toBeDefined();
+ expect(entry?.track).toBe(2);
+ expect(entry?.authoredTrack).toBe(2);
+ });
});
describe("setPreviewMediaVolume", () => {
diff --git a/packages/studio/src/player/lib/timelineIframeHelpers.ts b/packages/studio/src/player/lib/timelineIframeHelpers.ts
index 05c57a2a90..e3e683eb49 100644
--- a/packages/studio/src/player/lib/timelineIframeHelpers.ts
+++ b/packages/studio/src/player/lib/timelineIframeHelpers.ts
@@ -452,6 +452,7 @@ function buildMissingCompositionEntry(params: {
start: window.start,
duration: window.duration,
track: timing.trackIndex,
+ authoredTrack: timing.trackIndex,
domId: optionalNonEmpty(element.id),
hfId: optionalNonEmpty(element.getAttribute("data-hf-id")),
selector,
diff --git a/packages/studio/src/utils/razorSplitTransaction.test.ts b/packages/studio/src/utils/razorSplitTransaction.test.ts
index ea526da58c..53b4676d3c 100644
--- a/packages/studio/src/utils/razorSplitTransaction.test.ts
+++ b/packages/studio/src/utils/razorSplitTransaction.test.ts
@@ -37,6 +37,16 @@ describe("buildAtomicCutIntents", () => {
expect(intents[0].targets.map((target) => target.originalId)).toEqual(["host-a", "host-b"]);
});
+ it("carries the element's authored track onto the cut target, so both split halves stay pinned to it server-side", () => {
+ const intents = buildAtomicCutIntents([element({ authoredTrack: 2 })], 2, "index.html");
+ expect(intents[0].targets[0].track).toBe(2);
+ });
+
+ it("falls back to the resolved track when the element has no authoredTrack", () => {
+ const intents = buildAtomicCutIntents([element({ track: 3 })], 2, "index.html");
+ expect(intents[0].targets[0].track).toBe(3);
+ });
+
it("rebases each nested target into its own source-file coordinates", () => {
const intents = buildAtomicCutIntents(
[element({ start: 8, duration: 4, expandedParentStart: 6, sourceFile: "scene.html" })],
diff --git a/packages/studio/src/utils/razorSplitTransaction.ts b/packages/studio/src/utils/razorSplitTransaction.ts
index 19ab58abc8..77054df21c 100644
--- a/packages/studio/src/utils/razorSplitTransaction.ts
+++ b/packages/studio/src/utils/razorSplitTransaction.ts
@@ -4,6 +4,7 @@ import { buildPatchTarget } from "./timelineElementSplit";
import { serializeStudioFileMutations } from "./studioFileMutationCoordinator";
import { buildProjectApiPath } from "./projectRouting";
import { markStudioWriteToken } from "./studioFileVersion";
+import { resolveElementTrack } from "./studioHelpers";
type ProjectFileWriter = (path: string, content: string, expectedContent?: string) => Promise<void>;
@@ -16,6 +17,7 @@ interface CutTarget {
playbackStart?: number;
playbackRate?: number;
isComposition?: boolean;
+ track?: number;
}
interface CutFileIntent {
@@ -69,6 +71,9 @@ function buildCutTarget(
...(element.playbackStart != null ? { playbackStart: element.playbackStart } : {}),
...(element.playbackRate != null ? { playbackRate: element.playbackRate } : {}),
...(element.kind === "composition" ? { isComposition: true } : {}),
+ // Pin both halves to the current track: unstamped, the runtime's positional
+ // fallback (parseAuthoredTrack) renumbers the new sibling onto a new row.
+ track: resolveElementTrack(element),
};
}
diff --git a/packages/studio/src/utils/studioHelpers.test.ts b/packages/studio/src/utils/studioHelpers.test.ts
index 9e16a8c8ea..077c0c6b37 100644
--- a/packages/studio/src/utils/studioHelpers.test.ts
+++ b/packages/studio/src/utils/studioHelpers.test.ts
@@ -5,6 +5,7 @@ import {
findMatchingTimelineElementId,
findTimelineIdByAncestor,
resolveDroppedAssetDimensions,
+ resolveElementTrack,
resolveTimelineIdForSelection,
resolveTimelineSelectionSeekTime,
} from "./studioHelpers";
@@ -42,6 +43,13 @@ describe("findMatchingTimelineElementId", () => {
expect(findMatchingTimelineElementId({ id: "s1", sourceFile: "index.html" }, els)).toBe("s1");
});
+ it("matches by hfId when the selection has no domId, so an element with no authored id can still be found", () => {
+ const els = [el({ id: "hf-1", domId: undefined, hfId: "hf-1", sourceFile: "index.html" })];
+ expect(
+ findMatchingTimelineElementId({ id: undefined, hfId: "hf-1", sourceFile: "index.html" }, els),
+ ).toBe("hf-1");
+ });
+
it("returns a qualified id for a sub-comp child with no matching timeline element", () => {
const els = [el({ id: "s3", domId: "s3", sourceFile: "index.html" })];
expect(
@@ -199,3 +207,13 @@ describe("resolveDroppedAssetDimensions", () => {
expect(load).toHaveBeenCalledOnce();
});
});
+
+describe("resolveElementTrack", () => {
+ it("rounds an authored track", () => {
+ expect(resolveElementTrack({ authoredTrack: 2.4, track: 0 })).toBe(2);
+ });
+
+ it("falls back to the resolved track, rounded, when nothing was authored", () => {
+ expect(resolveElementTrack({ authoredTrack: undefined, track: 3.6 })).toBe(4);
+ });
+});
diff --git a/packages/studio/src/utils/studioHelpers.ts b/packages/studio/src/utils/studioHelpers.ts
index 8531768a55..a5e4496fb8 100644
--- a/packages/studio/src/utils/studioHelpers.ts
+++ b/packages/studio/src/utils/studioHelpers.ts
@@ -126,9 +126,15 @@ export function getHistoryShortcutLabel(action: "undo" | "redo"): string {
return action === "undo" ? `${modifier}+Z` : `${modifier}+Shift+Z`;
}
-type ElementMatchSelection = Pick<
+export type ElementMatchSelection = Pick<
DomEditSelection,
- "id" | "selector" | "selectorIndex" | "sourceFile" | "compositionSrc" | "isCompositionHost"
+ | "id"
+ | "hfId"
+ | "selector"
+ | "selectorIndex"
+ | "sourceFile"
+ | "compositionSrc"
+ | "isCompositionHost"
>;
function matchesByDomId(
@@ -142,6 +148,17 @@ function matchesByDomId(
);
}
+function matchesByHfId(
+ selection: ElementMatchSelection,
+ element: TimelineElement,
+ selectionSourceFile: string,
+): boolean {
+ if (!selection.hfId) return false;
+ return (
+ element.hfId === selection.hfId && (element.sourceFile || "index.html") === selectionSourceFile
+ );
+}
+
function matchesByCompositionHost(
selection: ElementMatchSelection,
element: TimelineElement,
@@ -172,14 +189,22 @@ export function findMatchingTimelineElementId(
// scan let `.find()` stop at an EARLIER, unrelated host that merely shares
// the compositionSrc, before the scan ever reached the correct id/selector
// match further down the list — collapsing every repeated host to the
- // first one. Try id, then selector, across the WHOLE list first; only fall
- // back to the coarser compositionSrc-only match when neither identifies a
- // specific element.
+ // first one. Try id, then hfId, then selector, across the WHOLE list
+ // first; only fall back to the coarser compositionSrc-only match when
+ // none of them identifies a specific element.
const byId = selection.id
? elements.find((el) => matchesByDomId(selection, el, selectionSourceFile))
: undefined;
if (byId) return byId.key ?? byId.id;
+ // hfId is the stable content-hash id every element gets regardless of
+ // whether it has a real DOM id — the only correlator for an element like
+ // an ungroup child that has neither an authored id nor a selector.
+ const byHfId = selection.hfId
+ ? elements.find((el) => matchesByHfId(selection, el, selectionSourceFile))
+ : undefined;
+ if (byHfId) return byHfId.key ?? byHfId.id;
+
const bySelector = selection.selector
? elements.find((el) => matchesBySelector(selection, el))
: undefined;
@@ -198,6 +223,17 @@ export function findMatchingTimelineElementId(
return null;
}
+// The element's track: authored if given, else the runtime's already-resolved
+// fallback — always rounded to an integer index either way. Shared by the
+// group/ungroup and razor-split flows so they can't drift out of sync again.
+export function resolveElementTrack(
+ element: Pick<TimelineElement, "authoredTrack" | "track">,
+): number {
+ return Math.round(
+ Number.isFinite(element.authoredTrack) ? (element.authoredTrack as number) : element.track,
+ );
+}
+
/**
* A selected DOM node may be a static descendant of a clip (e.g. the `.num` text
* inside a `#stat1` card) — not a timeline element itself. Walk up to the nearest