insomnia/packages/insomnia-app/app/ui/components/keydown-binder.js

56 lines
1.3 KiB
JavaScript
Raw Normal View History

// @flow
import * as React from 'react';
import ReactDOM from 'react-dom';
import autobind from 'autobind-decorator';
2018-06-25 17:42:50 +00:00
import { isMac } from '../../common/constants';
type Props = {
onKeydown: Function,
2018-12-15 05:18:19 +00:00
children: React.Node,
disabled?: boolean,
scoped?: boolean,
stopMetaPropagation?: boolean,
};
@autobind
class KeydownBinder extends React.PureComponent<Props> {
2018-06-25 17:42:50 +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);
}
2018-06-25 17:42:50 +00:00
componentDidMount() {
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);
}
}
2018-06-25 17:42:50 +00:00
componentWillUnmount() {
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);
}
}
2018-06-25 17:42:50 +00:00
render() {
return this.props.children;
}
}
export default KeydownBinder;