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';
|
|
|
|
import {isMac} from '../../common/constants';
|
|
|
|
|
|
|
|
type Props = {
|
|
|
|
onKeydown: Function,
|
2017-09-25 21:32:58 +00:00
|
|
|
children?: React.Node,
|
2017-09-17 14:04:56 +00:00
|
|
|
disabled?: boolean,
|
|
|
|
scoped?: boolean,
|
|
|
|
stopMetaPropagation?: boolean
|
|
|
|
};
|
|
|
|
|
|
|
|
@autobind
|
2017-09-25 21:32:58 +00:00
|
|
|
class KeydownBinder extends React.PureComponent<Props> {
|
2017-09-17 14:04:56 +00:00
|
|
|
_handleKeydown (e: KeyboardEvent) {
|
|
|
|
const {stopMetaPropagation, onKeydown, disabled} = this.props;
|
|
|
|
|
|
|
|
if (disabled) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const isMeta = isMac() ? e.metaKey : e.ctrlKey;
|
|
|
|
if (stopMetaPropagation && isMeta) {
|
|
|
|
e.stopPropagation();
|
|
|
|
}
|
|
|
|
|
|
|
|
onKeydown(e);
|
|
|
|
}
|
|
|
|
|
|
|
|
componentDidMount () {
|
|
|
|
if (this.props.scoped) {
|
|
|
|
const el = ReactDOM.findDOMNode(this);
|
|
|
|
el && el.addEventListener('keydown', this._handleKeydown);
|
|
|
|
} else {
|
|
|
|
document.body && document.body.addEventListener('keydown', this._handleKeydown);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
componentWillUnmount () {
|
|
|
|
if (this.props.scoped) {
|
|
|
|
const el = ReactDOM.findDOMNode(this);
|
|
|
|
el && el.removeEventListener('keydown', this._handleKeydown);
|
|
|
|
} else {
|
|
|
|
document.body && document.body.removeEventListener('keydown', this._handleKeydown);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
render () {
|
|
|
|
return this.props.children;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default KeydownBinder;
|