aboutsummaryrefslogtreecommitdiff
path: root/static/src/mouse_controller.ts
blob: b8849b4d98899cf26f6f1da2533f33caed5012e5 (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 readonly debounce_ms = 400;
  private readonly movement_threshold = 40;
  private last_event_time = Date.now();
  private movement_queue: Vec2[] = [];
  private interval_id: number | null = null;

  constructor(private readonly callback: (new_movement: Vec2) => void) {}

  public start() {
    if (this.interval_id !== null) {
      return;
    }
    this.interval_id = setInterval(() => {
      this.publish_movement();
    }, this.debounce_ms);
  }

  public stop() {
    if (this.interval_id === null) {
      return;
    }
    clearInterval(this.interval_id);
    this.interval_id = null;
  }

  public move(x: number, y: number) {
    const new_movement = new Vec2(x, y);
    const last_movement = this.movement_queue.at(-1);
    this.movement_queue.push(new_movement);
    if (
      typeof last_movement === "undefined" ||
      new_movement.distance_to(last_movement) < this.movement_threshold
    ) {
      return;
    }
    this.publish_movement();
  }

  private publish_movement() {
    if (
      Date.now() - this.last_event_time < this.debounce_ms ||
      this.movement_queue.length === 0
    ) {
      return;
    }

    this.last_event_time = Date.now();
    this.callback(this.movement_queue.at(-1)!);
    this.movement_queue = [];
  }
}