Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions src/components/canvas/canvas-gestures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand All @@ -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<number, Point>();

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();
};
}
12 changes: 11 additions & 1 deletion src/components/canvas/shotstack-canvas.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
Expand Down
2 changes: 2 additions & 0 deletions src/core/events/edit-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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 };
Expand Down
26 changes: 26 additions & 0 deletions src/core/ui/selection-handles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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 {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<ResolvedClip> = {};
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 {
Expand Down
62 changes: 60 additions & 2 deletions tests/canvas-dispose.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 },
Expand Down Expand Up @@ -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();
});
});
});
Loading
Loading