forked from ayrton/react-key-handler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
key-handler.js
102 lines (81 loc) · 2.32 KB
/
key-handler.js
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
92
93
94
95
96
97
98
99
100
101
102
/* @flow */
import React from 'react';
import PropTypes from 'prop-types';
import { canUseDOM } from 'exenv';
import { KEYDOWN, KEYPRESS, KEYUP, type KeyConstants } from './constants';
import { type primitiveOrArray } from './types';
import { isInput, matchesKeyboardEvent } from './utils';
type Props = {|
+keyValue?: ?primitiveOrArray<string>,
+keyCode?: ?primitiveOrArray<number>,
+code?: ?primitiveOrArray<string>,
+keyEventName: KeyConstants,
+onKeyHandle?: (event: KeyboardEvent) => mixed,
|};
export default class KeyHandler extends React.Component<Props> {
static propTypes = {
keyValue: PropTypes.oneOfType([
PropTypes.string,
PropTypes.arrayOf(PropTypes.string),
]),
keyCode: PropTypes.oneOfType([
PropTypes.number,
PropTypes.arrayOf(PropTypes.number),
]),
code: PropTypes.oneOfType([
PropTypes.string,
PropTypes.arrayOf(PropTypes.string),
]),
keyEventName: PropTypes.oneOf([KEYDOWN, KEYPRESS, KEYUP]),
onKeyHandle: PropTypes.func,
};
static defaultProps = {
keyEventName: KEYUP,
};
shouldComponentUpdate(): boolean {
return false;
}
constructor(props: Props) {
super(props);
/* eslint-disable no-console */
if (props.keyCode) {
console.warn(
'Warning: Deprecated propType: `keyCode` is deprecated in favour of `code` for `KeyHandler`.',
);
}
if (!props.keyValue && !props.keyCode && !props.code) {
console.error(
'Warning: Failed propType: Missing prop `code`, `keyValue` or `keyCode` for `KeyHandler`.',
);
}
/* eslint-enable */
}
componentDidMount(): void {
if (!canUseDOM) return;
window.document.addEventListener(this.props.keyEventName, this.handleKey);
}
componentWillUnmount(): void {
if (!canUseDOM) return;
window.document.removeEventListener(
this.props.keyEventName,
this.handleKey,
);
}
render(): null {
return null;
}
handleKey = (event: KeyboardEvent): void => {
const { keyValue, keyCode, code, onKeyHandle } = this.props;
if (!onKeyHandle) {
return;
}
const { target } = event;
if (target instanceof window.HTMLElement && isInput(target)) {
return;
}
if (!matchesKeyboardEvent(event, { keyValue, keyCode, code })) {
return;
}
onKeyHandle(event);
};
}