From 3db02bade8d46e713c3cf0fbed70288e119fbd2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Tue, 24 Nov 2026 18:10:26 +0000 Subject: [PATCH] refactor(studio): drop the timeline stacking-mode move no drag reaches (#8732) * refactor(studio): drop the timeline stacking-mode move no drag reaches * chore(studio): name the timeline stacking-mode files as agreed deletions * fix(studio): keep the z-index commit option hosts may still pass, as a no-op * fix(studio): keep the stacking field hosts may still pass to a timeline move, ignored --- packages/studio/src/App.tsx | 6 +- .../src/hooks/timelineEditingHelpers.test.ts | 103 ----- .../src/hooks/timelineEditingHelpers.ts | 76 ---- .../src/hooks/useElementLifecycleOps.ts | 2 +- .../useTimelineClipTimingEditing.test.tsx | 2 - .../src/hooks/useTimelineClipTimingEditing.ts | 23 +- .../src/hooks/useTimelineEditing.test.tsx | 408 +----------------- .../studio/src/hooks/useTimelineEditing.ts | 3 - .../src/hooks/useTimelineEditingTypes.ts | 7 +- packages/studio/src/hostMount.test.tsx | 16 +- .../player/components/timelineEditing.test.ts | 61 --- .../src/player/components/timelineEditing.ts | 40 -- .../components/timelineLayerDrag.test.ts | 200 --------- .../player/components/timelineLayerDrag.ts | 383 ---------------- scripts/check-no-main-deletions.mjs | 8 + 15 files changed, 26 insertions(+), 1312 deletions(-) delete mode 100644 packages/studio/src/player/components/timelineLayerDrag.test.ts delete mode 100644 packages/studio/src/player/components/timelineLayerDrag.ts diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsx index 8bfbc22fff..64262873d4 100644 --- a/packages/studio/src/App.tsx +++ b/packages/studio/src/App.tsx @@ -20,7 +20,6 @@ import { usePreviewPersistence } from "./hooks/usePreviewPersistence"; import { usePreviewDocumentVersion } from "./hooks/usePreviewDocumentVersion"; import { useTimelineEditing } from "./hooks/useTimelineEditing"; import { useTimelineMoveEditsHandler } from "./hooks/timelineMoveAdapter"; -import type { TimelineZIndexReorderCommit } from "./hooks/useTimelineEditingTypes"; import type { BlockPreviewInfo } from "./components/sidebar/BlocksTab"; import { useDomEditSession } from "./hooks/useDomEditSession"; import { useSdkSelectionSync } from "./hooks/useSdkSelectionSync"; @@ -101,7 +100,6 @@ export function StudioApp({ readOnlyPreview = false, readOnlyPreviewReason }: St rightPanelTab: initialUrlStateRef.current.rightPanelTab, }); const editHistory = useStableHandlers(usePersistentEditHistory({ projectId }), projectId); - const handleDomZIndexReorderCommitRef = useRef(null); const pendingTimelineEditPathRef = useRef(new Set()); const isGestureRecordingRef = useRef(false); const setRefreshKey = useCallback((next: SetStateAction) => { @@ -181,7 +179,6 @@ export function StudioApp({ readOnlyPreview = false, readOnlyPreviewReason }: St publishSdkSession: sdkHandle.publish, forceReloadSdkSession: sdkHandle.forceReload, invalidateGsapCache, - handleDomZIndexReorderCommitRef, }); const handleTimelineElementsMove = useTimelineMoveEditsHandler( timelineEditing.handleTimelineGroupMove, @@ -322,8 +319,7 @@ export function StudioApp({ readOnlyPreview = false, readOnlyPreviewReason }: St }); const domEditSession = useStableHandlers(domEditSessionResult, projectId); domEditSelectionBridgeRef.current = domEditSession.domEditSelection; - const { handleDomZIndexReorderCommit: zCommit, handleDomEditElementDelete: del } = domEditSession; - handleDomZIndexReorderCommitRef.current = trackedStudioEdit(zCommit); + const { handleDomEditElementDelete: del } = domEditSession; clearDomSelectionRef.current = domEditSession.clearDomSelection; handleDomEditElementDeleteRef.current = trackedStudioEdit(del); resetKeyframesRef.current = domEditSession.handleResetSelectedElementKeyframes; diff --git a/packages/studio/src/hooks/timelineEditingHelpers.test.ts b/packages/studio/src/hooks/timelineEditingHelpers.test.ts index f0bcc99731..8173f87f22 100644 --- a/packages/studio/src/hooks/timelineEditingHelpers.test.ts +++ b/packages/studio/src/hooks/timelineEditingHelpers.test.ts @@ -2,7 +2,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { applyTimelineMoveAttributes, - applyTimelineStackingReorder, buildTimelineMoveTimingPatch, buildTimelineResizeTimingPatch, deleteSelectedKeyframes, @@ -48,108 +47,6 @@ function el(input: Partial & { id: string; tag: string }): Time }; } -describe("applyTimelineStackingReorder", () => { - it("commits via the change's own locator even when the element is not in timelineElements", () => { - // Sub-comp children live in the preview iframe but NOT in the top-level - // timelineElements list — the intent must be self-contained. - const iframe = makeIframeWith(` -
-
-
- `); - const commit = vi.fn<(entries: unknown[]) => void>(); - - applyTimelineStackingReorder({ - element: el({ id: "chip", tag: "div" }), - stackingReorder: { - contextKey: "scene", - placement: { type: "above", layerId: "layer:scene:x" }, - zIndexChanges: [ - { - key: "scenes/scene.html#chip", - zIndex: 5, - domId: "chip", - sourceFile: "scenes/scene.html", - }, - ], - }, - timelineElements: [], // element intentionally absent from the top-level list - iframe, - activeCompPath: "index.html", - commit, - }); - - expect(commit).toHaveBeenCalledTimes(1); - const entries = commit.mock.calls[0]![0] as Array<{ - zIndex: number; - id?: string; - sourceFile: string; - }>; - expect(entries).toHaveLength(1); - expect(entries[0]!.zIndex).toBe(5); - expect(entries[0]!.id).toBe("chip"); - expect(entries[0]!.sourceFile).toBe("scenes/scene.html"); - }); - - it("never commits when the dragged clip is audio", () => { - const iframe = makeIframeWith(``); - const commit = vi.fn<(entries: unknown[]) => void>(); - - applyTimelineStackingReorder({ - element: el({ id: "track", tag: "audio" }), - stackingReorder: { - contextKey: "main", - placement: { type: "above", layerId: "layer:main:x" }, - zIndexChanges: [{ key: "track", zIndex: 5, domId: "track" }], - }, - timelineElements: [], - iframe, - activeCompPath: "index.html", - commit, - }); - - expect(commit).not.toHaveBeenCalled(); - }); - - it("resolves selectorIndex within the change's source file", () => { - const iframe = makeIframeWith(` -
-
root
-
-
scene zero
-
scene one
-
-
- `); - const sceneOne = iframe.contentDocument?.querySelectorAll(".chip")[2]; - const commit = vi.fn<(entries: unknown[]) => void>(); - - applyTimelineStackingReorder({ - element: el({ id: "scene-one", tag: "div" }), - stackingReorder: { - contextKey: "scene", - placement: { type: "above", layerId: "layer:scene:x" }, - zIndexChanges: [ - { - key: "scenes/scene.html#.chip:1", - zIndex: 5, - selector: ".chip", - selectorIndex: 1, - sourceFile: "scenes/scene.html", - }, - ], - }, - timelineElements: [], - iframe, - activeCompPath: "index.html", - commit, - }); - - const entries = commit.mock.calls[0]![0] as Array<{ element: Element }>; - expect(entries[0]!.element).toBe(sceneOne); - }); -}); - describe("patchIframeDomTiming", () => { it("patches a top-level composition host in its parent source file", () => { const iframe = makeIframeWith(` diff --git a/packages/studio/src/hooks/timelineEditingHelpers.ts b/packages/studio/src/hooks/timelineEditingHelpers.ts index a9ae466723..57027df912 100644 --- a/packages/studio/src/hooks/timelineEditingHelpers.ts +++ b/packages/studio/src/hooks/timelineEditingHelpers.ts @@ -1,4 +1,3 @@ -import { isHtmlElement } from "@hyperframes/core/runtime/dom-realm"; import { applyAuthoredTiming } from "@hyperframes/core/studio-preview-mark"; import { type TimelineElement, usePlayerStore } from "../player/store/playerStore"; import { toAuthoredStart } from "../player/store/timelineElement"; @@ -13,12 +12,9 @@ import { import { formatTimelineAttributeNumber, formatTimelineMediaOffset, - type TimelineStackingReorderIntent, } from "../player/components/timelineEditing"; -import { getElementZIndex } from "../player/lib/layerOrdering"; import { furthestClipEndFromDocument, - getTimelineElementIdentity, playbackStartAttributeForElement, readPlaybackStartAttributes, } from "../player/lib/timelineElementHelpers"; @@ -31,7 +27,6 @@ import { type RecordEditInput, } from "../utils/studioFileHistory"; import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator"; -import type { TimelineZIndexReorderCommit } from "./useTimelineEditingTypes"; import { setCompositionDurationToContent } from "../utils/timelineAssetDrop"; import { rootCompositionDurationOf } from "../utils/rootDuration"; import { readFileContent } from "./timelineTimingSync"; @@ -41,77 +36,6 @@ import { } from "../components/editor/domEditingElement"; export { deleteSelectedKeyframes } from "./deleteSelectedKeyframes"; export { readFileContent }; -/** - * 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 - * the preview DOM, remaps with the dup-preserving reorder math, and writes only - * z-index (never data-track-index). No-op when the move isn't a reorder, the - * dragged clip is audio (no visual layer to restack), or the live siblings can't - * be resolved. Extracted from StudioApp's timeline hook to keep it under the - * studio 600-LOC cap. - */ -// fallow-ignore-next-line complexity -export function applyTimelineStackingReorder(input: { - element: TimelineElement; - stackingReorder: TimelineStackingReorderIntent | null | undefined; - timelineElements: readonly TimelineElement[]; - iframe: HTMLIFrameElement | null; - activeCompPath: string | null; - commit: TimelineZIndexReorderCommit | null | undefined; - coalesceKey?: string; -}): Promise { - // 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. - const siblingByKey = new Map( - input.timelineElements.map((el) => [getTimelineElementIdentity(el), el]), - ); - const doc = input.iframe?.contentDocument ?? null; - const commitEntries: Array<{ - element: HTMLElement; - zIndex: number; - id?: string; - selector?: string; - selectorIndex?: number; - sourceFile: string; - key: string; - }> = []; - for (const change of intent.zIndexChanges) { - const sibling = siblingByKey.get(change.key); - const domId = change.domId ?? sibling?.domId; - const selector = change.selector ?? sibling?.selector; - const selectorIndex = change.selectorIndex ?? sibling?.selectorIndex; - const sourceFile = - change.sourceFile ?? sibling?.sourceFile ?? input.activeCompPath ?? "index.html"; - const element = doc - ? findElementForSelection( - doc, - { id: domId, selector, selectorIndex, sourceFile }, - input.activeCompPath, - ) - : null; - if (!isHtmlElement(element)) return Promise.resolve(); - if (getElementZIndex(element) === change.zIndex) continue; - commitEntries.push({ - element, - zIndex: change.zIndex, - id: domId ?? sibling?.id ?? change.key, - selector, - selectorIndex, - sourceFile, - key: change.key, - }); - } - if (commitEntries.length === 0) return Promise.resolve(); - // The durability report is for gesture-level callers (z→lane mirror); this - // lane-drag z-sync path has no dependent follow-up write — swallow it. - // Promise.resolve-wrapped: a commit implementation may return void. - return Promise.resolve(input.commit?.(commitEntries, input.coalesceKey)).then(() => undefined); -} export function extendRootDurationIfNeeded(newEnd: number): boolean { const store = usePlayerStore.getState(); if (newEnd <= store.duration) return false; diff --git a/packages/studio/src/hooks/useElementLifecycleOps.ts b/packages/studio/src/hooks/useElementLifecycleOps.ts index ef2fea0f8d..c8bb476132 100644 --- a/packages/studio/src/hooks/useElementLifecycleOps.ts +++ b/packages/studio/src/hooks/useElementLifecycleOps.ts @@ -372,7 +372,7 @@ export function useElementLifecycleOps({ usePlayerStore.getState().bumpZEditVersion(); }; // Resolves once every source-file batch is persisted so a same-file timing write - // can be ordered after it (see applyTimelineStackingReorder callers). + // can be ordered after it. // // skipReload: the live iframe DOM and the player store already hold the // final z state (applied synchronously above), and the persisted patch is diff --git a/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx b/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx index c8ae538cc3..4996cfc594 100644 --- a/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx +++ b/packages/studio/src/hooks/useTimelineClipTimingEditing.test.tsx @@ -43,7 +43,6 @@ function mountClipTiming() { function Harness() { hook = useTimelineClipTimingEditing({ activeCompPath: "index.html", - timelineElements: [], showToast, writeProjectFile: vi.fn(), recordEdit: vi.fn(), @@ -152,7 +151,6 @@ describe("a single-clip trim queued before a project switch", () => { queue = useTimelineEditQueue(projectId); hook = useTimelineClipTimingEditing({ activeCompPath: "index.html", - timelineElements: [], showToast: vi.fn(), writeProjectFile: vi.fn(), recordEdit: vi.fn(), diff --git a/packages/studio/src/hooks/useTimelineClipTimingEditing.ts b/packages/studio/src/hooks/useTimelineClipTimingEditing.ts index da84705dcd..630a8f35ca 100644 --- a/packages/studio/src/hooks/useTimelineClipTimingEditing.ts +++ b/packages/studio/src/hooks/useTimelineClipTimingEditing.ts @@ -2,7 +2,6 @@ import { useCallback } from "react"; import type { TimelineElement } from "../player"; import { toAuthoredStart, toCompositionTime } from "../player/store/timelineElement"; import { - applyTimelineStackingReorder, patchIframeDomTiming, persistTimelineEdit, formatTimelineAttributeNumber, @@ -21,7 +20,6 @@ import { syncPreviewContentDuration, timingGestureStep, } from "./timelineTimingSync"; -import { serializeZLaneGesture } from "../components/nle/zLaneGesture"; import { cutoverCommittedOrThrow, sdkTimingPersist, type CutoverResult } from "../utils/sdkCutover"; type SdkCommit = Extract; @@ -40,7 +38,6 @@ import { type UseTimelineClipTimingEditingOptions = Pick< UseTimelineEditingOptions, | "activeCompPath" - | "timelineElements" | "showToast" | "writeProjectFile" | "recordEdit" @@ -52,7 +49,6 @@ type UseTimelineClipTimingEditingOptions = Pick< | "publishSdkSession" | "forceReloadSdkSession" | "invalidateGsapCache" - | "handleDomZIndexReorderCommitRef" > & { editQueueRef: TimelineEditQueue; }; @@ -60,7 +56,6 @@ type UseTimelineClipTimingEditingOptions = Pick< /** One clip's move and resize: the timing write, then its tween rewrite, as one undo step. */ export function useTimelineClipTimingEditing({ activeCompPath, - timelineElements, showToast, writeProjectFile, recordEdit, @@ -72,7 +67,6 @@ export function useTimelineClipTimingEditing({ publishSdkSession, forceReloadSdkSession, invalidateGsapCache, - handleDomZIndexReorderCommitRef, editQueueRef, }: UseTimelineClipTimingEditingOptions) { const enqueueEdit = useCallback( @@ -150,16 +144,7 @@ export function useTimelineClipTimingEditing({ patchIframeDomTiming(previewIframeRef.current, element, liveAttrs, activeCompPath); } - const reorderDone = applyTimelineStackingReorder({ - element, - stackingReorder: updates.stackingReorder, - timelineElements, - iframe: previewIframeRef.current, - activeCompPath, - commit: handleDomZIndexReorderCommitRef?.current, - }); - - if (!startChanged && !trackChanged) return reorderDone; + if (!startChanged && !trackChanged) return Promise.resolve(); // Snapshot the duration BEFORE the optimistic updates below so a failed // persist can roll the readout + live root back (see captureDurationRollback). @@ -224,7 +209,7 @@ export function useTimelineClipTimingEditing({ { label: "Move timeline clip", ...step, skipRefresh: true }, ) : undefined; - return reorderDone + return Promise.resolve() .then(() => enqueueEdit(element, "Move timeline clip", buildMovePatches, step, { ifEarlierRefused: keepUnlessItOverlaps([{ element, start: updates.start }]), @@ -239,7 +224,7 @@ export function useTimelineClipTimingEditing({ throw error; }); }; - return updates.stackingReorder ? serializeZLaneGesture(commitMove) : commitMove(); + return commitMove(); }, [ previewIframeRef, @@ -250,8 +235,6 @@ export function useTimelineClipTimingEditing({ recordEdit, writeProjectFile, reloadPreview, - timelineElements, - handleDomZIndexReorderCommitRef, showToast, invalidateGsapCache, editQueueRef, diff --git a/packages/studio/src/hooks/useTimelineEditing.test.tsx b/packages/studio/src/hooks/useTimelineEditing.test.tsx index 3d3af8d2a9..2e7fb5a0a7 100644 --- a/packages/studio/src/hooks/useTimelineEditing.test.tsx +++ b/packages/studio/src/hooks/useTimelineEditing.test.tsx @@ -1,13 +1,12 @@ // fallow-ignore-file code-duplication // @vitest-environment happy-dom -import React, { act, useRef, useState } from "react"; +import React, { act, useState } from "react"; import { createRoot } from "react-dom/client"; import { openComposition } from "@hyperframes/sdk"; import { afterEach, describe, expect, it, vi } from "vitest"; import { usePlayerStore, type TimelineElement } from "../player"; import { jsonResponse, requestUrl } from "./fetchStubTestUtils"; -import { useElementLifecycleOps } from "./useElementLifecycleOps"; import { useTimelineEditing } from "./useTimelineEditing"; import { buildMissingCompositionElements, @@ -39,15 +38,6 @@ vi.mock("../components/editor/manualEditingAvailability", async (importOriginal) (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; -type ZIndexEntry = { - element: HTMLElement; - zIndex: number; - id?: string; - selector?: string; - selectorIndex?: number; - sourceFile: string; -}; - afterEach(() => { document.body.innerHTML = ""; usePlayerStore.getState().reset(); @@ -123,7 +113,6 @@ function mountHarness(node: React.ReactElement): { unmount: () => void } { function renderTimelineEditingHook(input: { timelineElements: TimelineElement[]; iframe: HTMLIFrameElement; - onZIndexCommit: (entries: ZIndexEntry[]) => Promise; projectId?: string | null; writeProjectFile?: (path: string, content: string) => Promise; recordEdit?: (input: { @@ -167,8 +156,6 @@ function renderTimelineEditingHook(input: { let latest: ReturnType | null = null; function Harness() { - const commitRef = useRef(input.onZIndexCommit); - commitRef.current = input.onZIndexCommit; const hook = useTimelineEditing({ projectId: input.projectId ?? null, activeCompPath: input.activeCompPath ?? "index.html", @@ -184,7 +171,6 @@ function renderTimelineEditingHook(input: { publishSdkSession: input.publishSdkSession, forceReloadSdkSession: input.forceReloadSdkSession, invalidateGsapCache: input.invalidateGsapCache, - handleDomZIndexReorderCommitRef: commitRef, canEdit: input.canEdit, }); move = hook.handleTimelineElementMove; @@ -230,55 +216,6 @@ type TimelinePublishSdkSession = NonNullable< Parameters[0]["publishSdkSession"] >; -function renderTimelineEditingHookWithLifecycle(input: { - timelineElements: TimelineElement[]; - iframe: HTMLIFrameElement; - commitDomEditPatchBatches: ReturnType< - typeof vi.fn< - (...args: unknown[]) => Promise<{ durable: boolean; allMatched: boolean; changed: boolean }> - > - >; -}): { - move: ReturnType["handleTimelineElementMove"]; - unmount: () => void; -} { - let move: ReturnType["handleTimelineElementMove"] | null = null; - - function Harness() { - const lifecycle = useElementLifecycleOps({ - activeCompPath: "index.html", - showToast: vi.fn(), - writeProjectFile: vi.fn(), - editHistory: { recordEdit: vi.fn() }, - projectIdRef: { current: "p1" }, - reloadPreview: vi.fn(), - clearDomSelection: vi.fn(), - commitDomEditPatchBatches: input.commitDomEditPatchBatches, - }); - const commitRef = useRef(lifecycle.handleDomZIndexReorderCommit); - commitRef.current = lifecycle.handleDomZIndexReorderCommit; - const hook = useTimelineEditing({ - projectId: null, - activeCompPath: "index.html", - timelineElements: input.timelineElements, - showToast: vi.fn(), - writeProjectFile: vi.fn(), - recordEdit: vi.fn(), - reloadPreview: vi.fn(), - previewIframeRef: { current: input.iframe }, - pendingTimelineEditPathRef: { current: new Set() }, - uploadProjectFiles: vi.fn(), - handleDomZIndexReorderCommitRef: commitRef, - }); - move = hook.handleTimelineElementMove; - return null; - } - - const { unmount } = mountHarness(); - if (!move) throw new Error("Expected hook to expose move handler"); - return { move, unmount }; -} - async function flushAsyncWork(): Promise { for (let i = 0; i < 8; i += 1) { await Promise.resolve(); @@ -339,14 +276,10 @@ function stubProjectFetch(files: string | Record, gsapBody?: unk function setupSingleClipHarness(options?: { source?: string; clipStyle?: string; - onZIndexCommit?: (entries: ZIndexEntry[]) => Promise; canEdit?: NonNullable[0]["canEdit"]>; }) { const iframe = createPreviewIframe([{ id: "clip", track: 0, style: options?.clipStyle }]); const clip = timelineElement({ id: "clip", track: 0, zIndex: 0 }); - const commit = - options?.onZIndexCommit ?? - vi.fn<(entries: ZIndexEntry[]) => Promise>().mockResolvedValue(undefined); const writeProjectFile = vi.fn<(...args: unknown[]) => Promise>(async () => {}); const reloadPreview = vi.fn(); const fetchMock = stubProjectFetch( @@ -357,7 +290,6 @@ function setupSingleClipHarness(options?: { const hook = renderTimelineEditingHook({ timelineElements: [clip], iframe, - onZIndexCommit: commit, projectId: "p1", writeProjectFile, recordEdit, @@ -368,7 +300,6 @@ function setupSingleClipHarness(options?: { return { iframe, clip, - commit, writeProjectFile, recordEdit, showToast, @@ -441,7 +372,6 @@ async function setupRootDurationFallback() { const hook = renderTimelineEditingHook({ timelineElements: [clip], iframe, - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile, recordEdit, @@ -508,279 +438,6 @@ describe("useTimelineEditing timeline z-index reorder", () => { ctx.hook.unmount(); }); - it("routes a vertical drag through the shared z-index commit without writing track-index", async () => { - const iframe = createPreviewIframe([ - { id: "front", track: 0, style: "position: relative; z-index: 10" }, - { id: "back", track: 2, style: "position: relative; z-index: 1" }, - ]); - const front = timelineElement({ id: "front", track: 0, zIndex: 10 }); - const back = timelineElement({ id: "back", track: 2, zIndex: 1 }); - const commit = vi.fn<(entries: ZIndexEntry[]) => Promise>().mockResolvedValue(undefined); - const { move, unmount } = renderTimelineEditingHook({ - timelineElements: [front, back], - iframe, - onZIndexCommit: commit, - }); - - await act(async () => { - await move(back, { - start: back.start, - track: back.track, - stackingReorder: { - contextKey: "root", - placement: { type: "onto", layerId: "layer-front" }, - zIndexChanges: [{ key: "back", zIndex: 10 }], - }, - }); - }); - - const doc = iframe.contentDocument; - if (!doc) throw new Error("Expected iframe document"); - - expect(commit).toHaveBeenCalledTimes(1); - expect(commit.mock.calls[0]![0].map((entry) => [entry.id, entry.zIndex])).toEqual([ - ["back", 10], - ]); - expect(doc.getElementById("back")?.getAttribute("data-track-index")).toBe("2"); - - unmount(); - }); - - it("never writes z-index when the dragged clip is audio (no visual layer)", async () => { - const iframe = createPreviewIframe([ - { id: "front", track: 0 }, - { id: "music", track: 1 }, - ]); - const front = timelineElement({ id: "front", track: 0, zIndex: 0 }); - const music = timelineElement({ id: "music", track: 1, zIndex: 0, tag: "audio" }); - const commit = vi.fn<(entries: ZIndexEntry[]) => Promise>().mockResolvedValue(undefined); - const { move, unmount } = renderTimelineEditingHook({ - timelineElements: [front, music], - iframe, - onZIndexCommit: commit, - }); - - await act(async () => { - await move(music, { - start: music.start, - track: music.track, - stackingReorder: { - contextKey: "root", - placement: { type: "onto", layerId: "layer-front" }, - zIndexChanges: [{ key: "music", zIndex: 2 }], - }, - }); - }); - - expect(commit).not.toHaveBeenCalled(); - - unmount(); - }); - - it("commits only the minimum z-index changes resolved by the timeline drag", async () => { - const iframe = createPreviewIframe([ - { id: "front", track: 0, style: "position: relative; z-index: 2" }, - { id: "back", track: 1, style: "position: relative; z-index: 1" }, - { id: "dragged", track: 2, style: "position: relative; z-index: 0" }, - ]); - const front = timelineElement({ id: "front", track: 0, zIndex: 2 }); - const back = timelineElement({ id: "back", track: 1, zIndex: 1 }); - const dragged = timelineElement({ id: "dragged", track: 2, zIndex: 0 }); - const commit = vi.fn<(entries: ZIndexEntry[]) => Promise>().mockResolvedValue(undefined); - const { move, unmount } = renderTimelineEditingHook({ - timelineElements: [front, back, dragged], - iframe, - onZIndexCommit: commit, - }); - - await act(async () => { - await move(dragged, { - start: dragged.start, - track: dragged.track, - stackingReorder: { - contextKey: "root", - placement: { type: "between", beforeLayerId: "front", afterLayerId: "back" }, - zIndexChanges: [ - { key: "dragged", zIndex: 2 }, - { key: "front", zIndex: 3 }, - ], - }, - }); - }); - - expect(commit.mock.calls[0]![0].map((entry) => [entry.id, entry.zIndex])).toEqual([ - ["dragged", 2], - ["front", 3], - ]); - - unmount(); - }); - - it("uses the shared lifecycle commit so static clips receive position relative", async () => { - const iframe = createPreviewIframe([ - { id: "front", track: 0, style: "position: static" }, - { id: "back", track: 1, style: "position: static" }, - ]); - const front = timelineElement({ id: "front", track: 0, zIndex: 0 }); - const back = timelineElement({ id: "back", track: 1, zIndex: 0 }); - const commitDomEditPatchBatches = vi.fn< - (...args: unknown[]) => Promise<{ durable: boolean; allMatched: boolean; changed: boolean }> - >(async () => ({ durable: true, allMatched: true, changed: true })); - const { move, unmount } = renderTimelineEditingHookWithLifecycle({ - timelineElements: [front, back], - iframe, - commitDomEditPatchBatches, - }); - - await act(async () => { - await move(back, { - start: back.start, - track: back.track, - stackingReorder: { - contextKey: "root", - placement: { type: "above", layerId: "front" }, - zIndexChanges: [{ key: "back", zIndex: 2 }], - }, - }); - await flushAsyncWork(); - }); - - 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" }, - ]); - - unmount(); - }); - - it("rejects and rolls back DOM and store z-index changes when a reorder save fails", async () => { - const iframe = createPreviewIframe([ - { id: "front", track: 0, style: "position: relative; z-index: 7" }, - { id: "back", track: 1, style: "position: static" }, - ]); - const front = timelineElement({ id: "front", track: 0, zIndex: 7 }); - const back = timelineElement({ id: "back", track: 1, zIndex: 0 }); - usePlayerStore.getState().setElements([ - { ...front, hasExplicitZIndex: true }, - { ...back, hasExplicitZIndex: false }, - ]); - const saveError = new Error("save failed"); - const commitDomEditPatchBatches = vi - .fn< - (...args: unknown[]) => Promise<{ durable: boolean; allMatched: boolean; changed: boolean }> - >() - .mockRejectedValueOnce(saveError); - const { move, unmount } = renderTimelineEditingHookWithLifecycle({ - timelineElements: [front, back], - iframe, - commitDomEditPatchBatches, - }); - const doc = iframe.contentDocument; - if (!doc) throw new Error("Expected iframe document"); - const frontElement = doc.getElementById("front") as HTMLElement | null; - const backElement = doc.getElementById("back") as HTMLElement | null; - if (!frontElement || !backElement) throw new Error("Expected reordered elements"); - - let rejection: unknown; - await act(async () => { - try { - await move(back, { - start: back.start, - track: back.track, - stackingReorder: { - contextKey: "root", - placement: { type: "above", layerId: "front" }, - zIndexChanges: [ - { key: "front", zIndex: 2 }, - { key: "back", zIndex: 5 }, - ], - }, - }); - } catch (error) { - rejection = error; - } - await flushAsyncWork(); - }); - - expect(rejection).toBe(saveError); - expect(frontElement.style.zIndex).toBe("7"); - expect(frontElement.style.position).toBe("relative"); - expect(backElement.style.zIndex).toBe(""); - expect(backElement.style.position).toBe("static"); - const storeEntries = usePlayerStore.getState().elements; - expect(storeEntries.find((entry) => entry.id === "front")).toMatchObject({ - zIndex: 7, - hasExplicitZIndex: true, - }); - expect(storeEntries.find((entry) => entry.id === "back")).toMatchObject({ - zIndex: 0, - hasExplicitZIndex: false, - }); - - unmount(); - }); - - 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 releaseBatch!: () => void; - const batchSave = new Promise((resolve) => { - releaseBatch = resolve; - }); - const commitDomEditPatchBatches = vi - .fn< - (...args: unknown[]) => Promise<{ durable: boolean; allMatched: boolean; changed: boolean }> - >() - .mockReturnValueOnce( - batchSave.then(() => ({ durable: true, allMatched: true, changed: true })), - ); - const { move, unmount } = renderTimelineEditingHookWithLifecycle({ - timelineElements: [front, back], - iframe, - commitDomEditPatchBatches, - }); - let settled = false; - - let movePromise!: Promise; - await act(async () => { - movePromise = move(back, { - start: back.start, - track: back.track, - stackingReorder: { - contextKey: "root", - placement: { type: "above", layerId: "front" }, - zIndexChanges: [ - { key: "front", zIndex: 2 }, - { key: "back", zIndex: 3 }, - ], - }, - }).then(() => { - settled = true; - }); - await flushAsyncWork(); - }); - - expect(commitDomEditPatchBatches).toHaveBeenCalledTimes(1); - expect(settled).toBe(false); - - await act(async () => { - releaseBatch(); - await movePromise; - await flushAsyncWork(); - }); - expect(settled).toBe(true); - - unmount(); - }); - it("keeps horizontal-only drag on the timing and GSAP shift path without z-index writes", async () => { const h = setupSingleClipHarness(); @@ -792,7 +449,6 @@ describe("useTimelineEditing timeline z-index reorder", () => { if (!doc) throw new Error("Expected iframe document"); expect(doc.getElementById("clip")?.getAttribute("data-start")).toBe("1.25"); expect(doc.getElementById("clip")?.getAttribute("data-track-index")).toBe("0"); - expect(h.commit).not.toHaveBeenCalled(); expect(h.writeProjectFile.mock.calls[0]![1]).toContain('data-start="1.25"'); expect(h.writeProjectFile.mock.calls[0]![1]).toContain('data-track-index="0"'); expect(h.writeProjectFile.mock.calls[0]![1]).not.toContain("z-index"); @@ -822,51 +478,6 @@ describe("useTimelineEditing timeline z-index reorder", () => { h.unmount(); }); - it("orders the timing write after the z-index commit so a diagonal drag can't clobber the restack", async () => { - // Gate the z-index commit so we can observe whether the timing write waits. - let releaseCommit!: () => void; - const commitGate = new Promise((resolve) => { - releaseCommit = resolve; - }); - const h = setupSingleClipHarness({ - clipStyle: "position: relative; z-index: 0", - onZIndexCommit: vi - .fn<(entries: ZIndexEntry[]) => Promise>() - .mockReturnValue(commitGate), - }); - const { clip, commit, writeProjectFile, move, unmount } = h; - - // Diagonal drag: both a time move (start change) and a restack (z-index change). - let movePromise!: Promise; - await act(async () => { - movePromise = move(clip, { - start: 1.25, - track: clip.track, - stackingReorder: { - contextKey: "root", - placement: { type: "onto", layerId: "layer-clip" }, - zIndexChanges: [{ key: "clip", zIndex: 5 }], - }, - }); - await flushAsyncWork(); - }); - - // The z-index commit is in flight but gated; the full-file timing write must - // not have run yet, or it would overwrite the file without the z-index change. - expect(commit).toHaveBeenCalledTimes(1); - expect(writeProjectFile).not.toHaveBeenCalled(); - - // Release the z-index commit → the timing write now proceeds, on top of it. - await act(async () => { - releaseCommit(); - await movePromise; - await flushAsyncWork(); - }); - expect(writeProjectFile).toHaveBeenCalled(); - - unmount(); - }); - it("persists a same-file group move with one write containing every clip timing", async () => { const source = [ '
', @@ -889,7 +500,6 @@ describe("useTimelineEditing timeline z-index reorder", () => { const { groupMove, unmount } = renderTimelineEditingHook({ timelineElements: clips, iframe, - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile, recordEdit, @@ -926,7 +536,6 @@ describe("useTimelineEditing timeline z-index reorder", () => { const { groupMove, unmount } = renderTimelineEditingHook({ timelineElements: [a, b], iframe, - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile, recordEdit, @@ -967,7 +576,6 @@ describe("useTimelineEditing timeline z-index reorder", () => { const { groupMove, unmount } = renderTimelineEditingHook({ timelineElements: [clip], iframe, - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile, recordEdit: vi.fn(async () => {}), @@ -1055,7 +663,6 @@ describe("useTimelineEditing timeline z-index reorder", () => { const { groupMove, unmount } = renderTimelineEditingHook({ timelineElements: [cap], iframe, - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile, recordEdit: vi.fn(async () => {}), @@ -1106,7 +713,6 @@ describe("useTimelineEditing timeline z-index reorder", () => { const { groupMove, unmount } = renderTimelineEditingHook({ timelineElements: [a, b], iframe, - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile, recordEdit: vi.fn(async () => {}), @@ -1141,7 +747,6 @@ describe("useTimelineEditing timeline z-index reorder", () => { const single = renderTimelineEditingHook({ timelineElements: [clip], iframe: createPreviewIframe([{ id: "clip", track: 0 }]), - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile: singleWrite, recordEdit: vi.fn(async () => {}), @@ -1155,7 +760,6 @@ describe("useTimelineEditing timeline z-index reorder", () => { const group = renderTimelineEditingHook({ timelineElements: [clip], iframe: createPreviewIframe([{ id: "clip", track: 0 }]), - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile: groupWrite, recordEdit: vi.fn(async () => {}), @@ -1181,7 +785,6 @@ describe("useTimelineEditing timeline z-index reorder", () => { const h = renderTimelineEditingHook({ timelineElements: [clip], iframe: createPreviewIframe([{ id: "clip", track: 0 }]), - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile: vi.fn(async () => {}), recordEdit, @@ -1241,7 +844,6 @@ describe("useTimelineEditing duration rollback on failed persist", () => { const hook = renderTimelineEditingHook({ timelineElements: [clip], iframe, - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile, recordEdit: vi.fn(async () => {}), @@ -1343,7 +945,6 @@ describe("useTimelineEditing duration rollback on failed persist", () => { const hook = renderTimelineEditingHook({ timelineElements: [tail], iframe, - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile, recordEdit: vi.fn(async () => {}), @@ -1380,7 +981,6 @@ describe("useTimelineEditing duration rollback on failed persist", () => { const succeeding = renderTimelineEditingHook({ timelineElements: [clip], iframe, - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile, recordEdit: vi.fn(async () => {}), @@ -1543,7 +1143,6 @@ describe("useTimelineEditing: canEdit gate", () => { const hook = renderTimelineEditingHook({ timelineElements: [free, locked], iframe, - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile, recordEdit, @@ -1717,7 +1316,6 @@ describe("useTimelineEditing: canEdit gate", () => { const hook = renderTimelineEditingHook({ timelineElements: [voice1, voice2], iframe, - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile, recordEdit, @@ -1759,7 +1357,6 @@ describe("useTimelineEditing: canEdit gate", () => { const hook = renderTimelineEditingHook({ timelineElements: [member], iframe, - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile, recordEdit, @@ -1982,7 +1579,6 @@ function setupNestedHarness() { const hook = renderTimelineEditingHook({ timelineElements: parseTimelineFromDOM(doc, 20), iframe, - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile, recordEdit: vi.fn(async () => {}), @@ -2245,7 +1841,6 @@ describe("useTimelineEditing: nested rows write composition-local starts", () => const hook = renderTimelineEditingHook({ timelineElements: [clip], iframe, - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", writeProjectFile, recordEdit: vi.fn(async () => {}), @@ -2375,7 +1970,6 @@ describe("clip timing edits sync GSAP exactly once", () => { const hook = renderTimelineEditingHook({ timelineElements: [scene, side], iframe, - onZIndexCommit: vi.fn().mockResolvedValue(undefined), projectId: "p1", activeCompPath: SCENE_PATH, writeProjectFile: project.writeProjectFile, diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.ts index 1554f77e52..2a8b587b11 100644 --- a/packages/studio/src/hooks/useTimelineEditing.ts +++ b/packages/studio/src/hooks/useTimelineEditing.ts @@ -46,7 +46,6 @@ export function useTimelineEditing({ publishSdkSession, forceReloadSdkSession, invalidateGsapCache, - handleDomZIndexReorderCommitRef, canEdit, }: UseTimelineEditingOptions) { const projectIdRef = useRef(projectId); @@ -73,7 +72,6 @@ export function useTimelineEditing({ }); const { handleTimelineElementMove, handleTimelineElementResize } = useTimelineClipTimingEditing({ activeCompPath, - timelineElements, showToast, writeProjectFile, recordEdit, @@ -85,7 +83,6 @@ export function useTimelineEditing({ publishSdkSession, forceReloadSdkSession, invalidateGsapCache, - handleDomZIndexReorderCommitRef, editQueueRef, }); diff --git a/packages/studio/src/hooks/useTimelineEditingTypes.ts b/packages/studio/src/hooks/useTimelineEditingTypes.ts index 7b9a8edf60..8b4f4acc95 100644 --- a/packages/studio/src/hooks/useTimelineEditingTypes.ts +++ b/packages/studio/src/hooks/useTimelineEditingTypes.ts @@ -1,7 +1,6 @@ import type { MutableRefObject, RefObject } from "react"; import type { Composition } from "@hyperframes/sdk"; import type { TimelineElement } from "../player"; -import type { TimelineStackingReorderIntent } from "../player/components/timelineEditing"; import type { PublishSdkSession } from "../utils/sdkCutover"; import type { CanEditTimelineElement } from "./timelineEditPermission"; @@ -47,6 +46,7 @@ export interface UseTimelineEditingOptions { forceReloadSdkSession?: () => void; /** Reparse authored animations after a timing rewrite changes their positions. */ invalidateGsapCache?: () => void; + /** @deprecated Ignored: a lane drag restacks through the timeline's own stacking sync. */ handleDomZIndexReorderCommitRef?: MutableRefObject; /** Refuses a hand edit at the persist boundary when set; absent = Studio unchanged. */ canEdit?: CanEditTimelineElement; @@ -57,8 +57,7 @@ export type TimelineFileDropHandler = ( placement?: { start: number; track: number }, ) => Promise; -/** What a timeline move commits: the new start and track, plus the z-index - * reorder a vertical drag resolves to (absent for a pure horizontal move). */ export type TimelineMoveUpdates = Pick & { - stackingReorder?: TimelineStackingReorderIntent | null; + /** @deprecated Ignored: a lane drag restacks through the timeline's own stacking sync. */ + stackingReorder?: unknown; }; diff --git a/packages/studio/src/hostMount.test.tsx b/packages/studio/src/hostMount.test.tsx index 2697d3b593..4d2ea8c0cc 100644 --- a/packages/studio/src/hostMount.test.tsx +++ b/packages/studio/src/hostMount.test.tsx @@ -113,12 +113,10 @@ async function stubHostProjectDisk( return { read, fetchMock }; } -type TimelineEditingHandle = { - handleTimelineElementMove: ( - element: TimelineElement, - updates: { start: number; track: number }, - ) => Promise; -}; +type TimelineEditingHandle = Pick< + ReturnType, + "handleTimelineElementMove" +>; function mountHost( clip: TimelineElement, @@ -213,7 +211,11 @@ describe("public export surface: a host mounting hand editing outside EditorShel const { timelineEditing, undo } = mountHost(clip, iframe); await act(async () => { - await timelineEditing.handleTimelineElementMove(clip, { start: 5, track: 0 }); + await timelineEditing.handleTimelineElementMove(clip, { + start: 5, + track: 0, + stackingReorder: null, + }); }); expect(disk.read("index.html")).toContain('data-start="5"'); diff --git a/packages/studio/src/player/components/timelineEditing.test.ts b/packages/studio/src/player/components/timelineEditing.test.ts index 534163f047..bc37f3e746 100644 --- a/packages/studio/src/player/components/timelineEditing.test.ts +++ b/packages/studio/src/player/components/timelineEditing.test.ts @@ -17,7 +17,6 @@ import { snapKeyframePctToBeat, type TimelinePromptElement, } from "./timelineEditing"; -import { buildStackingTimelineLayers } from "./timelineTrackOrder"; describe("resolveTimelineMove", () => { it("moves timing based on horizontal drag and snaps to centiseconds", () => { @@ -154,66 +153,6 @@ describe("resolveTimelineMove", () => { ), ).toEqual({ start: 2, track: 2 }); }); - - it("snaps conflicting vertical stacking movement to a new lane without changing data-track-index", () => { - const stackingElements = [ - { - id: "root-front", - tag: "div", - start: 0, - duration: 2, - track: 0, - zIndex: 2, - hasExplicitZIndex: true, - stackingContextId: "root", - parentCompositionId: null, - compositionAncestors: ["root"], - }, - { - id: "root-back", - tag: "div", - start: 0, - duration: 2, - track: 1, - zIndex: 1, - hasExplicitZIndex: true, - stackingContextId: "root", - parentCompositionId: null, - compositionAncestors: ["root"], - }, - ]; - const layers = buildStackingTimelineLayers(stackingElements).rows; - const result = resolveTimelineMove( - { - start: 0, - track: 1, - duration: 2, - originClientX: 0, - originRow: 0, - pixelsPerSecond: 100, - maxStart: 8, - trackOrder: [0, 1], - layerOrder: layers.map((layer) => layer.id), - timelineLayers: layers, - stackingElement: stackingElements[1], - stackingElements, - }, - 0, - -1, - ); - - expect(result).toEqual({ - start: 0, - track: 1, - previewLayerId: `preview:root-back:above:${layers[0]!.id}`, - previewLayerIndex: 0, - stackingReorder: { - contextKey: "root", - placement: { type: "above", layerId: layers[0]!.id }, - zIndexChanges: [{ key: "root-back", zIndex: 3 }], - }, - }); - }); }); describe("resolveTimelineGroupMove", () => { diff --git a/packages/studio/src/player/components/timelineEditing.ts b/packages/studio/src/player/components/timelineEditing.ts index ce62f491c3..caa0889bbf 100644 --- a/packages/studio/src/player/components/timelineEditing.ts +++ b/packages/studio/src/player/components/timelineEditing.ts @@ -1,9 +1,7 @@ import { formatTime } from "../lib/time"; import { roundToCenti } from "../../utils/rounding"; import type { StackingTimelineLayer, TimelineLayerId } from "./timelineTrackOrder"; -import { resolveTimelineLayerStackingMove } from "./timelineLayerDrag"; import { shouldShowTimelineLayerGroupHeader } from "./TimelineLayerGroupHeader"; -import type { TimelineStackingElement, TimelineStackingReorderIntent } from "./timelineStacking"; import type { TimelineEditCapabilities } from "./timelineEditCapabilities"; export { @@ -26,11 +24,6 @@ export { type TimelineGroupTimingMember, } from "./timelineGroupEditing"; -export { - type TimelineStackingElement, - type TimelineStackingReorderIntent, -} from "./timelineStacking"; - const roundToCentiseconds = roundToCenti; function clamp(value: number, min: number, max: number): number { @@ -54,12 +47,6 @@ export interface TimelineMoveInput { minStart?: number; maxStart: number; trackOrder: number[]; - layerOrder?: TimelineLayerId[]; - timelineLayers?: StackingTimelineLayer[]; - /** When provided, vertical movement is resolved as a z-index stacking reorder - * within `stackingElement`'s context instead of a raw track change. */ - stackingElement?: TimelineStackingElement; - stackingElements?: TimelineStackingElement[]; } export interface TimelineResizeInput { @@ -114,9 +101,6 @@ export function resolveTimelineMove( ): { start: number; track: number; - previewLayerId?: TimelineLayerId; - previewLayerIndex?: number; - stackingReorder?: TimelineStackingReorderIntent | null; } { const scrollDeltaX = (input.currentScrollLeft ?? 0) - (input.originScrollLeft ?? 0); const deltaTime = @@ -132,30 +116,6 @@ export function resolveTimelineMove( Math.max(0, input.maxStart), ); - // Stacking mode: the two axes never fight. Horizontal movement writes time - // (nextStart); vertical movement writes z-index. Lane/overlap resolution - // uses the clip's authored time span, NOT the dragged start, otherwise a - // diagonal drag that drifts the clip out of overlap silently flips the - // placement from "restack" to "join lane" and cancels the reorder. - if (input.stackingElement) { - const layerMove = - input.timelineLayers && input.layerOrder - ? resolveTimelineLayerStackingMove({ - element: { ...input.stackingElement, duration: input.duration }, - layers: input.timelineLayers, - layerOrder: input.layerOrder, - trackDeltaRaw, - }) - : null; - return { - start: nextStart, - track: input.track, - previewLayerId: layerMove?.previewLayerId, - previewLayerIndex: layerMove?.previewLayerIndex, - stackingReorder: layerMove?.stackingReorder ?? null, - }; - } - const currentTrackIndex = Math.max(0, input.trackOrder.indexOf(input.track)); const desiredTrackIndex = currentTrackIndex + deltaTrack; const nextTrackIndex = clamp(desiredTrackIndex, 0, Math.max(0, input.trackOrder.length - 1)); diff --git a/packages/studio/src/player/components/timelineLayerDrag.test.ts b/packages/studio/src/player/components/timelineLayerDrag.test.ts deleted file mode 100644 index b325095a21..0000000000 --- a/packages/studio/src/player/components/timelineLayerDrag.test.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { describe, expect, it } from "vitest"; -import type { TimelineElement } from "../store/playerStore"; -import type { StackingTimelineLayer } from "./timelineTrackOrder"; -import { - resolveTimelineLayerStackingMove, - resolveTimelineLayerZIndexChanges, -} from "./timelineLayerDrag"; - -function element(input: { - id: string; - zIndex: number; - tag?: string; - start?: number; - duration?: number; -}): TimelineElement { - return { - id: input.id, - tag: input.tag ?? "div", - start: input.start ?? 0, - duration: input.duration ?? 1, - track: 0, - zIndex: input.zIndex, - hasExplicitZIndex: true, - stackingContextId: "root", - parentCompositionId: null, - compositionAncestors: ["root"], - }; -} - -function layer( - id: string, - zIndex: number, - elements: TimelineElement[] = [element({ id, zIndex })], -): StackingTimelineLayer { - return { - id, - kind: "visual", - contextKey: "root", - zIndex, - placementTrack: 0, - elements, - }; -} - -describe("resolveTimelineLayerZIndexChanges", () => { - it("joins an existing lane by assigning the dragged clip that lane's z-index", () => { - const dragged = element({ id: "dragged", zIndex: 1, start: 2, duration: 1 }); - const front = element({ id: "front", zIndex: 10, start: 0, duration: 1 }); - - expect( - resolveTimelineLayerZIndexChanges({ - element: dragged, - layers: [layer("front", 10, [front]), layer("back", 1)], - placement: { type: "onto", layerId: "front" }, - })?.zIndexChanges, - ).toEqual([{ key: "dragged", zIndex: 10 }]); - }); - - it("rejects an onto-lane join when the dragged clip would overlap that lane", () => { - const dragged = element({ id: "dragged", zIndex: 1, start: 0.5, duration: 1 }); - const front = element({ id: "front", zIndex: 10, start: 0, duration: 1 }); - - expect( - resolveTimelineLayerZIndexChanges({ - element: dragged, - layers: [layer("front", 10, [front]), layer("back", 1)], - placement: { type: "onto", layerId: "front" }, - }), - ).toBeNull(); - }); - - it("interpolates a new integer z-index strictly between neighboring layers", () => { - const dragged = element({ id: "dragged", zIndex: 1 }); - - expect( - resolveTimelineLayerZIndexChanges({ - element: dragged, - layers: [layer("front", 10), layer("back", 4)], - placement: { type: "between", beforeLayerId: "front", afterLayerId: "back" }, - })?.zIndexChanges, - ).toEqual([{ key: "dragged", zIndex: 7 }]); - }); - - it("renumbers the minimum sibling set when adjacent layers leave no integer gap", () => { - const dragged = element({ id: "dragged", zIndex: 0 }); - - expect( - resolveTimelineLayerZIndexChanges({ - element: dragged, - layers: [layer("front", 2), layer("back", 1), layer("lower", 0)], - placement: { type: "between", beforeLayerId: "front", afterLayerId: "back" }, - })?.zIndexChanges, - ).toEqual([ - { key: "dragged", zIndex: 2 }, - { key: "front", zIndex: 3 }, - ]); - }); - - it("assigns new extreme z-index values above the top and below the bottom layer", () => { - const dragged = element({ id: "dragged", zIndex: 0 }); - const layers = [layer("front", 10), layer("back", -2)]; - - expect( - resolveTimelineLayerZIndexChanges({ - element: dragged, - layers, - placement: { type: "above", layerId: "front" }, - })?.zIndexChanges, - ).toEqual([{ key: "dragged", zIndex: 11 }]); - - expect( - resolveTimelineLayerZIndexChanges({ - element: dragged, - layers, - placement: { type: "below", layerId: "back" }, - })?.zIndexChanges, - ).toEqual([{ key: "dragged", zIndex: -3 }]); - }); - - it("does not resolve stacking z-index changes for audio clips", () => { - expect( - resolveTimelineLayerZIndexChanges({ - element: element({ id: "music", zIndex: 0, tag: "audio" }), - layers: [layer("front", 10)], - placement: { type: "onto", layerId: "front" }, - }), - ).toBeNull(); - }); -}); - -describe("resolveTimelineLayerStackingMove", () => { - it("places an upward onto-lane drop above the overlapping target lane", () => { - const front = element({ id: "front", zIndex: 10, start: 0, duration: 2 }); - const dragged = element({ id: "dragged", zIndex: 1, start: 0.5, duration: 1 }); - const layers = [layer("front", 10, [front]), layer("dragged", 1, [dragged])]; - - expect( - resolveTimelineLayerStackingMove({ - element: dragged, - layers, - layerOrder: layers.map((item) => item.id), - trackDeltaRaw: -0.8, - }), - ).toEqual({ - previewLayerId: "preview:dragged:above:front", - previewLayerIndex: 0, - stackingReorder: { - contextKey: "root", - placement: { type: "above", layerId: "front" }, - zIndexChanges: [{ key: "dragged", zIndex: 11 }], - }, - }); - }); - - it("places a downward onto-lane drop below the overlapping target lane", () => { - const dragged = element({ id: "dragged", zIndex: 10, start: 0.5, duration: 1 }); - const back = element({ id: "back", zIndex: 1, start: 0, duration: 2 }); - const layers = [layer("dragged", 10, [dragged]), layer("back", 1, [back])]; - - expect( - resolveTimelineLayerStackingMove({ - element: dragged, - layers, - layerOrder: layers.map((item) => item.id), - trackDeltaRaw: 0.8, - }), - ).toEqual({ - previewLayerId: "preview:dragged:below:back", - previewLayerIndex: 2, - stackingReorder: { - contextKey: "root", - placement: { type: "below", layerId: "back" }, - zIndexChanges: [{ key: "dragged", zIndex: 0 }], - }, - }); - }); - - it("keeps a non-overlapping onto-lane drop joined to the target lane", () => { - const front = element({ id: "front", zIndex: 10, start: 0, duration: 1 }); - const dragged = element({ id: "dragged", zIndex: 1, start: 2, duration: 1 }); - const layers = [layer("front", 10, [front]), layer("dragged", 1, [dragged])]; - - expect( - resolveTimelineLayerStackingMove({ - element: dragged, - layers, - layerOrder: layers.map((item) => item.id), - trackDeltaRaw: -0.8, - }), - ).toEqual({ - previewLayerId: "front", - previewLayerIndex: 0, - stackingReorder: { - contextKey: "root", - placement: { type: "onto", layerId: "front" }, - zIndexChanges: [{ key: "dragged", zIndex: 10 }], - }, - }); - }); -}); diff --git a/packages/studio/src/player/components/timelineLayerDrag.ts b/packages/studio/src/player/components/timelineLayerDrag.ts deleted file mode 100644 index 75e4d4c1bc..0000000000 --- a/packages/studio/src/player/components/timelineLayerDrag.ts +++ /dev/null @@ -1,383 +0,0 @@ -import { resolveStackingContextKey } from "../lib/layerOrdering"; -import { getTimelineElementIdentity } from "../lib/timelineElementHelpers"; -import { - timelineElementsOverlap, - type StackingTimelineLayer, - type TimelineLayerId, -} from "./timelineTrackOrder"; -import { - toStackingOrderItem, - type TimelineLayerDropPlacement, - type TimelineStackingElement, - type TimelineStackingReorderIntent, - type TimelineStackingZIndexChange, -} from "./timelineStacking"; - -const ONTO_ROW_THRESHOLD = 0.35; - -export interface TimelineLayerStackingMoveResolution { - previewLayerId: TimelineLayerId; - previewLayerIndex: number; - stackingReorder: TimelineStackingReorderIntent | null; -} - -function isAudioElement(element: TimelineStackingElement): boolean { - return element.tag?.toLowerCase() === "audio"; -} - -function layerContainsElement(layer: StackingTimelineLayer, key: string): boolean { - return layer.elements.some((element) => getTimelineElementIdentity(element) === key); -} - -function layerConflictsWithElement( - layer: StackingTimelineLayer, - element: TimelineStackingElement, - draggedKey: string, -): boolean { - return layer.elements.some( - (candidate) => - getTimelineElementIdentity(candidate) !== draggedKey && - timelineElementsOverlap(candidate, element), - ); -} - -function addElementChange( - changes: TimelineStackingZIndexChange[], - element: TimelineStackingElement, - zIndex: number, -): void { - if ((element.zIndex ?? 0) === zIndex) return; - changes.push({ - key: getTimelineElementIdentity(element), - zIndex, - domId: element.domId, - selector: element.selector, - selectorIndex: element.selectorIndex, - sourceFile: element.sourceFile, - }); -} - -function addLayerChanges( - changes: TimelineStackingZIndexChange[], - layer: StackingTimelineLayer, - zIndex: number, - excludedKey: string, -): number { - let count = 0; - for (const element of layer.elements) { - const key = getTimelineElementIdentity(element); - if (key === excludedKey) continue; - const before = changes.length; - addElementChange(changes, element, zIndex); - if (changes.length > before) count += 1; - } - return count; -} - -function getContextLayers( - layers: readonly StackingTimelineLayer[], - contextKey: string, -): StackingTimelineLayer[] { - return layers.filter((layer) => layer.kind === "visual" && layer.contextKey === contextKey); -} - -function findLayer( - layers: readonly StackingTimelineLayer[], - id: string, -): StackingTimelineLayer | null { - return layers.find((layer) => layer.id === id) ?? null; -} - -function resolvePlacementZIndexChanges(input: { - element: TimelineStackingElement; - targetZIndex: number; -}): TimelineStackingZIndexChange[] { - const changes: TimelineStackingZIndexChange[] = []; - addElementChange(changes, input.element, input.targetZIndex); - return changes; -} - -function buildPushUpCandidate(input: { - element: TimelineStackingElement; - layers: readonly StackingTimelineLayer[]; - beforeIndex: number; - bottomZIndex: number; -}): { changes: TimelineStackingZIndexChange[]; siblingChanges: number } { - const draggedKey = getTimelineElementIdentity(input.element); - const draggedZIndex = input.bottomZIndex + 1; - const changes = resolvePlacementZIndexChanges({ - element: input.element, - targetZIndex: draggedZIndex, - }); - let siblingChanges = 0; - let requiredZIndex = draggedZIndex + 1; - for (let index = input.beforeIndex; index >= 0; index -= 1) { - const layer = input.layers[index]; - if (!layer) continue; - const nextZIndex = layer.zIndex >= requiredZIndex ? layer.zIndex : requiredZIndex; - siblingChanges += addLayerChanges(changes, layer, nextZIndex, draggedKey); - requiredZIndex = nextZIndex + 1; - } - return { changes, siblingChanges }; -} - -function buildPushDownCandidate(input: { - element: TimelineStackingElement; - layers: readonly StackingTimelineLayer[]; - afterIndex: number; - topZIndex: number; -}): { changes: TimelineStackingZIndexChange[]; siblingChanges: number } { - const draggedKey = getTimelineElementIdentity(input.element); - const draggedZIndex = input.topZIndex - 1; - const changes = resolvePlacementZIndexChanges({ - element: input.element, - targetZIndex: draggedZIndex, - }); - let siblingChanges = 0; - let requiredZIndex = draggedZIndex - 1; - for (let index = input.afterIndex; index < input.layers.length; index += 1) { - const layer = input.layers[index]; - if (!layer) continue; - const nextZIndex = layer.zIndex <= requiredZIndex ? layer.zIndex : requiredZIndex; - siblingChanges += addLayerChanges(changes, layer, nextZIndex, draggedKey); - requiredZIndex = nextZIndex - 1; - } - return { changes, siblingChanges }; -} - -function resolveBetweenChanges(input: { - element: TimelineStackingElement; - layers: readonly StackingTimelineLayer[]; - beforeLayer: StackingTimelineLayer; - afterLayer: StackingTimelineLayer; -}): TimelineStackingZIndexChange[] { - const topZIndex = input.beforeLayer.zIndex; - const bottomZIndex = input.afterLayer.zIndex; - if (topZIndex - bottomZIndex > 1) { - return resolvePlacementZIndexChanges({ - element: input.element, - targetZIndex: Math.floor((topZIndex + bottomZIndex) / 2), - }); - } - - const beforeIndex = input.layers.findIndex((layer) => layer.id === input.beforeLayer.id); - const afterIndex = input.layers.findIndex((layer) => layer.id === input.afterLayer.id); - const pushUp = buildPushUpCandidate({ - element: input.element, - layers: input.layers, - beforeIndex, - bottomZIndex, - }); - const pushDown = buildPushDownCandidate({ - element: input.element, - layers: input.layers, - afterIndex, - topZIndex, - }); - return pushUp.siblingChanges <= pushDown.siblingChanges ? pushUp.changes : pushDown.changes; -} - -function resolveOntoChanges(input: { - element: TimelineStackingElement; - layers: readonly StackingTimelineLayer[]; - layerId: string; -}): TimelineStackingZIndexChange[] | null { - const target = findLayer(input.layers, input.layerId); - if (!target) return null; - if (layerConflictsWithElement(target, input.element, getTimelineElementIdentity(input.element))) { - return null; - } - return resolvePlacementZIndexChanges({ - element: input.element, - targetZIndex: target.zIndex, - }); -} - -function resolveEdgeChanges(input: { - element: TimelineStackingElement; - layers: readonly StackingTimelineLayer[]; - layerId: string; - offset: number; -}): TimelineStackingZIndexChange[] | null { - const target = findLayer(input.layers, input.layerId); - if (!target) return null; - return resolvePlacementZIndexChanges({ - element: input.element, - targetZIndex: target.zIndex + input.offset, - }); -} - -function resolvePlacementChanges(input: { - element: TimelineStackingElement; - layers: readonly StackingTimelineLayer[]; - placement: TimelineLayerDropPlacement; -}): TimelineStackingZIndexChange[] | null { - switch (input.placement.type) { - case "onto": - return resolveOntoChanges({ - element: input.element, - layers: input.layers, - layerId: input.placement.layerId, - }); - case "above": - return resolveEdgeChanges({ - element: input.element, - layers: input.layers, - layerId: input.placement.layerId, - offset: 1, - }); - case "below": - return resolveEdgeChanges({ - element: input.element, - layers: input.layers, - layerId: input.placement.layerId, - offset: -1, - }); - case "between": { - const beforeLayer = findLayer(input.layers, input.placement.beforeLayerId); - const afterLayer = findLayer(input.layers, input.placement.afterLayerId); - return beforeLayer && afterLayer - ? resolveBetweenChanges({ - element: input.element, - layers: input.layers, - beforeLayer, - afterLayer, - }) - : null; - } - } -} - -export function resolveTimelineLayerZIndexChanges(input: { - element: TimelineStackingElement; - layers: readonly StackingTimelineLayer[]; - placement: TimelineLayerDropPlacement; -}): TimelineStackingReorderIntent | null { - if (isAudioElement(input.element)) return null; - const contextKey = resolveStackingContextKey(toStackingOrderItem(input.element)); - const layers = getContextLayers(input.layers, contextKey); - const changes = resolvePlacementChanges({ - element: input.element, - layers, - placement: input.placement, - }); - - return changes && changes.length > 0 - ? { contextKey, placement: input.placement, zIndexChanges: changes } - : null; -} - -// fallow-ignore-next-line complexity -function resolveDragPlacement( - layers: readonly StackingTimelineLayer[], - targetPosition: number, -): TimelineLayerDropPlacement | null { - const first = layers[0]; - const last = layers[layers.length - 1]; - if (!first || !last) return null; - if (targetPosition < -ONTO_ROW_THRESHOLD) return { type: "above", layerId: first.id }; - if (targetPosition > layers.length - 1 + ONTO_ROW_THRESHOLD) { - return { type: "below", layerId: last.id }; - } - - const nearestIndex = Math.round(targetPosition); - const nearest = layers[nearestIndex]; - if (nearest && Math.abs(targetPosition - nearestIndex) <= ONTO_ROW_THRESHOLD) { - return { type: "onto", layerId: nearest.id }; - } - - const insertionIndex = Math.max(0, Math.min(layers.length, Math.ceil(targetPosition))); - if (insertionIndex <= 0) return { type: "above", layerId: first.id }; - if (insertionIndex >= layers.length) return { type: "below", layerId: last.id }; - const before = layers[insertionIndex - 1]; - const after = layers[insertionIndex]; - return before && after - ? { type: "between", beforeLayerId: before.id, afterLayerId: after.id } - : null; -} - -function resolveLaneAwareDragPlacement(input: { - layers: readonly StackingTimelineLayer[]; - element: TimelineStackingElement; - draggedKey: string; - placement: TimelineLayerDropPlacement; - targetPosition: number; - currentIndex: number; -}): TimelineLayerDropPlacement | null { - if (input.placement.type !== "onto") return input.placement; - const target = findLayer(input.layers, input.placement.layerId); - if (!target) return null; - if (!layerConflictsWithElement(target, input.element, input.draggedKey)) return input.placement; - if (input.targetPosition < input.currentIndex) { - return { type: "above", layerId: target.id }; - } - if (input.targetPosition > input.currentIndex) { - return { type: "below", layerId: target.id }; - } - return input.placement; -} - -function getPreviewLayerId( - draggedKey: string, - placement: TimelineLayerDropPlacement, -): TimelineLayerId { - if (placement.type === "onto") return placement.layerId; - if (placement.type === "between") { - return `preview:${draggedKey}:between:${placement.beforeLayerId}:${placement.afterLayerId}`; - } - return `preview:${draggedKey}:${placement.type}:${placement.layerId}`; -} - -function getPreviewLayerIndex( - layerOrder: readonly TimelineLayerId[], - placement: TimelineLayerDropPlacement, -): number { - if (placement.type === "onto") return Math.max(0, layerOrder.indexOf(placement.layerId)); - if (placement.type === "between") { - return Math.max(0, layerOrder.indexOf(placement.afterLayerId)); - } - const targetIndex = Math.max(0, layerOrder.indexOf(placement.layerId)); - return placement.type === "above" ? targetIndex : targetIndex + 1; -} - -export function resolveTimelineLayerStackingMove(input: { - element: TimelineStackingElement; - layers: readonly StackingTimelineLayer[]; - layerOrder: readonly TimelineLayerId[]; - trackDeltaRaw: number; -}): TimelineLayerStackingMoveResolution | null { - if (isAudioElement(input.element)) return null; - const contextKey = resolveStackingContextKey(toStackingOrderItem(input.element)); - const layerById = new Map(input.layers.map((layer) => [layer.id, layer])); - const contextLayers = input.layerOrder - .map((id) => layerById.get(id) ?? null) - .filter( - (layer): layer is StackingTimelineLayer => - layer != null && layer.kind === "visual" && layer.contextKey === contextKey, - ); - const draggedKey = getTimelineElementIdentity(input.element); - const currentIndex = contextLayers.findIndex((layer) => layerContainsElement(layer, draggedKey)); - if (currentIndex < 0) return null; - - const targetPosition = currentIndex + input.trackDeltaRaw; - const rawPlacement = resolveDragPlacement(contextLayers, targetPosition); - if (!rawPlacement) return null; - const placement = resolveLaneAwareDragPlacement({ - layers: contextLayers, - element: input.element, - draggedKey, - placement: rawPlacement, - targetPosition, - currentIndex, - }); - if (!placement) return null; - return { - previewLayerId: getPreviewLayerId(draggedKey, placement), - previewLayerIndex: getPreviewLayerIndex(input.layerOrder, placement), - stackingReorder: resolveTimelineLayerZIndexChanges({ - element: input.element, - layers: contextLayers, - placement, - }), - }; -} diff --git a/scripts/check-no-main-deletions.mjs b/scripts/check-no-main-deletions.mjs index a94659fe5a..87feac5b3f 100644 --- a/scripts/check-no-main-deletions.mjs +++ b/scripts/check-no-main-deletions.mjs @@ -985,6 +985,14 @@ export const ALLOWED_DELETIONS = new Map([ "packages/core/scripts/rewrite-esm-extensions.ts", "moved to scripts/rewrite-relative-import-extensions.mjs as plain ESM so packages without tsx can use it; now also rewrites .d.ts", ], + [ + "packages/studio/src/player/components/timelineLayerDrag.ts", + "its only importer was resolveTimelineMove's stacking mode, which no timeline drag reaches", + ], + [ + "packages/studio/src/player/components/timelineLayerDrag.test.ts", + "tests for the removed timeline stacking-mode move", + ], [ "packages/studio/src/hooks/gsapTargetCache.ts", "its only caller was the deleted var-offset move writer; nothing imports isElementGsapTargeted",