diff --git a/src/components/canvas/canvas-gestures.ts b/src/components/canvas/canvas-gestures.ts index ae303f55..fd347d2e 100644 --- a/src/components/canvas/canvas-gestures.ts +++ b/src/components/canvas/canvas-gestures.ts @@ -15,6 +15,8 @@ export interface ZoomLimits { max: number; } +type Pair = [Point, Point]; + const clamp = (value: number, { min, max }: ZoomLimits): number => Math.min(Math.max(value, min), max); /** Zooms to `zoom`, within the limits, so the point under `anchor` stays under it. */ @@ -23,3 +25,89 @@ export function zoomAbout(view: View, anchor: Point, zoom: number, limits: ZoomL const ratio = next / view.zoom; return { zoom: next, x: anchor.x - (anchor.x - view.x) * ratio, y: anchor.y - (anchor.y - view.y) * ratio }; } + +const midpoint = ([a, b]: Pair): Point => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }); +const distance = ([a, b]: Pair): number => Math.hypot(b.x - a.x, b.y - a.y); + +/** The view after two pointers move from `from` to `to`: zoomed by their spread, then carried by their midpoint. */ +export function pinch(view: View, from: Pair, to: Pair, limits: ZoomLimits): View { + const start = distance(from); + const before = midpoint(from); + const after = midpoint(to); + const zoomed = zoomAbout(view, before, start > 0 ? view.zoom * (distance(to) / start) : view.zoom, limits); + return { ...zoomed, x: zoomed.x + after.x - before.x, y: zoomed.y + after.y - before.y }; +} + +export interface CanvasGesturesOptions { + getView: () => View; + setView: (view: View) => void; + limits: ZoomLimits; + /** The second pointer has landed: whatever one pointer was doing has to stop. */ + onStart: () => void; +} + +/** Two touches on the canvas pinch and pan it. One touch, a mouse, or anything that starts off the canvas is left alone. */ +export class CanvasGestures { + private readonly pointers = new Map(); + + constructor( + private readonly root: HTMLElement, + private readonly canvas: HTMLElement, + private readonly options: CanvasGesturesOptions + ) { + // Capture, so a second finger is claimed before the canvas can start a drag with it. + root.addEventListener("pointerdown", this.onDown, true); + root.addEventListener("pointermove", this.onMove); + root.addEventListener("pointerup", this.onEnd); + root.addEventListener("pointercancel", this.onEnd); + // Safari's own page pinch, which touch-action does not always stop. + root.addEventListener("gesturestart", this.blockPageZoom); + root.addEventListener("gesturechange", this.blockPageZoom); + } + + dispose(): void { + this.root.removeEventListener("pointerdown", this.onDown, true); + this.root.removeEventListener("pointermove", this.onMove); + this.root.removeEventListener("pointerup", this.onEnd); + this.root.removeEventListener("pointercancel", this.onEnd); + this.root.removeEventListener("gesturestart", this.blockPageZoom); + this.root.removeEventListener("gesturechange", this.blockPageZoom); + this.pointers.clear(); + } + + private onDown = (e: PointerEvent): void => { + // A new touch sequence has begun, so whatever is still tracked lost its pointerup somewhere. + if (e.pointerType === "touch" && e.isPrimary) this.pointers.clear(); + if (e.pointerType !== "touch" || e.target !== this.canvas) return; + + this.pointers.set(e.pointerId, { x: e.clientX, y: e.clientY }); + if (this.pointers.size < 2) return; + + e.stopPropagation(); + if (this.pointers.size === 2) this.options.onStart(); + }; + + private onMove = (e: PointerEvent): void => { + const before = this.pointers.get(e.pointerId); + if (!before) return; + + this.pointers.set(e.pointerId, { x: e.clientX, y: e.clientY }); + if (this.pointers.size !== 2) return; + + const { left, top } = this.canvas.getBoundingClientRect(); + const local = (point: Point): Point => ({ x: point.x - left, y: point.y - top }); + const entries = [...this.pointers.entries()]; + const from = entries.map(([id, point]) => local(id === e.pointerId ? before : point)) as Pair; + const to = entries.map(([, point]) => local(point)) as Pair; + this.options.setView(pinch(this.options.getView(), from, to, this.options.limits)); + }; + + private onEnd = (e: PointerEvent): void => { + this.pointers.delete(e.pointerId); + }; + + // Only a pinch of ours: a trackpad pinch on desktop Safari is the user's page zoom. + private blockPageZoom = (e: Event): void => { + if (e.target === this.canvas && this.pointers.size > 0) e.preventDefault(); + }; +} diff --git a/src/components/canvas/shotstack-canvas.ts b/src/components/canvas/shotstack-canvas.ts index d8d5c1f7..4946b655 100644 --- a/src/components/canvas/shotstack-canvas.ts +++ b/src/components/canvas/shotstack-canvas.ts @@ -1,5 +1,5 @@ import { BufferingNotice, visibleBounds } from "@canvas/buffering-notice"; -import { zoomAbout, type View } from "@canvas/canvas-gestures"; +import { CanvasGestures, zoomAbout, type View } from "@canvas/canvas-gestures"; import type { Player } from "@canvas/players/player"; import { AlignmentGuides } from "@canvas/system/alignment-guides"; import { createWebGLErrorOverlay } from "@canvas/webgl-error-overlay"; @@ -63,6 +63,7 @@ export class Canvas { private onBackgroundClickBound: (event: pixi.FederatedPointerEvent) => void; private onWheelBound: (e: WheelEvent) => void; private canvasRoot: HTMLDivElement | null = null; + private gestures: CanvasGestures | null = null; private readonly bufferingNotice = new BufferingNotice(); constructor(edit: Edit) { @@ -155,6 +156,13 @@ export class Canvas { this.canvasRoot = root; root.addEventListener("wheel", this.onWheelBound, { passive: false, capture: true }); root.addEventListener("pointerdown", this.onPanPointerDown); + this.gestures?.dispose(); + this.gestures = new CanvasGestures(root, this.application.canvas, { + getView: () => this.getView(), + setView: view => this.setView(view), + limits: this.zoomLimits, + onStart: () => this.edit.getInternalEvents().emit(InternalEvent.CanvasGestureStarted) + }); } private getView(): View { @@ -740,6 +748,8 @@ export class Canvas { // Remove canvas root listeners this.canvasRoot?.removeEventListener("wheel", this.onWheelBound, { capture: true }); this.canvasRoot?.removeEventListener("pointerdown", this.onPanPointerDown); + this.gestures?.dispose(); + this.gestures = null; document.removeEventListener("pointermove", this.onPanPointerMove); document.removeEventListener("pointerup", this.onPanPointerUp); this.canvasRoot = null; diff --git a/src/core/events/edit-events.ts b/src/core/events/edit-events.ts index 444e2740..148f5c3b 100644 --- a/src/core/events/edit-events.ts +++ b/src/core/events/edit-events.ts @@ -117,6 +117,7 @@ export const InternalEvent = { CanvasClipClicked: "canvas:clipClicked", CanvasClipDoubleClicked: "canvas:clipDoubleClicked", CanvasBackgroundClicked: "canvas:backgroundClicked", + CanvasGestureStarted: "canvas:gestureStarted", // Font capability detection FontCapabilitiesChanged: "font:capabilitiesChanged", @@ -214,6 +215,7 @@ export type InternalEventMap = { [InternalEvent.CanvasClipClicked]: { player: Player }; [InternalEvent.CanvasClipDoubleClicked]: { player: Player }; [InternalEvent.CanvasBackgroundClicked]: void; + [InternalEvent.CanvasGestureStarted]: void; // Font [InternalEvent.FontCapabilitiesChanged]: { supportsBold: boolean }; diff --git a/src/core/ui/selection-handles.ts b/src/core/ui/selection-handles.ts index 677acf76..39dd3478 100644 --- a/src/core/ui/selection-handles.ts +++ b/src/core/ui/selection-handles.ts @@ -109,6 +109,7 @@ export class SelectionHandles implements CanvasOverlayRegistration { private onSelectionClearedBound: () => void; private onClipFocusedBound: (payload: { trackIndex: number; clipIndex: number }) => void; private onClipBlurredBound: () => void; + private onGestureStartedBound: () => void; private onPointerDownBound: (event: pixi.FederatedPointerEvent) => void; private onPointerMoveBound: (event: pixi.FederatedPointerEvent) => void; private onPointerUpBound: () => void; @@ -150,6 +151,7 @@ export class SelectionHandles implements CanvasOverlayRegistration { this.onSelectionClearedBound = this.onSelectionCleared.bind(this); this.onClipFocusedBound = this.onClipFocused.bind(this); this.onClipBlurredBound = this.onClipBlurred.bind(this); + this.onGestureStartedBound = this.cancelInteraction.bind(this); this.onPointerDownBound = this.onPointerDown.bind(this); this.onPointerMoveBound = this.onPointerMove.bind(this); this.onPointerUpBound = this.onPointerUp.bind(this); @@ -162,6 +164,7 @@ export class SelectionHandles implements CanvasOverlayRegistration { const internal = this.edit.getInternalEvents(); internal.on(InternalEvent.ClipFocused, this.onClipFocusedBound); internal.on(InternalEvent.ClipBlurred, this.onClipBlurredBound); + internal.on(InternalEvent.CanvasGestureStarted, this.onGestureStartedBound); } mount(parent: pixi.Container, app: pixi.Application): void { @@ -232,6 +235,7 @@ export class SelectionHandles implements CanvasOverlayRegistration { const internal = this.edit.getInternalEvents(); internal.off(InternalEvent.ClipFocused, this.onClipFocusedBound); internal.off(InternalEvent.ClipBlurred, this.onClipBlurredBound); + internal.off(InternalEvent.CanvasGestureStarted, this.onGestureStartedBound); if (this.app) { this.app.stage.off("pointerdown", this.onPointerDownBound); @@ -578,6 +582,28 @@ export class SelectionHandles implements CanvasOverlayRegistration { this.edit.clearAlignmentGuides(); } + /** A second pointer means a pinch: put back what the drag has moved so far, and drop it without committing. */ + private cancelInteraction(): void { + if (!(this.isDragging || this.scaleDirection || this.edgeDragDirection || this.isRotating)) return; + + const moved = this.finalDragState; + if (moved && this.selectedClipId && this.initialClipConfiguration) { + const { offset, width, height, transform } = this.initialClipConfiguration; + const restore: Partial = {}; + if (moved.offset) restore.offset = offset; + if (moved.width !== undefined) restore.width = width; + if (moved.height !== undefined) restore.height = height; + if (moved.transform) restore.transform = transform; + + this.edit.updateClipInDocument(this.selectedClipId, restore); + this.edit.resolveClip(this.selectedClipId); + } + + this.finalDragState = null; + this.resetDragState(); + this.edit.clearAlignmentGuides(); + } + // ─── Drag Operations ───────────────────────────────────────────────────────── private startDrag(event: pixi.FederatedPointerEvent): void { diff --git a/tests/canvas-dispose.test.ts b/tests/canvas-dispose.test.ts index 0f1dd4a2..b1e30b9f 100644 --- a/tests/canvas-dispose.test.ts +++ b/tests/canvas-dispose.test.ts @@ -8,6 +8,7 @@ import { Canvas } from "@canvas/shotstack-canvas"; import type { Edit } from "@core/edit-session"; +import { InternalEvent } from "@core/events/edit-events"; import * as pixi from "pixi.js"; // earcut is ESM-only, which jest cannot require. Nothing drawn here needs triangulating. @@ -52,8 +53,8 @@ const makeClip = (index: number): { getContainer: () => pixi.Container } => { return { getContainer: () => sprite }; }; -const makeEdit = (clips: number): Edit => { - const events = { on: () => {}, off: () => {}, emit: () => {} }; +const makeEdit = (clips: number, emit: (...args: unknown[]) => void = () => {}): Edit => { + const events = { on: () => {}, off: () => {}, emit }; return { setCanvas: () => {}, size: { width: 1280, height: 720 }, @@ -115,4 +116,61 @@ describe("Canvas dispose", () => { expect(lostContexts).not.toContain(survivorView); survivor.dispose(); }); + + describe("touch gestures", () => { + const touch = (type: string, target: EventTarget, id: number, x: number, y: number): void => { + // jsdom has no PointerEvent, so an Event carries the fields the gesture handler reads. + const event = new Event(type, { bubbles: true, cancelable: true }); + Object.defineProperties(event, { + pointerId: { value: id }, + pointerType: { value: "touch" }, + isPrimary: { value: id === 1 }, + clientX: { value: x }, + clientY: { value: y } + }); + target.dispatchEvent(event); + }; + const pinchOut = (target: EventTarget): void => { + touch("pointerdown", target, 1, 100, 100); + touch("pointerdown", target, 2, 200, 100); + touch("pointermove", target, 1, 50, 100); + touch("pointermove", target, 2, 250, 100); + }; + const started = (emit: jest.Mock): number => emit.mock.calls.filter(([name]) => name === InternalEvent.CanvasGestureStarted).length; + + it("pinches the canvas it loaded, and lets go of the root once disposed", async () => { + const emit = jest.fn(); + const canvas = new Canvas(makeEdit(0, emit)); + await canvas.load(); + canvas.application.stop(); + const view = canvas.application.canvas; + const before = canvas.getZoom(); + + pinchOut(view); + + expect(started(emit)).toBe(1); + expect(canvas.getZoom()).toBeCloseTo(before * 2); + + const root = view.parentElement as HTMLElement; + canvas.dispose(); + root.append(view); + pinchOut(view); + + expect(started(emit)).toBe(1); + }); + + it("tracks pointers once, however many times the root is set up", async () => { + const emit = jest.fn(); + const canvas = new Canvas(makeEdit(0, emit)); + await canvas.load(); + canvas.application.stop(); + const view = canvas.application.canvas; + + (canvas as unknown as { setupTouchHandling(root: HTMLElement): void }).setupTouchHandling(view.parentElement as HTMLElement); + pinchOut(view); + + expect(started(emit)).toBe(1); + canvas.dispose(); + }); + }); }); diff --git a/tests/canvas-gestures.test.ts b/tests/canvas-gestures.test.ts index 0fd7e553..dee3c907 100644 --- a/tests/canvas-gestures.test.ts +++ b/tests/canvas-gestures.test.ts @@ -2,7 +2,7 @@ * @jest-environment jsdom */ -import { zoomAbout, type Point, type View } from "@canvas/canvas-gestures"; +import { CanvasGestures, pinch, zoomAbout, type Point, type View } from "@canvas/canvas-gestures"; const LIMITS = { min: 0.1, max: 4 }; @@ -31,3 +31,231 @@ describe("zoomAbout", () => { expect(zoomAbout(view, anchor, 0.001, LIMITS).zoom).toBe(0.1); }); }); + +const pair = (ax: number, ay: number, bx: number, by: number): [Point, Point] => [ + { x: ax, y: ay }, + { x: bx, y: by } +]; + +describe("pinch", () => { + const view = { x: 20, y: 30, zoom: 1 }; + const midpoint = { x: 150, y: 100 }; + + it("doubles the zoom when the pointers spread from 100px to 200px, and the midpoint stays put", () => { + const next = pinch(view, pair(100, 100, 200, 100), pair(50, 100, 250, 100), LIMITS); + + expect(next.zoom).toBe(2); + expect(worldAt(next, midpoint)).toEqual(worldAt(view, midpoint)); + }); + + it("clamps the zoom at the limit and still holds the midpoint", () => { + const start = { x: 20, y: 30, zoom: 3 }; + + const next = pinch(start, pair(100, 100, 200, 100), pair(50, 100, 250, 100), LIMITS); + + expect(next.zoom).toBe(4); + expect(worldAt(next, midpoint).x).toBeCloseTo(worldAt(start, midpoint).x); + }); + + it("pans by how far the midpoint moved when the spread is unchanged", () => { + expect(pinch(view, pair(100, 100, 200, 100), pair(130, 90, 230, 90), LIMITS)).toEqual({ x: 50, y: 20, zoom: 1 }); + }); + + it("carries the point under the midpoint along with it as it moves", () => { + const before = worldAt(view, { x: 150, y: 120 }); + + const after = worldAt(pinch(view, pair(100, 100, 200, 140), pair(120, 80, 300, 170), LIMITS), { x: 210, y: 125 }); + + expect(after.x).toBeCloseTo(before.x); + expect(after.y).toBeCloseTo(before.y); + }); + + it("leaves the zoom alone when the pointers start on the same spot", () => { + expect(pinch(view, pair(100, 100, 100, 100), pair(100, 100, 160, 100), LIMITS).zoom).toBe(1); + }); +}); + +function pointerEvent(type: string, target: EventTarget, init: { id: number; x: number; y: number; pointerType?: string; primary?: boolean }): Event { + // jsdom has no PointerEvent, so an Event carries the fields the handlers read. + const event = new Event(type, { bubbles: true, cancelable: true }); + Object.defineProperties(event, { + pointerId: { value: init.id }, + pointerType: { value: init.pointerType ?? "touch" }, + isPrimary: { value: init.primary ?? init.id === 1 }, + clientX: { value: init.x }, + clientY: { value: init.y } + }); + target.dispatchEvent(event); + return event; +} + +describe("CanvasGestures", () => { + let root: HTMLDivElement; + let canvas: HTMLCanvasElement; + let button: HTMLButtonElement; + let view: View; + let onStart: jest.Mock; + let gestures: CanvasGestures; + + beforeEach(() => { + document.body.innerHTML = ""; + root = document.createElement("div"); + canvas = document.createElement("canvas"); + button = document.createElement("button"); + root.append(canvas, button); + document.body.append(root); + jest.spyOn(canvas, "getBoundingClientRect").mockReturnValue({ left: 10, top: 20, width: 800, height: 600 } as DOMRect); + + view = { x: 0, y: 0, zoom: 1 }; + onStart = jest.fn(); + gestures = new CanvasGestures(root, canvas, { + getView: () => view, + setView: next => { + view = next; + }, + limits: LIMITS, + onStart + }); + }); + + afterEach(() => gestures.dispose()); + + const twoFingers = (): void => { + pointerEvent("pointerdown", canvas, { id: 1, x: 110, y: 120 }); + pointerEvent("pointerdown", canvas, { id: 2, x: 210, y: 120 }); + }; + + it("zooms around the midpoint in canvas coordinates when two pointers spread", () => { + twoFingers(); + + pointerEvent("pointermove", canvas, { id: 1, x: 60, y: 120 }); + pointerEvent("pointermove", canvas, { id: 2, x: 260, y: 120 }); + + expect(view.zoom).toBeCloseTo(2); + // The midpoint is (150, 100) on the canvas: client (160, 120) less the canvas offset (10, 20). + expect(worldAt(view, { x: 150, y: 100 }).x).toBeCloseTo(150); + expect(worldAt(view, { x: 150, y: 100 }).y).toBeCloseTo(100); + }); + + it("pans when both pointers move together", () => { + twoFingers(); + + pointerEvent("pointermove", canvas, { id: 1, x: 140, y: 100 }); + pointerEvent("pointermove", canvas, { id: 2, x: 240, y: 100 }); + + expect(view.zoom).toBeCloseTo(1); + expect(view.x).toBeCloseTo(30); + expect(view.y).toBeCloseTo(-20); + }); + + it("starts the gesture once, when the second pointer lands, and keeps that pointer from the canvas", () => { + const reachedCanvas = jest.fn(); + canvas.addEventListener("pointerdown", reachedCanvas); + + pointerEvent("pointerdown", canvas, { id: 1, x: 110, y: 120 }); + expect(onStart).not.toHaveBeenCalled(); + + pointerEvent("pointerdown", canvas, { id: 2, x: 210, y: 120 }); + pointerEvent("pointerdown", canvas, { id: 3, x: 310, y: 120 }); + + expect(onStart).toHaveBeenCalledTimes(1); + expect(reachedCanvas).toHaveBeenCalledTimes(1); + }); + + it("leaves a single pointer to the canvas", () => { + const reachedCanvas = jest.fn(); + canvas.addEventListener("pointerdown", reachedCanvas); + + pointerEvent("pointerdown", canvas, { id: 1, x: 110, y: 120 }); + pointerEvent("pointermove", canvas, { id: 1, x: 300, y: 300 }); + + expect(reachedCanvas).toHaveBeenCalledTimes(1); + expect(view).toEqual({ x: 0, y: 0, zoom: 1 }); + }); + + it("stops transforming once a pointer lifts, and again if it lands later", () => { + twoFingers(); + pointerEvent("pointerup", canvas, { id: 2, x: 210, y: 120 }); + + pointerEvent("pointermove", canvas, { id: 1, x: 400, y: 400 }); + + expect(view).toEqual({ x: 0, y: 0, zoom: 1 }); + pointerEvent("pointerdown", canvas, { id: 4, x: 210, y: 120 }); + expect(onStart).toHaveBeenCalledTimes(2); + }); + + it("forgets a pointer the browser cancelled", () => { + twoFingers(); + pointerEvent("pointercancel", canvas, { id: 2, x: 210, y: 120 }); + + pointerEvent("pointermove", canvas, { id: 1, x: 400, y: 400 }); + + expect(view).toEqual({ x: 0, y: 0, zoom: 1 }); + }); + + it("ignores a mouse, which keeps its own wheel and middle-button handling", () => { + const reachedCanvas = jest.fn(); + canvas.addEventListener("pointerdown", reachedCanvas); + + pointerEvent("pointerdown", canvas, { id: 1, x: 110, y: 120, pointerType: "mouse" }); + pointerEvent("pointerdown", canvas, { id: 2, x: 210, y: 120, pointerType: "mouse" }); + + expect(onStart).not.toHaveBeenCalled(); + expect(reachedCanvas).toHaveBeenCalledTimes(2); + }); + + it("ignores pointers that start on something other than the canvas", () => { + pointerEvent("pointerdown", canvas, { id: 1, x: 110, y: 120 }); + pointerEvent("pointerdown", button, { id: 2, x: 210, y: 120 }); + + expect(onStart).not.toHaveBeenCalled(); + }); + + it("stops Safari zooming the page while a touch pinch is on the canvas, and only then", () => { + const idle = new Event("gesturestart", { bubbles: true, cancelable: true }); + canvas.dispatchEvent(idle); + expect(idle.defaultPrevented).toBe(false); + + twoFingers(); + const overCanvas = new Event("gesturestart", { bubbles: true, cancelable: true }); + const overButton = new Event("gesturechange", { bubbles: true, cancelable: true }); + canvas.dispatchEvent(overCanvas); + button.dispatchEvent(overButton); + + expect(overCanvas.defaultPrevented).toBe(true); + expect(overButton.defaultPrevented).toBe(false); + }); + + it("forgets pointers whose end never arrived when a new touch sequence begins", () => { + twoFingers(); + expect(onStart).toHaveBeenCalledTimes(1); + + // Neither pointerup reached the root, so a fresh primary touch is a one-finger tap and not a second finger. + const reachedCanvas = jest.fn(); + canvas.addEventListener("pointerdown", reachedCanvas); + pointerEvent("pointerdown", canvas, { id: 7, x: 110, y: 120, primary: true }); + + expect(onStart).toHaveBeenCalledTimes(1); + expect(reachedCanvas).toHaveBeenCalledTimes(1); + }); + + it("removes every listener it added when disposed", () => { + const added = jest.spyOn(root, "addEventListener"); + const removed = jest.spyOn(root, "removeEventListener"); + const other = new CanvasGestures(root, canvas, { getView: () => view, setView: jest.fn(), limits: LIMITS, onStart }); + + other.dispose(); + + expect(added.mock.calls.length).toBeGreaterThan(0); + expect(removed.mock.calls).toHaveLength(added.mock.calls.length); + expect(removed.mock.calls).toEqual(expect.arrayContaining(added.mock.calls)); + }); + + it("stops listening when disposed", () => { + gestures.dispose(); + + twoFingers(); + + expect(onStart).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/selection-handles-gesture.test.ts b/tests/selection-handles-gesture.test.ts new file mode 100644 index 00000000..55b923b4 --- /dev/null +++ b/tests/selection-handles-gesture.test.ts @@ -0,0 +1,117 @@ +/** + * @jest-environment jsdom + */ + +import type { Edit } from "@core/edit-session"; +import { InternalEvent } from "@core/events/edit-events"; +import { EventEmitter } from "@core/events/event-emitter"; +import { SelectionHandles } from "@core/ui/selection-handles"; + +// earcut is ESM-only, which jest cannot require. Nothing drawn here needs triangulating. +jest.mock("earcut", () => ({ __esModule: true, default: () => [] })); + +// jsdom has no structuredClone, which the drag code uses. +if (typeof structuredClone === "undefined") { + global.structuredClone = (value: unknown) => JSON.parse(JSON.stringify(value)); +} + +const initial = { id: "clip-1", offset: { x: 0.1, y: 0.2 }, width: 400, height: 300, transform: { rotate: { angle: 10 } } }; +const resized = { width: 500, height: 350, offset: { x: 0.3, y: 0.4 } }; + +// Each interaction, the flag that marks it, and what it writes to the document as it moves. +const INTERACTIONS: Array<[string, Record, Record, string[]]> = [ + ["a drag", { isDragging: true }, { offset: { x: 0.4, y: 0.5 } }, ["offset"]], + ["a corner resize", { scaleDirection: "bottomRight" }, resized, ["width", "height", "offset"]], + ["an edge resize", { edgeDragDirection: "left" }, resized, ["width", "height", "offset"]], + ["a rotation", { isRotating: true }, { transform: { rotate: { angle: 30 } } }, ["transform"]] +]; + +describe("SelectionHandles when a second pointer lands", () => { + let internal: EventEmitter; + let edit: { [name: string]: jest.Mock }; + let handles: SelectionHandles; + let state: Record; + let disposed = false; + + beforeEach(() => { + disposed = false; + internal = new EventEmitter(); + edit = { + updateClipInDocument: jest.fn(), + resolveClip: jest.fn(), + commitClipUpdate: jest.fn(), + clearAlignmentGuides: jest.fn() + }; + const editStub = { ...edit, events: new EventEmitter(), getInternalEvents: () => internal } as unknown as Edit; + handles = new SelectionHandles(editStub); + state = handles as unknown as Record; + state["selectedPlayer"] = { clipConfiguration: initial, notifyDimensionsChanged: jest.fn() }; + state["selectedClipId"] = "clip-1"; + state["initialClipConfiguration"] = structuredClone(initial); + }); + + afterEach(() => { + if (!disposed) handles.dispose(); + }); + + const release = (): void => (state["onPointerUp"] as () => void)(); + const cancel = (): void => internal.emit(InternalEvent.CanvasGestureStarted); + + it("commits a drag when the pointer lifts, if nothing interrupts it", () => { + Object.assign(state, { isDragging: true, finalDragState: { offset: { x: 0.4, y: 0.5 } } }); + + release(); + + expect(edit["commitClipUpdate"]).toHaveBeenCalledTimes(1); + }); + + it.each(INTERACTIONS)("puts back only what %s moved, and leaves no edit behind", (_name, flag, moved, keys) => { + Object.assign(state, flag, { finalDragState: moved }); + + cancel(); + + expect(edit["updateClipInDocument"]).toHaveBeenCalledTimes(1); + const [clipId, restored] = edit["updateClipInDocument"].mock.calls[0]; + expect(clipId).toBe("clip-1"); + expect(Object.keys(restored).sort()).toEqual([...keys].sort()); + keys.forEach(key => expect(restored[key]).toEqual(initial[key as keyof typeof initial])); + expect(edit["resolveClip"]).toHaveBeenCalledWith("clip-1"); + Object.keys(flag).forEach(name => expect([false, null]).toContain(state[name])); + + release(); + + expect(edit["commitClipUpdate"]).not.toHaveBeenCalled(); + expect(edit["clearAlignmentGuides"]).toHaveBeenCalled(); + }); + + it.each(INTERACTIONS)("leaves the document alone when the second pointer lands before %s has moved", (_name, flag) => { + Object.assign(state, flag, { finalDragState: null }); + + cancel(); + release(); + + expect(edit["updateClipInDocument"]).not.toHaveBeenCalled(); + expect(edit["resolveClip"]).not.toHaveBeenCalled(); + expect(edit["commitClipUpdate"]).not.toHaveBeenCalled(); + Object.keys(flag).forEach(name => expect([false, null]).toContain(state[name])); + }); + + it("does nothing when no drag is in progress", () => { + state["finalDragState"] = { offset: { x: 0.4, y: 0.5 } }; + + cancel(); + + expect(edit["updateClipInDocument"]).not.toHaveBeenCalled(); + expect(edit["resolveClip"]).not.toHaveBeenCalled(); + }); + + it("stops listening when disposed", () => { + handles.dispose(); + disposed = true; + Object.assign(state, { isDragging: true, finalDragState: { offset: { x: 0.4, y: 0.5 } } }); + + cancel(); + + expect(edit["updateClipInDocument"]).not.toHaveBeenCalled(); + }); +});