This repository has been archived by the owner on Mar 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 425
/
KeyListener.tsx
91 lines (81 loc) · 2.66 KB
/
KeyListener.tsx
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
//
// This file incorporates work covered by the following copyright and
// permission notice:
//
// Copyright 2019-2021 Cruise LLC
//
// This source code is licensed under the Apache License, Version 2.0,
// found at http://www.apache.org/licenses/LICENSE-2.0
// You may not use this file except in compliance with the License.
type KeyHandlers = {
[key: string]: (event: KeyboardEvent) => void;
};
type Props = {
global: true | false;
keyDownHandlers?: KeyHandlers;
keyPressHandlers?: KeyHandlers;
keyUpHandlers?: KeyHandlers;
};
export default class KeyListener extends React.Component<Props> {
el?: HTMLDivElement;
static defaultProps = {
global: false,
};
override componentDidMount(): void {
const { global } = this.props;
const target = global ? document : this.el?.parentElement;
if (target) {
target.addEventListener("keydown", this.handleEvent as any);
target.addEventListener("keypress", this.handleEvent as any);
target.addEventListener("keyup", this.handleEvent as any);
}
}
override componentWillUnmount(): void {
const { global } = this.props;
const target = global ? document : this.el?.parentElement;
if (target) {
target.removeEventListener("keydown", this.handleEvent as any);
target.removeEventListener("keypress", this.handleEvent as any);
target.removeEventListener("keyup", this.handleEvent as any);
}
}
callHandlers(handlers: KeyHandlers | undefined, event: KeyboardEvent): void {
if (!handlers) {
return;
}
if (typeof handlers[event.key] === "function") {
event.preventDefault();
handlers[event.key]?.(event);
}
}
handleEvent = (event: KeyboardEvent): void => {
const { target, type } = event;
if (
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
(target instanceof HTMLElement && target.isContentEditable)
) {
// The user is typing in an editable field; ignore the event.
return;
}
switch (type) {
case "keydown":
this.callHandlers(this.props.keyDownHandlers, event);
break;
case "keypress":
this.callHandlers(this.props.keyPressHandlers, event);
break;
case "keyup":
this.callHandlers(this.props.keyUpHandlers, event);
break;
default:
break;
}
};
override render(): JSX.Element {
return <div style={{ display: "none" }} ref={(el) => (this.el = el ?? undefined)} />;
}
}