diff --git a/src/components/timeline/interaction/interaction-controller.ts b/src/components/timeline/interaction/interaction-controller.ts index f4515d75..610278a6 100644 --- a/src/components/timeline/interaction/interaction-controller.ts +++ b/src/components/timeline/interaction/interaction-controller.ts @@ -22,6 +22,7 @@ import { buildTrackYPositions, determineDragBehavior, determineDropAction, + distance, exceedsDragThreshold, findContentClipAtPosition, findNearestSnapPoint, @@ -83,6 +84,11 @@ const DEFAULT_CONFIG: ResolvedConfig = { resizeZone: 12 }; +/** A touch held this long without moving lifts the clip under it */ +const LIFT_HOLD_MS = 450; +/** Movement past this before the hold completes is a pan or a drag, not a lift */ +const LIFT_SLOP_PX = 8; + // ─── Lifecycle Interface ─────────────────────────────────────────────────── /** @@ -101,6 +107,7 @@ export interface TimelineInteractionRegistration { export class InteractionController implements TimelineInteractionRegistration { private state: InteractionState = IDLE_STATE; private activePointerId = -1; + private activePointerType = ""; private readonly config: ResolvedConfig; private snapPoints: SnapPoint[] = []; @@ -113,6 +120,15 @@ export class InteractionController implements TimelineInteractionRegistration { private readonly handlePointerUp: (e: PointerEvent) => void; private readonly handlePointerCancel: (e: PointerEvent) => void; private readonly handleTouchTap: (e: PointerEvent) => void; + private readonly handleLiftedTouchMove: (e: TouchEvent) => void; + + private liftTimer: ReturnType | null = null; + /** The touch's latest event while a lift is pending, where the lifted clip picks up */ + private liftEvent: PointerEvent | null = null; + /** The held clip's id, so a lift never picks up a clip removed or reordered during the hold */ + private liftClipId: string | null = null; + /** Where the clip was lifted; set only while a lifted clip is held */ + private liftPoint: { x: number; y: number } | null = null; constructor( private readonly edit: Edit, @@ -131,6 +147,9 @@ export class InteractionController implements TimelineInteractionRegistration { this.handlePointerUp = this.onPointerUp.bind(this); this.handlePointerCancel = this.onPointerCancel.bind(this); this.handleTouchTap = this.onTouchTap.bind(this); + this.handleLiftedTouchMove = e => { + if (this.liftPoint && e.cancelable) e.preventDefault(); + }; } // ═══════════════════════════════════════════════════════════════════════════ @@ -143,6 +162,8 @@ export class InteractionController implements TimelineInteractionRegistration { document.addEventListener("pointermove", this.handlePointerMove); document.addEventListener("pointerup", this.handlePointerUp); document.addEventListener("pointercancel", this.handlePointerCancel); + // Browsers fix which listeners can cancel a touch when it starts, so this one is in place before any lift + this.tracksContainer.addEventListener("touchmove", this.handleLiftedTouchMove, { passive: false }); } public update(_deltaTime: number): void { @@ -156,6 +177,11 @@ export class InteractionController implements TimelineInteractionRegistration { private onPointerDown(e: PointerEvent): void { if (e.button !== 0) return; + // A second finger ends a touch interaction (a pinch or a stray touch) and starts nothing; a palm leaves a pen drag alone + if (this.state.type !== "idle" && e.pointerType === "touch" && e.pointerId !== this.activePointerId) { + if (this.activePointerType === "touch") this.cancelInteraction(); + return; + } if (this.state.type !== "idle") this.cancelInteraction(); const target = e.target as HTMLElement; @@ -171,12 +197,15 @@ export class InteractionController implements TimelineInteractionRegistration { return; } - // Only the selected clip has touch-action: none; a touch anywhere else is the browser's to scroll - if (isTouchPointer(e) && !clipEl.classList.contains("selected")) return; - const trackIndex = parseInt(clipEl.dataset["trackIndex"] || "0", 10); const clipIndex = parseInt(clipEl.dataset["clipIndex"] || "0", 10); + // Only the selected clip has touch-action: none; a touch anywhere else is the browser's to scroll unless a still hold lifts it + if (isTouchPointer(e) && !clipEl.classList.contains("selected")) { + if (e.pointerType === "touch") this.startPending(e, { trackIndex, clipIndex }, true); + return; + } + // Check if clicking on resize handle if (target.classList.contains("ss-clip-resize-handle")) { const edge = target.classList.contains("left") ? "left" : "right"; @@ -188,7 +217,7 @@ export class InteractionController implements TimelineInteractionRegistration { this.startPending(e, { trackIndex, clipIndex }); } - private startPending(e: PointerEvent, clipRef: ClipRef): void { + private startPending(e: PointerEvent, clipRef: ClipRef, liftOnly = false): void { const clip = this.stateManager.getClipAt(clipRef.trackIndex, clipRef.clipIndex); if (!clip) return; @@ -196,7 +225,33 @@ export class InteractionController implements TimelineInteractionRegistration { // the tracks container, which would break click handlers on clip children // (e.g. the mask badge). Capture happens if this becomes a real drag. this.activePointerId = e.pointerId; - this.state = createPendingState({ x: e.clientX, y: e.clientY }, clipRef, clip.config.start); + this.activePointerType = e.pointerType; + const pending = createPendingState({ x: e.clientX, y: e.clientY }, clipRef, clip.config.start, liftOnly); + this.state = pending; + + if (e.pointerType === "touch") { + this.liftEvent = e; + this.liftClipId = clip.id; + this.liftTimer = setTimeout(() => this.lift(pending), LIFT_HOLD_MS); + } + } + + private lift(pending: PendingState): void { + const e = this.liftEvent; + this.liftTimer = null; + if (this.state !== pending || !e) return; + if (this.stateManager.getClipAt(pending.clipRef.trackIndex, pending.clipRef.clipIndex)?.id !== this.liftClipId) { + this.setIdle(); + return; + } + + if (pending.liftOnly) { + this.stateManager.selectClip(pending.clipRef.trackIndex, pending.clipRef.clipIndex, false); + this.config.onRequestRender?.(); + } + // touch-action is fixed when a touch starts, so only cancelling its touchmoves stops the browser scrolling a lifted clip + this.liftPoint = { x: e.clientX, y: e.clientY }; + this.transitionToDragging(e, pending); } private startResize(e: PointerEvent, clipRef: ClipRef, edge: "left" | "right"): void { @@ -223,6 +278,7 @@ export class InteractionController implements TimelineInteractionRegistration { /** Track the pointer driving this interaction and capture it so its pointerup cannot be lost */ private beginPointerInteraction(e: PointerEvent): void { this.activePointerId = e.pointerId; + this.activePointerType = e.pointerType; try { this.tracksContainer.setPointerCapture(e.pointerId); } catch { @@ -258,6 +314,13 @@ export class InteractionController implements TimelineInteractionRegistration { private handlePendingMove(e: PointerEvent, state: PendingState): void { const dx = e.clientX - state.startPoint.x; const dy = e.clientY - state.startPoint.y; + if (this.liftEvent) this.liftEvent = e; + + if (state.liftOnly) { + // Past the slop the touch is a pan, which the browser already owns + if (distance(dx, dy) > LIFT_SLOP_PX) this.setIdle(); + return; + } if (exceedsDragThreshold(dx, dy, this.config.dragThreshold)) { this.transitionToDragging(e, state); @@ -535,7 +598,9 @@ export class InteractionController implements TimelineInteractionRegistration { this.setIdle(); break; case "dragging": - this.completeDrag(e, this.state); + // A lifted clip let go where it was lifted stays put; layout rounding would otherwise read as a small move + if (this.liftPoint && distance(e.clientX - this.liftPoint.x, e.clientY - this.liftPoint.y) <= LIFT_SLOP_PX) this.cancelInteraction(); + else this.completeDrag(e, this.state); break; case "resizing": this.completeResize(e, this.state); @@ -581,6 +646,12 @@ export class InteractionController implements TimelineInteractionRegistration { private setIdle(): void { this.state = IDLE_STATE; this.activePointerId = -1; + this.activePointerType = ""; + if (this.liftTimer) clearTimeout(this.liftTimer); + this.liftTimer = null; + this.liftEvent = null; + this.liftClipId = null; + this.liftPoint = null; } private completeDrag(_e: PointerEvent, state: DraggingState): void { @@ -952,6 +1023,7 @@ export class InteractionController implements TimelineInteractionRegistration { document.removeEventListener("pointermove", this.handlePointerMove); document.removeEventListener("pointerup", this.handlePointerUp); document.removeEventListener("pointercancel", this.handlePointerCancel); + this.tracksContainer.removeEventListener("touchmove", this.handleLiftedTouchMove); // Dispose all feedback elements (stateless, idempotent) disposeFeedbackElements(this.feedbackElements); diff --git a/src/components/timeline/interaction/interaction-state.ts b/src/components/timeline/interaction/interaction-state.ts index a7a24f10..576ffedd 100644 --- a/src/components/timeline/interaction/interaction-state.ts +++ b/src/components/timeline/interaction/interaction-state.ts @@ -44,6 +44,8 @@ export interface PendingState { readonly startPoint: Point; readonly clipRef: ClipRef; readonly originalTime: Seconds; + /** A touch on an unselected clip: the browser owns its pan, so only a still hold lifts it into a drag */ + readonly liftOnly: boolean; } export interface DraggingState { @@ -80,8 +82,8 @@ export const IDLE_STATE: IdleState = { type: "idle" }; // ─── State Factory Functions ─────────────────────────────────────────────── -export function createPendingState(startPoint: Point, clipRef: ClipRef, originalTime: Seconds): PendingState { - return { type: "pending", startPoint, clipRef, originalTime }; +export function createPendingState(startPoint: Point, clipRef: ClipRef, originalTime: Seconds, liftOnly = false): PendingState { + return { type: "pending", startPoint, clipRef, originalTime, liftOnly }; } export function createDraggingState( diff --git a/tests/interaction-controller.test.ts b/tests/interaction-controller.test.ts index b57d16f1..c4759b12 100644 --- a/tests/interaction-controller.test.ts +++ b/tests/interaction-controller.test.ts @@ -133,6 +133,7 @@ function createMockStateManager(tracks: MockTrack[] = []) { getViewport: jest.fn(() => ({ scrollX: 0, scrollY: 0, pixelsPerSecond: 100 })), getPlayback: jest.fn(() => ({ time: 0, isPlaying: false })), clearSelection: jest.fn(), + selectClip: jest.fn(), getAttachedLumaPlayer: jest.fn(() => null), setInteractionQuery: jest.fn(), // Allow tests to update tracks @@ -1312,6 +1313,213 @@ describe("InteractionController", () => { press(firstClip(), "mouse"); expect(controller.isDragging(0, 0)).toBe(true); }); + + describe("long-press lift", () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + const touch = (type: string, clientX: number, options: { target?: EventTarget; pointerId?: number } = {}) => + (options.target ?? document).dispatchEvent( + createPointerEvent(type, { clientX, clientY: 20, pointerType: "touch", pointerId: options.pointerId }) + ); + const touchmove = () => { + const event = new Event("touchmove", { bubbles: true, cancelable: true }); + firstClip().dispatchEvent(event); + return event.defaultPrevented; + }; + + it("lifts a still touch on an unselected clip at 450 ms and not before", () => { + touch("pointerdown", 50, { target: firstClip() }); + jest.advanceTimersByTime(449); + expect(controller.isDragging(0, 0)).toBe(false); + expect(mockStateManager.selectClip).not.toHaveBeenCalled(); + + jest.advanceTimersByTime(1); + expect(controller.isDragging(0, 0)).toBe(true); + expect(mockStateManager.selectClip).toHaveBeenCalledWith(0, 0, false); + }); + + it("lifts the selected clip too", () => { + firstClip().classList.add("selected"); + touch("pointerdown", 50, { target: firstClip() }); + jest.advanceTimersByTime(450); + expect(controller.isDragging(0, 0)).toBe(true); + }); + + it("cancels the lift after 9 px of movement, leaving the pan to the browser", () => { + touch("pointerdown", 50, { target: firstClip() }); + jest.advanceTimersByTime(200); + touch("pointermove", 59); + jest.advanceTimersByTime(300); + expect(controller.isDragging(0, 0)).toBe(false); + expect(mockStateManager.selectClip).not.toHaveBeenCalled(); + }); + + it("cancels the lift when a second pointer goes down, without starting one for it", () => { + const secondClip = mockDOM.tracksContainer.querySelectorAll(".ss-clip")[1] as HTMLElement; + touch("pointerdown", 50, { target: firstClip() }); + touch("pointerdown", 300, { target: secondClip, pointerId: 2 }); + jest.advanceTimersByTime(500); + expect(controller.isDragging(0, 0)).toBe(false); + expect(controller.isDragging(0, 1)).toBe(false); + }); + + it("leaves a release before 450 ms as a tap", () => { + touch("pointerdown", 50, { target: firstClip() }); + jest.advanceTimersByTime(200); + touch("pointerup", 50); + jest.advanceTimersByTime(300); + expect(controller.isDragging(0, 0)).toBe(false); + expect(mockStateManager.selectClip).not.toHaveBeenCalled(); + expect(mockEdit.executeEditCommand).not.toHaveBeenCalled(); + }); + + it("registers its touchmove listener before any touch starts, since browsers fix a touch's blocking regions then", () => { + controller.dispose(); + const addListener = jest.spyOn(mockDOM.tracksContainer, "addEventListener"); + controller = new InteractionController( + mockEdit as never, + mockStateManager as never, + mockTrackList as never, + mockDOM.tracksContainer, + mockDOM.feedbackLayer + ); + controller.mount(); + + expect(addListener).toHaveBeenCalledWith("touchmove", expect.any(Function), { passive: false }); + }); + + it("prevents a touchmove only while a clip is lifted", () => { + touch("pointerdown", 50, { target: firstClip() }); + expect(touchmove()).toBe(false); + + jest.advanceTimersByTime(450); + expect(touchmove()).toBe(true); + + touch("pointerup", 50); + expect(touchmove()).toBe(false); + }); + + it.each(["video", "luma"])("drops nothing when a lifted %s clip is released without moving", assetType => { + // A fractional start the quantised clip rect can't reproduce exactly + mockStateManager.setTestTracks([createMockTrack(0, [{ start: 1.234, length: 2, assetType }])] as MockTrack[]); + Object.assign(mockEdit, { getClip: jest.fn(() => ({ asset: { type: assetType, src: "luma.mp4" } })) }); + firstClip().getBoundingClientRect = () => ({ + left: 139, + top: 0, + width: 200, + height: 40, + right: 339, + bottom: 40, + x: 139, + y: 0, + toJSON: () => ({}) + }); + + touch("pointerdown", 150, { target: firstClip() }); + jest.advanceTimersByTime(450); + touch("pointerup", 152); + + expect(mockEdit.executeEditCommand).not.toHaveBeenCalled(); + expect(controller.isDragging(0, 0)).toBe(false); + }); + + it("drops the lift when the held clip changes during the hold", () => { + touch("pointerdown", 50, { target: firstClip() }); + const held = mockStateManager.getClipAt(0, 0) as ClipState; + mockStateManager.getClipAt.mockImplementation(() => ({ ...held, id: "another-clip" })); + jest.advanceTimersByTime(450); + + expect(controller.isDragging(0, 0)).toBe(false); + expect(mockStateManager.selectClip).not.toHaveBeenCalled(); + }); + + it("lets a resting palm leave a pen drag alone", () => { + firstClip().classList.add("selected"); + firstClip().dispatchEvent(createPointerEvent("pointerdown", { clientX: 50, clientY: 20, pointerType: "pen" })); + document.dispatchEvent(createPointerEvent("pointermove", { clientX: 100, clientY: 20, pointerType: "pen" })); + touch("pointerdown", 300, { target: mockDOM.tracksContainer, pointerId: 2 }); + + expect(controller.isDragging(0, 0)).toBe(true); + }); + + it("still lifts after 8 px of movement", () => { + touch("pointerdown", 50, { target: firstClip() }); + touch("pointermove", 58); + jest.advanceTimersByTime(450); + expect(controller.isDragging(0, 0)).toBe(true); + }); + + it("picks the clip up where the finger last rested", () => { + touch("pointerdown", 50, { target: firstClip() }); + jest.advanceTimersByTime(200); + touch("pointermove", 56); + jest.advanceTimersByTime(250); + // The clip's rect starts at 0, so its left follows the finger's 6 px + expect(firstClip().style.left).toBe("6px"); + }); + + it("clears the lift timer on pointercancel and on dispose", () => { + touch("pointerdown", 50, { target: firstClip() }); + touch("pointercancel", 50); + expect(jest.getTimerCount()).toBe(0); + + touch("pointerdown", 50, { target: firstClip() }); + controller.dispose(); + expect(jest.getTimerCount()).toBe(0); + }); + + it("leaves no command when a lifted drag is cancelled", () => { + // Alone on its track, so the drag would land as a move + mockStateManager.setTestTracks([createMockTrack(0, [{ start: 0, length: 2 }])] as MockTrack[]); + touch("pointerdown", 50, { target: firstClip() }); + jest.advanceTimersByTime(450); + touch("pointermove", 150); + touch("pointercancel", 150); + + expect(mockEdit.executeEditCommand).not.toHaveBeenCalled(); + expect(firstClip().style.position).toBe(""); + }); + + it("moves a lifted clip 2 s for a 100 px drag at 50 px/s, keeping its length", () => { + // Clip at 1 s for 2 s starts at view x 66 (16px padding) + mockStateManager.setTestTracks([createMockTrack(0, [{ start: 1, length: 2 }])] as MockTrack[]); + mockStateManager.getViewport.mockReturnValue({ scrollX: 0, scrollY: 0, pixelsPerSecond: 50 }); + firstClip().getBoundingClientRect = () => ({ + left: 66, + top: 0, + width: 100, + height: 40, + right: 166, + bottom: 40, + x: 66, + y: 0, + toJSON: () => ({}) + }); + + touch("pointerdown", 80, { target: firstClip() }); + jest.advanceTimersByTime(450); + touch("pointermove", 130); + touch("pointermove", 180); + touch("pointerup", 180); + + const commands = mockEdit.executeEditCommand.mock.calls.map(([cmd]) => cmd as { type: string; newTime?: number }); + expect(commands.map(cmd => cmd.type)).toEqual(["MoveClipCommand"]); + expect(commands[0]?.newTime).toBeCloseTo(3); + }); + + it.each(["mouse", "pen"])("doesn't lift for a %s held on the selected clip", pointerType => { + firstClip().classList.add("selected"); + firstClip().dispatchEvent(createPointerEvent("pointerdown", { clientX: 50, clientY: 20, pointerType })); + jest.advanceTimersByTime(500); + expect(controller.isDragging(0, 0)).toBe(false); + }); + }); }); // ─── Interrupted Interaction Tests ───────────────────────────────────────