2017-09-17 14:04:56 +00:00
|
|
|
// @flow
|
2017-09-25 21:32:58 +00:00
|
|
|
import * as React from 'react';
|
2017-09-17 14:04:56 +00:00
|
|
|
import ReactDOM from 'react-dom';
|
|
|
|
import autobind from 'autobind-decorator';
|
2018-06-25 17:42:50 +00:00
|
|
|
import { isMac } from '../../common/constants';
|
2017-09-17 14:04:56 +00:00
|
|
|
|
|
|
|
type Props = {
|
|
|
|
onKeydown: Function,
|
2018-12-15 05:18:19 +00:00
|
|
|
children: React.Node,
|
2017-09-17 14:04:56 +00:00
|
|
|
disabled?: boolean,
|
|
|
|
scoped?: boolean,
|
2018-12-12 17:36:11 +00:00
|
|
|
stopMetaPropagation?: boolean,
|
2017-09-17 14:04:56 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
@autobind
|
2017-09-25 21:32:58 +00:00
|
|
|
class KeydownBinder extends React.PureComponent<Props> {
|
2018-06-25 17:42:50 +00:00
|
|
|
_handleKeydown(e: KeyboardEvent) {
|
|
|
|
const { stopMetaPropagation, onKeydown, disabled } = this.props;
|
2017-09-17 14:04:56 +00:00
|
|
|
|
|
|
|
if (disabled) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const isMeta = isMac() ? e.metaKey : e.ctrlKey;
|
|
|
|
if (stopMetaPropagation && isMeta) {
|
|
|
|
e.stopPropagation();
|
|
|
|
}
|
|
|
|
|
|
|
|
onKeydown(e);
|
|
|
|
}
|
|
|
|
|
2018-06-25 17:42:50 +00:00
|
|
|
componentDidMount() {
|
2017-09-17 14:04:56 +00:00
|
|
|
if (this.props.scoped) {
|
|
|
|
const el = ReactDOM.findDOMNode(this);
|
|
|
|
el && el.addEventListener('keydown', this._handleKeydown);
|
|
|
|
} else {
|
2018-10-17 16:42:33 +00:00
|
|
|
document.body && document.body.addEventListener('keydown', this._handleKeydown);
|
2017-09-17 14:04:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-06-25 17:42:50 +00:00
|
|
|
componentWillUnmount() {
|
2017-09-17 14:04:56 +00:00
|
|
|
if (this.props.scoped) {
|
|
|
|
const el = ReactDOM.findDOMNode(this);
|
|
|
|
el && el.removeEventListener('keydown', this._handleKeydown);
|
|
|
|
} else {
|
2018-10-17 16:42:33 +00:00
|
|
|
document.body && document.body.removeEventListener('keydown', this._handleKeydown);
|
2017-09-17 14:04:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-06-25 17:42:50 +00:00
|
|
|
render() {
|
2017-09-17 14:04:56 +00:00
|
|
|
return this.props.children;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default KeydownBinder;
|