summaryrefslogtreecommitdiffstats
path: root/src/view/input/inputhandler.ts
blob: 96f15dd396ff925a51d65f46c2e9a992d9403d6d (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 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);
	}
}