blob: c7ae304d1efbc129777ace560fd374c10e34b146 (
plain) (
blame)
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
|
import { Vec2 } from "./vector";
export class MouseController {
private last_event_time = Date.now();
private last_movement: Vec2 | undefined;
private interval_id: number | undefined;
constructor(
private readonly publisher: (new_movement: Vec2) => void | Promise<void>,
private readonly debounce_ms = 200,
private readonly l2_norm_threshold = 40,
) {}
public start() {
if (typeof this.interval_id !== "undefined") {
return;
}
this.interval_id = setInterval(
() => this.publish_movement(),
this.debounce_ms,
);
}
public stop() {
if (this.interval_id === null) {
return;
}
clearInterval(this.interval_id);
delete this.interval_id;
}
public move(x: number, y: number) {
const new_movement = new Vec2(x, y);
if (
typeof this.last_movement !== "undefined" &&
new_movement.distance_to(this.last_movement) >= this.l2_norm_threshold
) {
this.publish_movement();
}
this.last_movement = new_movement;
}
private publish_movement() {
if (
typeof this.last_movement === "undefined" ||
Date.now() - this.last_event_time < this.debounce_ms
) {
return;
}
this.last_event_time = Date.now();
this.publisher(this.last_movement.copy());
delete this.last_movement;
}
}
|