Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): dropping an asset between or above timeline rows opens a new row (#4160)
Miguel Ángelc2ca2291cab6
diff --git a/packages/studio/src/components/EditorShell.tsx b/packages/studio/src/components/EditorShell.tsxindex a7cbec2941..f7b2b9295b 100644--- a/packages/studio/src/components/EditorShell.tsx+++ b/packages/studio/src/components/EditorShell.tsx@@ -16,12 +16,12 @@ import type { BlockPreviewInfo } from "./sidebar/BlocksTab";import type { GestureRecordingState } from "./editor/GestureRecordControl";import { useTimelineSelectionPreviewSync } from "../hooks/useTimelineSelectionPreviewSync";import { StudioAgentTools } from "../webmcp/StudioAgentTools";+import type { TimelineDropPlacement } from "../player/components/timelineCallbacks";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.diff --git a/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsx b/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsxindex 623a0c6abd..c1ae287345 100644--- a/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsx+++ b/packages/studio/src/hooks/useTimelineAssetDropOps.test.tsx@@ -5,6 +5,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { useTimelineAssetDropOps } from "./useTimelineAssetDropOps";import { mountReactHarness } from "./domSelectionTestHarness";import { usePlayerStore } from "../player/store/playerStore";+import type { TimelineElement } from "../player";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -19,6 +20,7 @@ type DropFn = ReturnType<typeof useTimelineAssetDropOps>["handleTimelineAssetDrofunction renderDropHook(sourceContent: string,writeProjectFile: (path: string, content: string, expectedContent?: string) => Promise<void>,+ timelineElements: TimelineElement[] = [],) {vi.stubGlobal("fetch",@@ -29,7 +31,7 @@ function renderDropHook(const { handleTimelineAssetDrop } = useTimelineAssetDropOps({projectIdRef: { current: "project" },activeCompPath: "index.html",- timelineElements: [],+ timelineElements,showToast: vi.fn(),writeProjectFile,recordEdit: vi.fn().mockResolvedValue(undefined),@@ -84,4 +86,42 @@ describe("useTimelineAssetDropOps handleTimelineAssetDrop", () => {expect(usePlayerStore.getState().selectedElementId).toBe("index.html#clip");});++ it("measures the insert row against the visible rows, not clips the timeline hides", async () => {+ const clip = (id: string, track: number): TimelineElement => ({+ id,+ key: id,+ tag: "div",+ start: 0,+ duration: 2,+ track,+ authoredTrack: track,+ hfId: `hf-${id}`,+ domId: id,+ });+ const source = [+ '<main data-composition-id="scene" data-duration="10" data-width="1920" data-height="1080">',+ ...["a:0", "hidden:1", "b:2"].map((t) => {+ const [id, track] = t.split(":");+ return `<div data-hf-id="hf-${id}" id="${id}" data-start="0" data-track-index="${track}"></div>`;+ }),+ "</main>",+ ].join("\n");+ usePlayerStore.getState().setTopLevelIds(new Set(["a", "b"]));+ const writeProjectFile = vi.fn().mockResolvedValue(undefined);+ const getDrop = renderDropHook(source, writeProjectFile, [+ clip("a", 0),+ clip("hidden", 1),+ clip("b", 2),+ ]);++ await act(async () => {+ await getDrop()("clip.mp4", { start: 1, track: 1, insertRow: 1, trackOrder: [0, 2] }, 2);+ });++ const [, written] = writeProjectFile.mock.calls[0] as [string, string];+ expect(written).toContain('id="b" data-start="0" data-track-index="2"');+ expect(written).toContain('id="hidden" data-start="0" data-track-index="1"');+ expect(written).toMatch(/<video id="clip"[^>]*data-track-index="1"/);+ });});diff --git a/packages/studio/src/hooks/useTimelineAssetDropOps.ts b/packages/studio/src/hooks/useTimelineAssetDropOps.tsindex 3b2c30fd7f..82d3c4ad1b 100644--- a/packages/studio/src/hooks/useTimelineAssetDropOps.ts+++ b/packages/studio/src/hooks/useTimelineAssetDropOps.ts@@ -4,6 +4,8 @@// 600-line cap.import { useCallback, type MutableRefObject, type RefObject } from "react";import type { TimelineElement } from "../player";+import type { TimelineDropPlacement } from "../player/components/timelineCallbacks";+import { resolveDropTrack } from "../utils/timelineDropTrackInsert";import {buildTimelineAssetId,buildTimelineAssetInsertHtml,@@ -23,6 +25,18 @@ import { commitTimelineCompositionInsertion } from "../utils/timelineCompositionimport { extendRootDurationInSource } from "../utils/rootDuration";import { deriveTimelineStoreKeyForDomId } from "../player/lib/timelineElementHelpers";import { selectAndRevealTimelineElement } from "../player/components/timelineDropReveal";+import { selectTimelineRowElements } from "../player/hooks/useTimelineRowElements";+import { usePlayerStore } from "../player/store/playerStore";++/** The first uploaded file opens the new track (if asked); the rest land on the lane it landed on. */+function fileDropPlacement(+ index: number,+ next: { start: number; track: number },+ dropped: TimelineDropPlacement | undefined,+ landedTrack: number | undefined,+): TimelineDropPlacement {+ return index === 0 ? { ...dropped, ...next } : { ...next, track: landedTrack ?? next.track };+}interface UseTimelineAssetDropOpsOptions {projectIdRef: MutableRefObject<string | null>;@@ -52,16 +66,16 @@ export function useTimelineAssetDropOps({observeProjectFileVersion,}: UseTimelineAssetDropOpsOptions) {// fallow-ignore-next-line complexity- const handleTimelineAssetDrop = useCallback(+ const dropAssetAt = useCallback(// fallow-ignore-next-line complexityasync (assetPath: string,- placement: Pick<TimelineElement, "start" | "track">,+ placement: TimelineDropPlacement,durationOverride?: number,- ) => {+ ): Promise<number | undefined> => {if (isRecordingRef?.current) {showToast("Cannot edit timeline while recording", "error");- return;+ return undefined;}const pid = projectIdRef.current;if (!pid) throw new Error("No active project");@@ -69,7 +83,7 @@ export function useTimelineAssetDropOps({const kind = getTimelineAssetKind(assetPath);if (!kind) {showToast("Only image, video, and audio assets can be dropped onto the timeline.");- return;+ return undefined;}const targetPath = activeCompPath || "index.html";@@ -91,9 +105,24 @@ export function useTimelineAssetDropOps({);const newElementZIndex = Math.max(1, relevantElements.length + 1);+ const { source: sourceWithRoom, track } = resolveDropTrack({+ source: originalContent,+ // insertRow counts the rows the timeline shows, so plan against those.+ elements: selectTimelineRowElements(+ relevantElements,+ usePlayerStore.getState().topLevelIds,+ ),+ placement,+ dropped: {+ id: newId,+ tag: kind === "image" ? "img" : kind,+ start: normalizedStart,+ duration: normalizedDuration,+ },+ });const patchedContent = extendRootDurationInSource(insertTimelineAssetIntoSource(- originalContent,+ sourceWithRoom,buildTimelineAssetInsertHtml({id: newId,hfId: `hf-${generateId()}`,@@ -101,7 +130,7 @@ export function useTimelineAssetDropOps({kind,start: normalizedStart,duration: normalizedDuration,- track: placement.track,+ track,zIndex: newElementZIndex,geometry: fitTimelineAssetGeometry(null,@@ -125,10 +154,12 @@ export function useTimelineAssetDropOps({selectAndRevealTimelineElement(deriveTimelineStoreKeyForDomId(newId, targetPath));forceReloadSdkSession?.();reloadPreview();+ return track;} catch (error) {const message =error instanceof Error ? error.message : "Failed to drop asset onto timeline";showToast(message);+ return undefined;}},[@@ -144,10 +175,17 @@ export function useTimelineAssetDropOps({],);+ const handleTimelineAssetDrop = useCallback(+ async (assetPath: string, placement: TimelineDropPlacement, durationOverride?: number) => {+ await dropAssetAt(assetPath, placement, durationOverride);+ },+ [dropAssetAt],+ );+// fallow-ignore-next-line complexityconst handleTimelineFileDrop = useCallback(// fallow-ignore-next-line complexity- async (files: File[], placement?: Pick<TimelineElement, "start" | "track">) => {+ async (files: File[], placement?: TimelineDropPlacement) => {if (isRecordingRef?.current) {showToast("Cannot edit timeline while recording", "error");return;@@ -166,15 +204,18 @@ export function useTimelineAssetDropOps({placement ?? { start: 0, track: 0 },durations,);+ let landedTrack: number | undefined;for (const [index, assetPath] of uploaded.entries()) {- await handleTimelineAssetDrop(+ const next = placements[index] ?? placements[0];+ const track = await dropAssetAt(assetPath,- placements[index] ?? placements[0],+ fileDropPlacement(index, next, placement, landedTrack),durations[index],);+ if (index === 0) landedTrack = track;}},- [handleTimelineAssetDrop, projectIdRef, uploadProjectFiles, isRecordingRef, showToast],+ [dropAssetAt, projectIdRef, uploadProjectFiles, isRecordingRef, showToast],);const handleTimelineCompositionDrop = useCallback(diff --git a/packages/studio/src/player/components/TimelineCanvas.tsx b/packages/studio/src/player/components/TimelineCanvas.tsxindex 34caaeb0c8..5c81a60f59 100644--- a/packages/studio/src/player/components/TimelineCanvas.tsx+++ b/packages/studio/src/player/components/TimelineCanvas.tsx@@ -2,6 +2,7 @@ import { memo } from "react";import { TimelineRuler } from "./TimelineRuler";import { PlayheadIndicator } from "./PlayheadIndicator";import type { TimelineRangeSelection } from "./timelineEditing";+import type { TimelineDropPlacement } from "./timelineCallbacks";import {RULER_H,CLIP_Y,@@ -40,7 +41,7 @@ interface TimelineCanvasProps extends TimelineLaneBaseProps {/** Gap strips: loud on gap-menu-row hover, quiet on the selected clip's lane. */laneGapStrips: TimelineLaneGapStrips[];/** Landing spot of an outside drag in progress, or null. */- dropPreview: { start: number; track: number } | null;+ dropPreview: TimelineDropPlacement | null;}// A dropped clip's length is unknown until it lands; the preview shows a default.@@ -55,6 +56,8 @@ export const TimelineCanvas = memo(function TimelineCanvas(props: TimelineCanvas: -1;// A track not in the order is a new track, drawn one row past the last lane.const dropRowIndex = dropTrackIndex < 0 ? displayTrackOrder.length : dropTrackIndex;+ const insertLineRow =+ (draggedClip?.started ? draggedClip.insertRow : null) ?? props.dropPreview?.insertRow ?? null;const draggedRowHeight = getTimelineRowHeight(draggedRowIndex, props.rowHeights);// A clip bar in an EXPANDED row still renders at TRACK_H (the property lanes// occupy the rest of the row — see TimelineLanes' clipHeight), so the drag@@ -183,7 +186,7 @@ export const TimelineCanvas = memo(function TimelineCanvas(props: TimelineCanvas{/* Drop preview: where an asset or file dragged in from outside will land(a row past the last lane means a new track). */}- {props.dropPreview && (+ {props.dropPreview && props.dropPreview.insertRow == null && (<divaria-hidden="true"data-testid="timeline-drop-preview"@@ -203,11 +206,12 @@ export const TimelineCanvas = memo(function TimelineCanvas(props: TimelineCanvas{/* 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 && (+ {insertLineRow != null && (<div+ data-testid="timeline-insert-line"className="absolute pointer-events-none"style={{- top: getTimelineRowTop(draggedClip.insertRow, props.rowHeights) - 0.5,+ top: getTimelineRowTop(insertLineRow, props.rowHeights) - 0.5,left: props.contentOrigin,width: props.trackContentWidth,height: 1,diff --git a/packages/studio/src/player/components/timelineCallbacks.ts b/packages/studio/src/player/components/timelineCallbacks.tsindex 67b347a96b..ad206205e6 100644--- a/packages/studio/src/player/components/timelineCallbacks.ts+++ b/packages/studio/src/player/components/timelineCallbacks.ts@@ -14,20 +14,20 @@ export interface TimelinePropertyGroupKeyframeToggle {remove: boolean;}+/** Where an outside drop lands; `insertRow` opens a new track at that row boundary of `trackOrder`. */+export type TimelineDropPlacement = { start: number; track: number } & (+ | { insertRow?: null; trackOrder?: undefined }+ | { insertRow: number; trackOrder: readonly number[] }+);+/*** Shared callback signatures for timeline editing operations.* Used by NLELayout, Timeline, and any component that passes through* the standard set of timeline mutation handlers.*/export interface TimelineDropCallbacks {- onFileDrop?: (- files: File[],- placement?: { start: number; track: number },- ) => Promise<void> | void;- onAssetDrop?: (- assetPath: string,- placement: { start: number; track: number },- ) => Promise<void> | void;+ onFileDrop?: (files: File[], placement?: TimelineDropPlacement) => Promise<void> | void;+ onAssetDrop?: (assetPath: string, placement: TimelineDropPlacement) => Promise<void> | void;onBlockDrop?: (blockName: string,placement: { start: number; track: number },diff --git a/packages/studio/src/player/components/timelineDragDrop.test.tsx b/packages/studio/src/player/components/timelineDragDrop.test.tsxindex d6a589d920..73aecc7c5c 100644--- a/packages/studio/src/player/components/timelineDragDrop.test.tsx+++ b/packages/studio/src/player/components/timelineDragDrop.test.tsx@@ -6,7 +6,8 @@ import { afterEach, describe, expect, it, vi, type Mock } from "vitest";import { TIMELINE_ASSET_MIME, TIMELINE_BLOCK_MIME } from "../../utils/timelineAssetDrop";import { usePlayerStore } from "../store/playerStore";import { createTimelineRowGeometry } from "./timelineLayout";-import { useTimelineAssetDrop } from "./timelineDragDrop";+import { resolveDropInsertRow, useTimelineAssetDrop } from "./timelineDragDrop";+import { getTimelineRowTop, TRACK_H } from "./timelineLayout";import { configureTimelineTestViewport } from "./timelineTestViewport";(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -252,3 +253,62 @@ describe("useTimelineAssetDrop", () => {act(() => view.root.unmount());});});++describe("resolveDropInsertRow", () => {+ const rows = [TRACK_H, TRACK_H, TRACK_H];+ it("arms a new track at the boundary between two lanes", () => {+ expect(resolveDropInsertRow(getTimelineRowTop(1, rows), rows, 3)).toBe(1);+ });+ it("arms a new track above the first lane", () => {+ expect(resolveDropInsertRow(getTimelineRowTop(0, rows) - 4, rows, 3)).toBe(0);+ });+ it("stays on the lane when the pointer is over its middle", () => {+ expect(resolveDropInsertRow(getTimelineRowTop(1, rows) + TRACK_H / 2, rows, 3)).toBeNull();+ });+ it("leaves the area below the last lane to the append path", () => {+ expect(resolveDropInsertRow(getTimelineRowTop(2, rows) + TRACK_H + 4, rows, 3)).toBeNull();+ });+ it("never arms on an empty timeline", () => {+ expect(resolveDropInsertRow(80, [], 0)).toBeNull();+ });+});++describe("useTimelineAssetDrop new-track drops", () => {+ it("previews and commits an insert row for an asset dropped between lanes", () => {+ const onAssetDrop = vi.fn();+ const view = renderHarness(onAssetDrop);+ const transfer = assetTransfer(JSON.stringify({ path: "assets/a.png" }));+ const y = getTimelineRowTop(1) + 1;++ act(() => view.api.handleAssetDragOver(dragEvent(transfer, 400, y)));+ expect(view.api.dropPreview).toMatchObject({ start: 10, insertRow: 1 });+ act(() => view.api.handleAssetDrop(dragEvent(transfer, 400, y)));+ expect(onAssetDrop).toHaveBeenCalledWith(+ "assets/a.png",+ expect.objectContaining({+ start: 10,+ insertRow: 1,+ trackOrder: Array.from({ length: 100 }, (_, index) => index),+ }),+ );+ act(() => view.root.unmount());+ });++ it("does not ask a block drop to insert a track", () => {+ const onBlockDrop = vi.fn();+ const view = renderHarness(vi.fn(), 1, { onBlockDrop });+ const transfer: DropTransfer = {+ types: [TIMELINE_BLOCK_MIME],+ files: [],+ dropEffect: "none",+ getData: (type) => (type === TIMELINE_BLOCK_MIME ? JSON.stringify({ name: "b" }) : ""),+ };+ const y = getTimelineRowTop(1) + 1;+ act(() => {+ view.api.handleAssetDragOver(dragEvent(transfer, 400, y));+ view.api.handleAssetDrop(dragEvent(transfer, 400, y));+ });+ expect(onBlockDrop).toHaveBeenCalledWith("b", { start: 10, track: 1 });+ act(() => view.root.unmount());+ });+});diff --git a/packages/studio/src/player/components/timelineDragDrop.ts b/packages/studio/src/player/components/timelineDragDrop.tsindex e7ea5e37e7..f3169f2e43 100644--- a/packages/studio/src/player/components/timelineDragDrop.ts+++ b/packages/studio/src/player/components/timelineDragDrop.ts@@ -4,8 +4,14 @@ import {parseTimelineCompositionPayload,TIMELINE_COMPOSITION_MIME,} from "../../utils/timelineCompositionDrop";-import { resolveTimelineAssetDrop, type TimelineRowGeometry } from "./timelineLayout";-import type { TimelineDropCallbacks } from "./timelineCallbacks";+import {+ getTimelineInsertBoundaryBand,+ getTimelineRowPositionFromY,+ resolveTimelineAssetDrop,+ type TimelineRowGeometry,+} from "./timelineLayout";+import { resolveInsertRow } from "./timelineCollision";+import type { TimelineDropCallbacks, TimelineDropPlacement } from "./timelineCallbacks";import {applyTimelineAutoScrollStep,resolveTimelineAutoScrollLoopAction,@@ -20,8 +26,6 @@ interface UseTimelineAssetDropOptions extends TimelineDropCallbacks {sessionEpoch: 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@@ -30,8 +34,8 @@ type TimelinePlacement = { start: number; track: number };function applyJsonDropPayload(raw: string,pick: (parsed: Record<string, string | undefined>) => string | undefined,- apply: (value: string, placement: TimelinePlacement) => void,- placement: TimelinePlacement,+ apply: (value: string, placement: TimelineDropPlacement) => void,+ placement: TimelineDropPlacement,): boolean {try {const value = pick(JSON.parse(raw) as Record<string, string | undefined>);@@ -43,6 +47,40 @@ function applyJsonDropPayload(}}+/** Only file and asset drops are written by the asset op that can open a track. */+function canInsertTrackFor(types: readonly string[]): boolean {+ return types.includes("Files") || types.includes(TIMELINE_ASSET_MIME);+}++/** The row boundary a pointer at `contentY` arms for a new track, or null over a lane's middle. */+export function resolveDropInsertRow(+ contentY: number,+ rowHeights: readonly number[] | undefined,+ trackCount: number,+): number | null {+ if (trackCount === 0) return null;+ const { rowFloat, rowHeight } = getTimelineRowPositionFromY(contentY, rowHeights);+ // Past the last lane the drop already appends a track (getDefaultDroppedTrack).+ if (rowFloat >= trackCount) return null;+ return resolveInsertRow(rowFloat, trackCount, getTimelineInsertBoundaryBand(rowHeight));+}++function placeDrop(+ geometry: Parameters<typeof resolveTimelineAssetDrop>[0],+ clientX: number,+ clientY: number,+ // Blocks and compositions are written by their own installers, which only take a track.+ canInsertTrack: boolean,+): TimelineDropPlacement {+ const placement = resolveTimelineAssetDrop(geometry, clientX, clientY);+ if (!canInsertTrack) return placement;+ const contentY = clientY - geometry.rectTop + geometry.scrollTop;+ const insertRow = resolveDropInsertRow(contentY, geometry.rowHeights, geometry.trackOrder.length);+ return insertRow == null+ ? placement+ : { ...placement, insertRow, trackOrder: geometry.trackOrder };+}+function invokeDropCallback(callback: () => Promise<void> | void): void {try {void Promise.resolve(callback()).catch(() => undefined);@@ -54,7 +92,7 @@ function invokeDropCallback(callback: () => Promise<void> | void): void {function applyFileDrop(transfer: DataTransfer,onFileDrop: TimelineDropCallbacks["onFileDrop"],- placement: TimelinePlacement,+ placement: TimelineDropPlacement,): boolean {if (!onFileDrop || transfer.files.length === 0) return false;invokeDropCallback(() => onFileDrop(Array.from(transfer.files), placement));@@ -65,8 +103,8 @@ function applyTypedJsonDrop(transfer: DataTransfer,mime: string,field: "name" | "path",- apply: ((value: string, placement: TimelinePlacement) => Promise<void> | void) | undefined,- placement: TimelinePlacement,+ apply: ((value: string, placement: TimelineDropPlacement) => Promise<void> | void) | undefined,+ placement: TimelineDropPlacement,): boolean {if (!apply || !Array.from(transfer.types).includes(mime)) return false;const payload = transfer.getData(mime);@@ -98,7 +136,7 @@ export function useTimelineAssetDrop({sessionEpoch,}: UseTimelineAssetDropOptions) {const [isDragOver, setIsDragOver] = useState(false);- const [dropPreview, setDropPreview] = useState<TimelinePlacement | null>(null);+ const [dropPreview, setDropPreview] = useState<TimelineDropPlacement | null>(null);const dragPointerRef = useRef<{ clientX: number; clientY: number; sessionEpoch: number } | null>(null,);@@ -144,10 +182,10 @@ export function useTimelineAssetDrop({);const resolveDropPlacement = useCallback(- (clientX: number, clientY: number): TimelinePlacement => {+ (clientX: number, clientY: number, canInsertTrack: boolean): TimelineDropPlacement => {const scroll = scrollRef.current;const rect = scroll?.getBoundingClientRect();- return resolveTimelineAssetDrop(+ return placeDrop({rectLeft: rect?.left ?? 0,rectTop: rect?.top ?? 0,@@ -160,6 +198,7 @@ export function useTimelineAssetDrop({},clientX,clientY,+ canInsertTrack,);},[scrollRef, ppsRef, trackOrderRef, rowGeometryRef, contentOrigin],@@ -177,9 +216,11 @@ export function useTimelineAssetDrop({e.dataTransfer.dropEffect = "copy";activeDropEpochRef.current = sessionEpoch;setIsDragOver(true);- const next = resolveDropPlacement(e.clientX, e.clientY);+ const next = resolveDropPlacement(e.clientX, e.clientY, canInsertTrackFor(types));setDropPreview((prev) =>- prev?.start === next.start && prev.track === next.track ? prev : next,+ prev?.start === next.start && prev.track === next.track && prev.insertRow === next.insertRow+ ? prev+ : next,);syncAutoScroll(e.clientX, e.clientY);},@@ -208,7 +249,8 @@ export function useTimelineAssetDrop({const canCommit = activeDropEpochRef.current === sessionEpoch;clearDropPreview();if (!canCommit) return;- const placement = resolveDropPlacement(e.clientX, e.clientY);+ const types = Array.from(e.dataTransfer.types);+ const placement = resolveDropPlacement(e.clientX, e.clientY, canInsertTrackFor(types));const compositionPayload = parseTimelineCompositionPayload(e.dataTransfer.getData(TIMELINE_COMPOSITION_MIME),diff --git a/packages/studio/src/utils/timelineDropTrackInsert.test.ts b/packages/studio/src/utils/timelineDropTrackInsert.test.tsnew file mode 100644index 0000000000..d8bea4ee83--- /dev/null+++ b/packages/studio/src/utils/timelineDropTrackInsert.test.ts@@ -0,0 +1,134 @@+import { describe, expect, it } from "vitest";+import type { TimelineElement } from "../player";+import {+ applyTrackRenumbers,+ planDropTrackInsert,+ resolveDropTrack,+} from "./timelineDropTrackInsert";++function clip(id: string, track: number, start: number): TimelineElement {+ return {+ id,+ key: id,+ tag: "div",+ start,+ duration: 2,+ track,+ authoredTrack: track,+ hfId: `hf-${id}`,+ domId: id,+ // Main-document elements carry no sourceFile, as in production.+ };+}++const trackOrder = [0, 1, 2];+const dropped = { id: "new", tag: "img", start: 5, duration: 3 };+const elements = [clip("a", 0, 0), clip("b", 1, 0), clip("c", 2, 0)];+const source = elements+ .map(+ (e) =>+ `<div data-hf-id="${e.hfId}" id="${e.id}" data-start="0" data-track-index="${e.track}"></div>`,+ )+ .join("\n");++describe("planDropTrackInsert", () => {+ it("opens a lane between two rows and pushes the lanes below down", () => {+ const plan = planDropTrackInsert({ elements, trackOrder, insertRow: 1, dropped });+ expect(plan?.track).toBe(1);+ expect(plan?.renumbers.map((r) => [r.element.id, r.track])).toEqual([+ ["b", 2],+ ["c", 3],+ ]);+ });++ it("opens a lane above the first row", () => {+ const plan = planDropTrackInsert({ elements, trackOrder, insertRow: 0, dropped });+ expect(plan?.track).toBe(0);+ expect(plan?.renumbers.map((r) => [r.element.id, r.track])).toEqual([+ ["a", 1],+ ["b", 2],+ ["c", 3],+ ]);+ });++ it("still renumbers when the peers' own sourceFile is a real path, not undefined", () => {+ const subComp = elements.map((e) => ({ ...e, sourceFile: "sub.html" }));+ const plan = planDropTrackInsert({ elements: subComp, trackOrder, insertRow: 1, dropped });+ expect(plan?.track).toBe(1);+ expect(plan?.renumbers.map((r) => [r.element.id, r.track])).toEqual([+ ["b", 2],+ ["c", 3],+ ]);+ });+});++describe("planDropTrackInsert against the display row order", () => {+ it("counts an audio-group anchor row the way a clip drag does", () => {+ // Rows shown: group anchor (-0.5), track 0, track 1. Row boundary 2 is between 0 and 1.+ const grouped = elements.slice(0, 2).map((e) => (e.id === "a" ? { ...e, audioGroup: "g" } : e));+ const plan = planDropTrackInsert({+ elements: grouped,+ trackOrder: [-0.5, 0, 1],+ insertRow: 2,+ dropped,+ });+ expect(plan?.track).toBe(1);+ expect(plan?.renumbers.map((r) => [r.element.id, r.track])).toEqual([["b", 2]]);+ });+});++describe("applyTrackRenumbers", () => {+ it("rewrites only the renumbered clips' data-track-index", () => {+ const plan = planDropTrackInsert({ elements, trackOrder, insertRow: 1, dropped });+ const out = applyTrackRenumbers(source, plan!);+ const tracks = [...out.matchAll(/id="(\w)"[^>]*data-track-index="(\d+)"/g)].map((m) => [+ m[1],+ +m[2],+ ]);+ expect(tracks).toEqual([+ ["a", 0],+ ["b", 2],+ ["c", 3],+ ]);+ });++ it("throws when a clip's opening tag is missing", () => {+ const plan = planDropTrackInsert({ elements, trackOrder, insertRow: 1, dropped });+ expect(() => applyTrackRenumbers("<div></div>", plan!)).toThrow(/Cannot renumber/);+ });+});++describe("resolveDropTrack", () => {+ it("keeps the aimed lane and the source when no insert is asked for", () => {+ const out = resolveDropTrack({+ source,+ elements,+ placement: { track: 2 },+ dropped,+ });+ expect(out).toEqual({ source, track: 2 });+ });++ it("returns the new lane and the source with the lanes below pushed down", () => {+ const out = resolveDropTrack({+ source,+ elements,+ placement: { track: 1, insertRow: 1, trackOrder },+ dropped,+ });+ expect(out.track).toBe(1);+ expect(out.source).toContain('id="b" data-start="0" data-track-index="2"');+ });++ it("refuses to insert when a locked clip would have to move", () => {+ const locked = elements.map((e) => (e.id === "b" ? { ...e, timelineLocked: true } : e));+ expect(() =>+ resolveDropTrack({+ source,+ elements: locked,+ placement: { track: 1, insertRow: 1, trackOrder },+ dropped,+ }),+ ).toThrow(/locked/);+ });+});diff --git a/packages/studio/src/utils/timelineDropTrackInsert.ts b/packages/studio/src/utils/timelineDropTrackInsert.tsnew file mode 100644index 0000000000..ed2cc2bfc3--- /dev/null+++ b/packages/studio/src/utils/timelineDropTrackInsert.ts@@ -0,0 +1,83 @@+import type { TimelineElement } from "../player";+import { layoutAfterTrackInsert } from "../player/components/timelineDragLanding";+import { canMoveTimelineElement } from "../player/components/timelineAuthoredMoveTarget";+import type { TimelineDropPlacement } from "../player/components/timelineCallbacks";+import { applyPatchByTarget, readAttributeByTarget } from "./sourcePatcher";+import { buildPatchTarget } from "../hooks/timelineEditingHelpers";+import { formatTimelineAttributeNumber } from "../player/components/timelineEditing";++export interface DropTrackInsertPlan {+ /** Lane the dropped clip is written on. */+ track: number;+ /** Existing clips whose lane changes to make room. */+ renumbers: Array<{ element: TimelineElement; track: number }>;+}++/** Plan a new lane at boundary `insertRow` with the renumber a clip drag into a gutter uses.+ * Null when a locked clip would have to move. */+export function planDropTrackInsert(input: {+ elements: TimelineElement[];+ /** The row order the timeline shows (anchor rows included), which `insertRow` indexes. */+ trackOrder: readonly number[];+ insertRow: number;+ dropped: Pick<TimelineElement, "id" | "tag" | "start" | "duration">;+}): DropTrackInsertPlan | null {+ const { elements, trackOrder, insertRow, dropped } = input;+ const newElement: TimelineElement = {+ ...dropped,+ key: dropped.id,+ // Parked on an existing lane so it adds no lane of its own to the topology.+ track: elements[0]?.track ?? 0,+ // sameSourceFile compares this raw field: borrow the peers' value, not the resolved path.+ sourceFile: elements[0]?.sourceFile,+ };+ const layout = layoutAfterTrackInsert(newElement, dropped.start, insertRow, null, {+ elements: [...elements, newElement],+ trackOrder: [...trackOrder],+ });+ if (!layout) return null;+ const byKey = new Map(elements.map((e) => [e.key ?? e.id, e]));+ const renumbers: DropTrackInsertPlan["renumbers"] = [];+ for (const norm of layout.normalized) {+ const key = norm.key ?? norm.id;+ if (key === dropped.id) continue;+ const src = byKey.get(key);+ if (!src || norm.track === (src.authoredTrack ?? src.track)) continue;+ if (!canMoveTimelineElement(src)) return null;+ renumbers.push({ element: src, track: norm.track });+ }+ const track = layout.normalized.find((n) => (n.key ?? n.id) === dropped.id)?.track;+ return track == null ? null : { track, renumbers };+}++/** Rewrite `data-track-index` on each renumbered clip's opening tag, via the shared source patcher. */+export function applyTrackRenumbers(source: string, plan: DropTrackInsertPlan): string {+ let out = source;+ for (const { element, track } of plan.renumbers) {+ const target = buildPatchTarget(element);+ if (!target || readAttributeByTarget(out, target, "track-index") === undefined) {+ throw new Error(`Cannot renumber the track of "${element.id}" in the source`);+ }+ out = applyPatchByTarget(out, target, {+ type: "attribute",+ property: "track-index",+ value: formatTimelineAttributeNumber(track),+ });+ }+ return out;+}++/** The lane a dropped clip is written on and the source with any lanes pushed down to make room. */+export function resolveDropTrack(input: {+ source: string;+ elements: TimelineElement[];+ placement: TimelineDropPlacement;+ dropped: Pick<TimelineElement, "id" | "tag" | "start" | "duration">;+}): { source: string; track: number } {+ const { source, elements, placement, dropped } = input;+ if (placement.insertRow == null) return { source, track: placement.track };+ const { insertRow, trackOrder } = placement;+ const plan = planDropTrackInsert({ elements, trackOrder, insertRow, dropped });+ if (!plan) throw new Error("Cannot open a new track here: a locked clip would have to move.");+ return { source: applyTrackRenumbers(source, plan), track: plan.track };+}