summaryrefslogtreecommitdiffstats
path: root/src/view/input/InputHandler.ts
blob: a6f129357a6e62fdf77043c162465811d9e9eb79 (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
import {Listenable} from '../../util';

export default class InputHandler extends Listenable<[]> {
	private readonly keys: Set<number> = new Set();

	constructor(relevantKeys: Set<number>) {
		super();

		window.addEventListener('keydown', (ev) => {
			if (!relevantKeys.has(ev.keyCode))
				return;

			ev.preventDefault();

			if (this.keys.has(ev.keyCode))
				return;

			this.keys.add(ev.keyCode);
			this.runListeners();
		});

		window.addEventListener('keyup', (ev) => {
			if (!relevantKeys.has(ev.keyCode))
				return;

			ev.preventDefault();

			if (!this.keys.has(ev.keyCode))
				return;

			this.keys.delete(ev.keyCode);
			this.runListeners();
		});
	}

	public has(key: number): boolean {
		return this.keys.has(key);
	}
}