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