summaryrefslogtreecommitdiffstats
path: root/src/renderer/runtime/view/input/inputhandler.ts
blob: 17abfe6bd8edd9224b735cf4323a27a0904d41f8 (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
40
41
42
43
44
import { Listenable } from '../../util';

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

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

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

			ev.preventDefault();

			if (ev.repeat)
				return;

			this.keys.add(ev.code);
			this.runListeners(ev.code, true);
		});

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

			ev.preventDefault();

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

			this.keys.delete(ev.code);
			this.runListeners(ev.code, false);
		});

		window.addEventListener('blur', () => {
			this.keys.clear();
			this.runListeners('', false);
		});
	}

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