diff options
Diffstat (limited to 'static/src/mouse_controller.ts')
| -rw-r--r-- | static/src/mouse_controller.ts | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/static/src/mouse_controller.ts b/static/src/mouse_controller.ts new file mode 100644 index 0000000..b8849b4 --- /dev/null +++ b/static/src/mouse_controller.ts @@ -0,0 +1,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 = []; + } +} |
