diff --git a/src/components/canvas/canvas-gestures.ts b/src/components/canvas/canvas-gestures.ts index fd347d2e..17b16cc1 100644 --- a/src/components/canvas/canvas-gestures.ts +++ b/src/components/canvas/canvas-gestures.ts @@ -15,7 +15,7 @@ export interface ZoomLimits { max: number; } -type Pair = [Point, Point]; +export type Pair = [Point, Point]; const clamp = (value: number, { min, max }: ZoomLimits): number => Math.min(Math.max(value, min), max); @@ -38,17 +38,32 @@ export function pinch(view: View, from: Pair, to: Pair, limits: ZoomLimits): Vie return { ...zoomed, x: zoomed.x + after.x - before.x, y: zoomed.y + after.y - before.y }; } +/** Takes a two-finger gesture over from the canvas: `move` gets where the fingers landed and where they are now, in client pixels. */ +export interface PinchTarget { + move: (landed: Pair, now: Pair) => void; + end: () => void; + /** The platform took a finger, or the sequence lost its end: whatever the gesture changed goes back. */ + cancel: () => void; +} + +/** A two-finger gesture starting on the canvas. A listener that claims it takes it over from the canvas. */ +export interface CanvasGesture { + claim: (pinch: PinchTarget) => void; +} + 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; + /** The second pointer has landed: whatever one pointer was doing has to stop. A target returned takes the gesture over. */ + onStart: () => PinchTarget | undefined; } -/** Two touches on the canvas pinch and pan it. One touch, a mouse, or anything that starts off the canvas is left alone. */ +/** Two touches on the canvas pinch and pan it, unless the start hands them to a target. One touch, a mouse, or anything that starts off the canvas is left alone. */ export class CanvasGestures { private readonly pointers = new Map(); + private target: PinchTarget | undefined; + private landed = new Map(); constructor( private readonly root: HTMLElement, @@ -77,14 +92,20 @@ export class CanvasGestures { 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.isPrimary) { + this.pointers.clear(); + this.target?.cancel(); + this.release(); + } 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(); + if (this.pointers.size !== 2) return; + this.target = this.options.onStart(); + if (this.target) this.landed = new Map(this.pointers); }; private onMove = (e: PointerEvent): void => { @@ -93,6 +114,11 @@ export class CanvasGestures { this.pointers.set(e.pointerId, { x: e.clientX, y: e.clientY }); if (this.pointers.size !== 2) return; + // A third finger lifting leaves the target's own two, in the order they landed. + if (this.target) { + this.target.move([...this.landed.values()] as Pair, [...this.pointers.values()] as Pair); + return; + } const { left, top } = this.canvas.getBoundingClientRect(); const local = (point: Point): Point => ({ x: point.x - left, y: point.y - top }); @@ -104,8 +130,18 @@ export class CanvasGestures { private onEnd = (e: PointerEvent): void => { this.pointers.delete(e.pointerId); + if (!this.landed.has(e.pointerId)) return; + + if (e.type === "pointercancel") this.target?.cancel(); + else this.target?.end(); + this.release(); }; + private release(): void { + this.target = undefined; + this.landed.clear(); + } + // 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 4946b655..41793eba 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 { CanvasGestures, zoomAbout, type View } from "@canvas/canvas-gestures"; +import { CanvasGestures, zoomAbout, type PinchTarget, 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"; @@ -161,7 +161,15 @@ export class Canvas { getView: () => this.getView(), setView: view => this.setView(view), limits: this.zoomLimits, - onStart: () => this.edit.getInternalEvents().emit(InternalEvent.CanvasGestureStarted) + onStart: () => { + let pinch: PinchTarget | undefined; + this.edit.getInternalEvents().emit(InternalEvent.CanvasGestureStarted, { + claim: target => { + pinch = target; + } + }); + return pinch; + } }); } diff --git a/src/core/events/edit-events.ts b/src/core/events/edit-events.ts index 148f5c3b..256930ea 100644 --- a/src/core/events/edit-events.ts +++ b/src/core/events/edit-events.ts @@ -1,3 +1,4 @@ +import type { CanvasGesture } from "@canvas/canvas-gestures"; import type { Player } from "@canvas/players/player"; import type { MergeField } from "@core/merge/types"; import type { Clip, Destination, Edit as EditConfig, Output, ResolvedEdit } from "@schemas"; @@ -215,7 +216,7 @@ export type InternalEventMap = { [InternalEvent.CanvasClipClicked]: { player: Player }; [InternalEvent.CanvasClipDoubleClicked]: { player: Player }; [InternalEvent.CanvasBackgroundClicked]: void; - [InternalEvent.CanvasGestureStarted]: void; + [InternalEvent.CanvasGestureStarted]: CanvasGesture; // Font [InternalEvent.FontCapabilitiesChanged]: { supportsBold: boolean }; diff --git a/src/core/ui/selection-handles.ts b/src/core/ui/selection-handles.ts index 340ea808..defd4047 100644 --- a/src/core/ui/selection-handles.ts +++ b/src/core/ui/selection-handles.ts @@ -1,3 +1,4 @@ +import type { CanvasGesture, Pair } from "@canvas/canvas-gestures"; import type { Player } from "@canvas/players/player"; import type { Edit } from "@core/edit-session"; import { EditEvent, InternalEvent } from "@core/events/edit-events"; @@ -7,7 +8,9 @@ import { clampDimensions, roundDimensions, detectCornerZone, - detectEdgeZone + detectEdgeZone, + INTERACTION_CONSTANTS, + type OriginalDimensions } from "@core/interaction/clip-interaction"; import { SELECTION_CONSTANTS, @@ -25,6 +28,7 @@ import { filterContainedClips, snap, snapRotation, + DEFAULT_ROTATION_SNAP_THRESHOLD, visualToLogical } from "@core/interaction/snap-system"; import { isKeyframedValue } from "@core/shared/clip-utils"; @@ -39,6 +43,7 @@ import type { CanvasOverlayRegistration } from "./ui-controller"; type ScaleDirection = "topLeft" | "topRight" | "bottomLeft" | "bottomRight"; type EdgeDirection = "left" | "right" | "top" | "bottom"; +type ClipChange = { offset?: Vector; width?: number; height?: number; transform?: ResolvedClip["transform"] }; /** * SelectionHandles renders selection UI (outline + resize handles) on selected players @@ -99,19 +104,18 @@ export class SelectionHandles implements CanvasOverlayRegistration { private initialClipConfiguration: ResolvedClip | null = null; // Final drag state - private finalDragState: { - offset?: { x: number; y: number }; - width?: number; - height?: number; - transform?: { rotate?: { angle: number } }; - } | null = null; + private finalDragState: ClipChange | null = null; + + // Whether the current touch sequence's first finger landed on the selected clip, handles included. + private touchOnClip = false; + private pinch: { initial: ResolvedClip; size: OriginalDimensions; angle: number; moved: ClipChange | null } | null = null; // Bound event handlers for cleanup private onClipSelectedBound: (payload: { trackIndex: number; clipIndex: number }) => void; private onSelectionClearedBound: () => void; private onClipFocusedBound: (payload: { trackIndex: number; clipIndex: number }) => void; private onClipBlurredBound: () => void; - private onGestureStartedBound: () => void; + private onGestureStartedBound: (gesture: CanvasGesture) => void; private onPointerDownBound: (event: pixi.FederatedPointerEvent) => void; private onTouchDownBound: (event: pixi.FederatedPointerEvent) => void; private onPointerMoveBound: (event: pixi.FederatedPointerEvent) => void; @@ -155,7 +159,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.onGestureStartedBound = this.onGestureStarted.bind(this); this.onPointerDownBound = this.onPointerDown.bind(this); this.onTouchDownBound = this.onTouchDown.bind(this); this.onPointerMoveBound = this.onPointerMove.bind(this); @@ -274,11 +278,15 @@ export class SelectionHandles implements CanvasOverlayRegistration { // ─── Selection Event Handlers ──────────────────────────────────────────────── private onClipSelected({ trackIndex, clipIndex }: { trackIndex: number; clipIndex: number }): void { - this.selectedPlayer = this.edit.getPlayerClip(trackIndex, clipIndex); + const player = this.edit.getPlayerClip(trackIndex, clipIndex); + // A pinch belongs to the clip it started on, so that clip goes back before the selection moves. + if (player?.clipId !== this.selectedClipId) this.dropPinch(); + this.selectedPlayer = player; this.selectedClipId = this.selectedPlayer?.clipId ?? null; } private onSelectionCleared(): void { + this.dropPinch(); this.selectedPlayer = null; this.selectedClipId = null; this.resetDragState(); @@ -501,8 +509,10 @@ export class SelectionHandles implements CanvasOverlayRegistration { } private onTouchDown(event: pixi.FederatedPointerEvent): void { + if (event.pointerType !== "touch") return; + this.touchOnClip = false; // Only what draw() shows: a clip outside the playhead's time stays selected with no handles. - if (event.pointerType !== "touch" || !this.selectedPlayer?.isActive() || this.edit.isInExportMode()) return; + if (!this.selectedPlayer?.isActive() || this.edit.isInExportMode()) return; const localPoint = event.getLocalPosition(this.selectedPlayer.getContainer()); const size = this.selectedPlayer.getSize(); @@ -525,6 +535,7 @@ export class SelectionHandles implements CanvasOverlayRegistration { inside || corner || edge ? null : detectCornerZone(localPoint, corners, handleRadius, SELECTION_CONSTANTS.TOUCH_ROTATION_HIT_ZONE / uiScale); if (!rotationCorner && !corner && !edge && !inside) return; + this.touchOnClip = true; event.stopPropagation(); this.initialClipConfiguration = structuredClone(this.selectedPlayer.clipConfiguration); if (corner) this.startCornerResize(event, corner); @@ -567,34 +578,40 @@ export class SelectionHandles implements CanvasOverlayRegistration { private onPointerUp(): void { if (!this.selectedPlayer) return; - if ( - (this.isDragging || this.scaleDirection || this.edgeDragDirection || this.isRotating) && - this.finalDragState && - this.selectedClipId && - this.initialClipConfiguration - ) { + if (this.isDragging || this.scaleDirection || this.edgeDragDirection || this.isRotating) { + this.commit(this.initialClipConfiguration, this.finalDragState, Boolean(this.scaleDirection || this.edgeDragDirection)); + } + + this.finalDragState = null; // Clear final state + this.resetDragState(); + this.edit.clearAlignmentGuides(); + } + + /** Records `moved` over `initial` as one history entry; a resize also sets the fit and a simple SVG's viewBox. */ + private commit(initial: ResolvedClip | null, moved: ClipChange | null, resized: boolean): void { + if (moved && this.selectedClipId && initial) { // Construct final config from local state with deep merge - const finalClip = structuredClone(this.initialClipConfiguration); + const finalClip = structuredClone(initial); // Deep merge for nested properties (transform, offset) - if (this.finalDragState.transform) { + if (moved.transform) { finalClip.transform = { ...finalClip.transform, - ...this.finalDragState.transform + ...moved.transform }; } - if (this.finalDragState.offset) { + if (moved.offset) { finalClip.offset = { ...finalClip.offset, - ...this.finalDragState.offset + ...moved.offset }; } // Shallow merge for flat properties (width, height) - if (this.finalDragState.width !== undefined) finalClip.width = this.finalDragState.width; - if (this.finalDragState.height !== undefined) finalClip.height = this.finalDragState.height; + if (moved.width !== undefined) finalClip.width = moved.width; + if (moved.height !== undefined) finalClip.height = moved.height; // Update SVG viewBox if this is an SVG clip resize - if ((this.scaleDirection || this.edgeDragDirection) && finalClip.asset?.type === "svg") { + if (resized && finalClip.asset?.type === "svg") { const svgAsset = finalClip.asset as SvgAsset; if (svgAsset.src && finalClip.width && finalClip.height) { // Only manipulate simple rect-based SVGs (maintains toolbar compatibility) @@ -612,24 +629,20 @@ export class SelectionHandles implements CanvasOverlayRegistration { } // Auto-set fit to "contain" for image/video clips when resizing - if ((this.scaleDirection || this.edgeDragDirection) && (finalClip.asset?.type === "image" || finalClip.asset?.type === "video")) { + if (resized && (finalClip.asset?.type === "image" || finalClip.asset?.type === "video")) { finalClip.fit = "contain"; this.edit.updateClipInDocument(this.selectedClipId, { fit: "contain" }); this.edit.resolveClip(this.selectedClipId); } // Commit with explicit final state (adds to history, doesn't execute) - this.edit.commitClipUpdate(this.selectedClipId, this.initialClipConfiguration, finalClip); + this.edit.commitClipUpdate(this.selectedClipId, initial, finalClip); - // Notify player if dimensions changed (corner or edge resize) - if ((this.scaleDirection || this.edgeDragDirection) && this.selectedPlayer) { + // Notify player if dimensions changed + if (resized && this.selectedPlayer) { this.selectedPlayer.notifyDimensionsChanged(); } } - - this.finalDragState = null; // Clear final state - this.resetDragState(); - this.edit.clearAlignmentGuides(); } private onPointerCancel(event: PointerEvent): void { @@ -658,6 +671,86 @@ export class SelectionHandles implements CanvasOverlayRegistration { this.edit.clearAlignmentGuides(); } + /** The pinch is the clip's when the first finger landed on it; otherwise it zooms the canvas. */ + private onGestureStarted(gesture: CanvasGesture): void { + this.cancelInteraction(); + if (!this.touchOnClip || !this.selectedPlayer || this.hasKeyframedOffset()) return; + + const initial = structuredClone(this.selectedPlayer.clipConfiguration); + this.captureOriginalDimensions(); + if (!this.originalDimensions) return; + + this.pinch = { initial, size: this.originalDimensions, angle: this.selectedPlayer.getRotation(), moved: null }; + gesture.claim({ move: (landed, now) => this.movePinch(landed, now), end: () => this.endPinch(), cancel: () => this.dropPinch() }); + } + + private movePinch([a, b]: Pair, [c, d]: Pair): void { + const { pinch } = this; + if (!pinch || !this.selectedPlayer || !this.selectedClipId) return; + + const { size } = pinch; + const spread = Math.hypot(b.x - a.x, b.y - a.y); + const ratio = spread > 0 ? Math.hypot(d.x - c.x, d.y - c.y) / spread : 1; + // One ratio for both sides, held within the size limits so the clip keeps its shape; a side already under the minimum doesn't grow on a pinch-in. + const { MIN_DIMENSION, MAX_WIDTH, MAX_HEIGHT } = INTERACTION_CONSTANTS; + const floor = Math.min(1, MIN_DIMENSION / Math.min(size.width, size.height)); + const held = Math.min(Math.max(ratio, floor), MAX_WIDTH / size.width, MAX_HEIGHT / size.height); + const { width, height } = roundDimensions(size.width * held, size.height * held); + + // The centre stays put: the top left moves back by half of what the size grew. + const anchor = this.selectedPlayer.clipConfiguration.position ?? "center"; + const from = absoluteToRelative(this.edit.size, size, anchor, { x: 0, y: 0 }); + const to = absoluteToRelative(this.edit.size, { width, height }, anchor, { x: (size.width - width) / 2, y: (size.height - height) / 2 }); + const moved: ClipChange = { width, height, offset: { x: size.offsetX + (to.x - from.x), y: size.offsetY + (to.y - from.y) } }; + + if (!this.hasKeyframedRotation()) { + // Wrapped to ±180°, so fingers that start level don't add a full turn as they cross it. + const twist = ((((Math.atan2(d.y - c.y, d.x - c.x) - Math.atan2(b.y - a.y, b.x - a.x)) * 180) / Math.PI + 540) % 360) - 180; + // The first 5° are a dead zone, so a resize's drift leaves a slight tilt alone, and rotation picks up from zero past it. + const turn = Math.sign(twist) * Math.max(0, Math.abs(twist) - DEFAULT_ROTATION_SNAP_THRESHOLD); + if (turn === 0) moved.transform = structuredClone(pinch.initial.transform); + else { + const { angle } = snapRotation(pinch.angle + turn); + moved.transform = { ...this.selectedPlayer.clipConfiguration.transform, rotate: { angle: angle % 360 } }; + } + } + + pinch.moved = moved; + this.edit.updateClipInDocument(this.selectedClipId, moved); + this.edit.resolveClip(this.selectedClipId); + this.showDimensionLabel(width, height); + } + + private endPinch(): void { + const { pinch } = this; + if (!pinch) return; + + const { width, height, transform } = pinch.moved ?? {}; + const resized = width !== undefined && (width !== pinch.size.width || height !== pinch.size.height); + const turned = transform?.rotate !== undefined && transform.rotate.angle !== pinch.angle; + if (!resized && !turned) { + this.dropPinch(); + return; + } + + this.pinch = null; + this.hideDimensionLabel(); + this.commit(pinch.initial, pinch.moved, resized); + } + + /** Puts the pinched clip back as it started, a size it didn't have included, with no history entry. */ + private dropPinch(): void { + const { pinch } = this; + if (!pinch) return; + this.pinch = null; + this.hideDimensionLabel(); + if (!this.selectedClipId) return; + + const { offset, width, height, transform } = pinch.initial; + this.edit.updateClipInDocument(this.selectedClipId, { offset, width, height, transform }); + this.edit.resolveClip(this.selectedClipId); + } + // ─── Drag Operations ───────────────────────────────────────────────────────── private startDrag(event: pixi.FederatedPointerEvent): void { diff --git a/tests/canvas-dispose.test.ts b/tests/canvas-dispose.test.ts index b1e30b9f..f21eeec8 100644 --- a/tests/canvas-dispose.test.ts +++ b/tests/canvas-dispose.test.ts @@ -6,6 +6,7 @@ * context underneath it is a stand-in, because jsdom has none. */ +import type { CanvasGesture } from "@canvas/canvas-gestures"; import { Canvas } from "@canvas/shotstack-canvas"; import type { Edit } from "@core/edit-session"; import { InternalEvent } from "@core/events/edit-events"; @@ -159,6 +160,24 @@ describe("Canvas dispose", () => { expect(started(emit)).toBe(1); }); + it("hands the pinch to a listener that claims it, and leaves the zoom alone", async () => { + const pinch = { move: jest.fn(), end: jest.fn(), cancel: jest.fn() }; + const emit = jest.fn((...args: unknown[]) => { + const [name, gesture] = args as [string, CanvasGesture | undefined]; + if (name === InternalEvent.CanvasGestureStarted) gesture?.claim(pinch); + }); + const canvas = new Canvas(makeEdit(0, emit)); + await canvas.load(); + canvas.application.stop(); + const before = canvas.getZoom(); + + pinchOut(canvas.application.canvas); + + expect(pinch.move).toHaveBeenCalled(); + expect(canvas.getZoom()).toBe(before); + canvas.dispose(); + }); + it("tracks pointers once, however many times the root is set up", async () => { const emit = jest.fn(); const canvas = new Canvas(makeEdit(0, emit)); diff --git a/tests/canvas-gestures.test.ts b/tests/canvas-gestures.test.ts index dee3c907..371799fb 100644 --- a/tests/canvas-gestures.test.ts +++ b/tests/canvas-gestures.test.ts @@ -226,6 +226,55 @@ describe("CanvasGestures", () => { expect(overButton.defaultPrevented).toBe(false); }); + describe("when the start hands the gesture to a target", () => { + const target = { move: jest.fn(), end: jest.fn(), cancel: jest.fn() }; + + beforeEach(() => { + Object.values(target).forEach(fn => fn.mockClear()); + onStart.mockReturnValue(target); + }); + + it("gives it where the fingers landed and where they are, and leaves the view alone", () => { + twoFingers(); + + pointerEvent("pointermove", canvas, { id: 1, x: 60, y: 120 }); + pointerEvent("pointermove", canvas, { id: 2, x: 260, y: 150 }); + + expect(target.move).toHaveBeenLastCalledWith(pair(110, 120, 210, 120), pair(60, 120, 260, 150)); + expect(view).toEqual({ x: 0, y: 0, zoom: 1 }); + const zoom = new Event("gesturechange", { bubbles: true, cancelable: true }); + canvas.dispatchEvent(zoom); + expect(zoom.defaultPrevented).toBe(true); + }); + + it("ends it once, when one of its fingers lifts", () => { + twoFingers(); + + pointerEvent("pointerup", canvas, { id: 2, x: 210, y: 120 }); + pointerEvent("pointermove", canvas, { id: 1, x: 400, y: 400 }); + pointerEvent("pointerup", canvas, { id: 1, x: 400, y: 400 }); + + expect(target.end).toHaveBeenCalledTimes(1); + expect(target.move).not.toHaveBeenCalled(); + expect(view).toEqual({ x: 0, y: 0, zoom: 1 }); + }); + + it.each([ + ["the platform cancels one of its fingers", (): unknown => pointerEvent("pointercancel", canvas, { id: 2, x: 210, y: 120 })], + [ + "a new touch sequence starts before its fingers lifted", + (): unknown => pointerEvent("pointerdown", canvas, { id: 7, x: 110, y: 120, primary: true }) + ] + ])("cancels it, rather than ending it, when %s", (_when, interrupt) => { + twoFingers(); + + interrupt(); + + expect(target.cancel).toHaveBeenCalledTimes(1); + expect(target.end).not.toHaveBeenCalled(); + }); + }); + it("forgets pointers whose end never arrived when a new touch sequence begins", () => { twoFingers(); expect(onStart).toHaveBeenCalledTimes(1); diff --git a/tests/selection-handles-gesture.test.ts b/tests/selection-handles-gesture.test.ts index 55b923b4..4af407d5 100644 --- a/tests/selection-handles-gesture.test.ts +++ b/tests/selection-handles-gesture.test.ts @@ -55,7 +55,7 @@ describe("SelectionHandles when a second pointer lands", () => { }); const release = (): void => (state["onPointerUp"] as () => void)(); - const cancel = (): void => internal.emit(InternalEvent.CanvasGestureStarted); + const cancel = (): void => internal.emit(InternalEvent.CanvasGestureStarted, { claim: () => {} }); 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 } } }); diff --git a/tests/selection-handles-pinch.test.ts b/tests/selection-handles-pinch.test.ts new file mode 100644 index 00000000..2b4cd54f --- /dev/null +++ b/tests/selection-handles-pinch.test.ts @@ -0,0 +1,313 @@ +/** + * @jest-environment node + */ + +import type { Pair, PinchTarget } from "@canvas/canvas-gestures"; +import type { Player } from "@canvas/players/player"; +import type { Edit } from "@core/edit-session"; +import { InternalEvent } from "@core/events/edit-events"; +import type * as pixi from "pixi.js"; + +import selectOnEdit from "./helpers/selection-handles-edit"; + +describe("SelectionHandles two-finger pinch on the selected clip", () => { + let harness: Awaited>; + let edit: Edit; + let player: Player; + let stage: pixi.Container; + + const load = async (clip: Record = {}, later: Record[] = []): Promise => { + harness = await selectOnEdit(clip, later); + ({ edit, player, stage } = harness); + }; + + afterEach(() => harness.dispose()); + + const touchEvent = (x: number, y: number): pixi.FederatedPointerEvent => harness.touchEvent(x, y); + const touch = (x: number, y: number, target?: unknown): void => harness.touch(x, y, target); + const history = (): number => harness.history(); + + const secondFinger = (): PinchTarget | undefined => { + let pinch: PinchTarget | undefined; + edit.getInternalEvents().emit(InternalEvent.CanvasGestureStarted, { + claim: target => { + pinch = target; + } + }); + return pinch; + }; + + const fingers = (spread: number, degrees = 0): Pair => { + const radians = (degrees * Math.PI) / 180; + return [ + { x: 300, y: 300 }, + { x: 300 + spread * Math.cos(radians), y: 300 + spread * Math.sin(radians) } + ]; + }; + + const centre = (): { x: number; y: number } => { + const { x, y } = player.getPosition(); + const { width, height } = player.getSize(); + return { x: x + width / 2, y: y + height / 2 }; + }; + + it.each(["center", "topLeft"])("doubles a %s-anchored image about its centre on a 100 to 200 px spread, in one history entry", async position => { + await load({ position }); + const before = centre(); + const entries = history(); + + touch(200, 150); + const pinch = secondFinger(); + pinch?.move(fingers(100), fingers(200)); + pinch?.end(); + + expect(pinch).toBeDefined(); + expect(player.clipConfiguration).toMatchObject({ width: 800, height: 600, fit: "contain" }); + expect(player.clipConfiguration.scale).toBeUndefined(); + expect(centre().x).toBeCloseTo(before.x); + expect(centre().y).toBeCloseTo(before.y); + expect(history()).toBe(entries + 1); + }); + + it.each([ + ["grows a 400 × 300 clip only as far as its height allows", {}, 2000, { width: 2880, height: 2160 }], + ["shrinks a 1000 × 80 clip only as far as its height allows", { width: 1000, height: 80 }, 50, { width: 625, height: 50 }] + ])("keeps the shape at the size limits: %s", async (_name, clip, spread, size) => { + await load(clip); + + touch(10, 10); + const pinch = secondFinger(); + pinch?.move(fingers(100), fingers(spread)); + pinch?.end(); + + expect(player.clipConfiguration).toMatchObject(size); + }); + + it.each([ + ["a 1000 × 40 clip pinched in stays as it is", { width: 1000, height: 40 }, 50, { width: 1000, height: 40 }, 0], + ["a 1000 × 4 line pinched in stays as it is", { width: 1000, height: 4 }, 50, { width: 1000, height: 4 }, 0], + ["a 1000 × 40 clip pinched out doubles", { width: 1000, height: 40 }, 200, { width: 2000, height: 80 }, 1] + ])("never grows a clip already under the minimum size on a pinch-in: %s", async (_name, clip, spread, size, added) => { + await load(clip); + const entries = history(); + const { width, height } = player.getSize(); + + touch(width / 2, height / 2); + const pinch = secondFinger(); + pinch?.move(fingers(100), fingers(spread)); + pinch?.end(); + + expect(player.clipConfiguration).toMatchObject(size); + expect(history()).toBe(entries + added); + }); + + it.each([ + [ + "records nothing for a pinch that ends where it started", + [ + [200, 4], + [100, 0] + ], + 0, + 400 + ], + ["keeps the tilt through a resize with a small twist", [[200, 4]], 1, 800] + ])("leaves a clip tilted 3° alone: %s", async (_name, moves, entriesAdded, width) => { + await load({ transform: { rotate: { angle: 3 } } }); + const entries = history(); + + touch(200, 150); + const pinch = secondFinger(); + moves.forEach(([spread, twist]) => pinch?.move(fingers(100), fingers(spread, twist))); + pinch?.end(); + + expect(player.getRotation()).toBe(3); + expect(player.clipConfiguration.width).toBe(width); + expect(history()).toBe(entries + entriesAdded); + }); + + it.each([ + ["another clip is selected", (): void => edit.selectClip(0, 1)], + ["the selection clears", (): void => edit.clearSelection()] + ])("puts its clip back, with no history, when %s mid-pinch", async (_name, moveSelection) => { + await load({}, [{ width: 200, height: 100 }]); + const other = edit.getPlayerClip(0, 1) as Player; + const before = structuredClone(player.clipConfiguration); + const otherBefore = structuredClone(other.clipConfiguration); + const entries = history(); + + touch(200, 150); + const pinch = secondFinger(); + pinch?.move(fingers(100), fingers(200)); + moveSelection(); + pinch?.move(fingers(100), fingers(300)); + pinch?.end(); + + expect(player.clipConfiguration).toEqual(before); + expect(other.clipConfiguration).toEqual(otherBefore); + expect(history()).toBe(entries); + }); + + it("adds a twist, less the 5° dead zone, to the rotation, and one undo puts back both the size and the angle", async () => { + await load(); + const entries = history(); + + touch(200, 150); + const pinch = secondFinger(); + pinch?.move(fingers(100), fingers(150, 30)); + pinch?.end(); + + expect(player.clipConfiguration).toMatchObject({ width: 600, height: 450 }); + expect(player.getRotation()).toBeCloseTo(25); + expect(history()).toBe(entries + 1); + + await edit.undo(); + + expect(player.clipConfiguration).toMatchObject({ width: 400, height: 300 }); + expect(player.getRotation()).toBe(0); + }); + + it("snaps a twist as the rotation handle does, and leaves the fit alone when the size holds", async () => { + await load(); + const { fit } = player.clipConfiguration; + + touch(200, 150); + const pinch = secondFinger(); + pinch?.move(fingers(100), fingers(100, 47)); + pinch?.end(); + + expect(player.getRotation()).toBe(45); + expect(player.clipConfiguration.fit).toBe(fit); + }); + + it("turns by the short way when the fingers cross from 170° to -170°", async () => { + await load(); + + touch(200, 150); + const pinch = secondFinger(); + pinch?.move(fingers(100, 170), fingers(100, -170)); + pinch?.end(); + + expect(player.getRotation()).toBeCloseTo(15); + }); + + it("turns a clip at 20° by 1° for a 6° twist", async () => { + await load({ transform: { rotate: { angle: 20 } } }); + + touch(200, 150); + const pinch = secondFinger(); + pinch?.move(fingers(100), fingers(100, 6)); + pinch?.end(); + + expect(player.getRotation()).toBeCloseTo(21); + }); + + it("doesn't flip a clip at 20° as the twist wavers across the dead zone's edge", async () => { + await load({ transform: { rotate: { angle: 20 } } }); + + touch(200, 150); + const pinch = secondFinger(); + const angles = [4.9, 5.1, 4.9, 5.1, 4.9].map(twist => { + pinch?.move(fingers(100), fingers(100, twist)); + return player.getRotation(); + }); + pinch?.end(); + + angles.slice(1).forEach((angle, i) => expect(Math.abs(angle - angles[i])).toBeLessThanOrEqual(0.1 + 1e-9)); + }); + + it("puts its clip back, with no history, when the platform cancels the pinch", async () => { + await load(); + const initial = structuredClone(player.clipConfiguration); + const entries = history(); + + touch(200, 150); + const pinch = secondFinger(); + pinch?.move(fingers(100), fingers(200, 30)); + pinch?.cancel(); + + expect(player.clipConfiguration).toEqual(initial); + expect(history()).toBe(entries); + }); + + it("keeps pinching when its own clip is selected again", async () => { + await load(); + const entries = history(); + + touch(200, 150); + const pinch = secondFinger(); + pinch?.move(fingers(100), fingers(150)); + edit.selectClip(0, 0); + pinch?.move(fingers(100), fingers(200)); + pinch?.end(); + + expect(player.clipConfiguration).toMatchObject({ width: 800, height: 600 }); + expect(history()).toBe(entries + 1); + }); + + it("leaves the pinch to the canvas when the first finger landed off the clip, whatever an earlier touch hit", async () => { + await load(); + touch(200, 150); + stage.emit("pointerup", touchEvent(200, 150)); + + touch(-300, -300, {}); + + expect(secondFinger()).toBeUndefined(); + expect(player.clipConfiguration).toMatchObject({ width: 400, height: 300 }); + }); + + it("puts back a drag the first finger started, then resizes from there, in one history entry", async () => { + await load(); + const offset = { ...player.clipConfiguration.offset }; + const entries = history(); + + touch(200, 150); + stage.emit("globalpointermove", touchEvent(300, 250)); + expect(player.clipConfiguration.offset).not.toEqual(offset); + + const pinch = secondFinger(); + pinch?.move(fingers(100), fingers(200)); + pinch?.end(); + + expect(player.clipConfiguration).toMatchObject({ width: 800, height: 600, offset }); + expect(history()).toBe(entries + 1); + }); + + it("leaves the pinch to the canvas over a selected clip that's off screen", async () => { + await load({ start: 1 }); + + touch(200, 150, {}); + + expect(player.isActive()).toBe(false); + expect(secondFinger()).toBeUndefined(); + }); + + it("leaves the pinch to the canvas for a clip whose offset is keyframed", async () => { + await load(); + player.clipConfiguration.offset = { x: [{ from: 0, to: 0.2, start: 0, length: 1, interpolation: "linear" }], y: 0 }; + + touch(200, 150); + + expect(secondFinger()).toBeUndefined(); + }); + + it.each([ + ["with an explicit size", {}], + ["filling the edit", { width: undefined, height: undefined }] + ])("records nothing for a pinch that ends where it started, on a clip %s", async (_name, clip) => { + await load(clip); + const initial = structuredClone(player.clipConfiguration); + const entries = history(); + const { width, height } = player.getSize(); + + touch(width / 2, height / 2); + const pinch = secondFinger(); + pinch?.move(fingers(100), fingers(200)); + pinch?.move(fingers(100), fingers(100)); + pinch?.end(); + + expect(pinch).toBeDefined(); + expect(history()).toBe(entries); + expect(player.clipConfiguration).toEqual(initial); + }); +});