aboutsummaryrefslogtreecommitdiff
path: root/src/web/pinch.js
blob: 935dfa0581c76849c55401265f4d6ce226f8460f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class Pinch {
	constructor(element) {
		this.event_cache = [];
		this.previous_diff = null;
		this.onpinch = () => {};
		this.onfinish = () => {};
		this.onstart = () => {};

		element.onpointerdown = (e) => this.pointer_down_handler(e);
		element.onpointermove = (e) => this.pointer_move_handler(e);
		element.onpointerup = (e) => this.pointer_up_handler(e);
		element.onpointercancel = (e) => this.pointer_up_handler(e);
		element.onpointerout = (e) => this.pointer_up_handler(e);
		element.onpointerleave = (e) => this.pointer_up_handler(e);
	}

	pointer_down_handler(event) {
		this.event_cache.push(event);

		if (this.event_cache.length === 2) {
			const point = {
				x: (this.event_cache[0].clientX + this.event_cache[1].clientX) / 2,
				y: (this.event_cache[0].clientY + this.event_cache[1].clientY) / 2,
			};

			this.onstart({ point });
		}
	}

	pointer_move_handler(event) {
		const index = this.event_cache.findIndex(
			(cached) => cached.pointerId == event.pointerId,
		);
		this.event_cache[index] = event;

		if (this.event_cache.length === 2) {
			event.preventDefault();

			const diff = Math.hypot(
				this.event_cache[0].clientX - this.event_cache[1].clientX,
				this.event_cache[0].clientY - this.event_cache[1].clientY,
			);

			if (this.previous_diff != null) {
				const point = {
					x: (this.event_cache[0].clientX + this.event_cache[1].clientX) / 2,
					y: (this.event_cache[0].clientY + this.event_cache[1].clientY) / 2,
				};

				const delta = this.previous_diff - diff;
				this.onpinch({ zoom_delta: delta, point });
			}

			this.previous_diff = diff;
		}
	}

	pointer_up_handler(event) {
		let cleanup = false;
		if (this.event_cache.length === 2) {
			cleanup = true;
		}

		const index = this.event_cache.findIndex(
			(cached) => cached.pointerId === event.pointerId,
		);
		this.event_cache.splice(index, 1);

		if (this.event_cache.length < 2) {
			this.previous_diff = null;
		}

		if (cleanup) {
			this.onfinish();
		}
	}
}