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

80 lines
2.0 KiB
TypeScript
Raw Normal View History

2021-07-22 23:04:56 +00:00
import { autoBindMethodsForReact } from 'class-autobind-decorator';
import { PureComponent, ReactNode } from 'react';
import ReactDOM from 'react-dom';
2021-07-22 23:04:56 +00:00
import { AUTOBIND_CFG, isMac } from '../../common/constants';
interface Props {
children?: ReactNode;
onKeydown?: (...args: any[]) => any;
onKeyup?: (...args: any[]) => any;
disabled?: boolean;
scoped?: boolean;
stopMetaPropagation?: boolean;
}
@autoBindMethodsForReact(AUTOBIND_CFG)
export class KeydownBinder extends 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();
}
if (onKeydown) {
onKeydown(e);
}
}
_handleKeyup(e: KeyboardEvent) {
const { stopMetaPropagation, onKeyup, disabled } = this.props;
if (disabled) {
return;
}
const isMeta = isMac() ? e.metaKey : e.ctrlKey;
if (stopMetaPropagation && isMeta) {
e.stopPropagation();
}
if (onKeyup) {
onKeyup(e);
}
}
2018-06-25 17:42:50 +00:00
componentDidMount() {
if (this.props.scoped) {
const el = ReactDOM.findDOMNode(this);
2021-07-30 03:32:08 +00:00
el?.addEventListener('keydown', this._handleKeydown);
el?.addEventListener('keyup', this._handleKeyup);
} else {
2018-10-17 16:42:33 +00:00
document.body && document.body.addEventListener('keydown', this._handleKeydown);
document.body && document.body.addEventListener('keyup', this._handleKeyup);
}
}
componentWillUnmount() {
if (this.props.scoped) {
const el = ReactDOM.findDOMNode(this);
2021-07-30 03:32:08 +00:00
el?.removeEventListener('keydown', this._handleKeydown);
el?.removeEventListener('keyup', this._handleKeyup);
} else {
2018-10-17 16:42:33 +00:00
document.body && document.body.removeEventListener('keydown', this._handleKeydown);
document.body && document.body.removeEventListener('keyup', this._handleKeyup);
}
}
2018-06-25 17:42:50 +00:00
render() {
return this.props.children ?? null;
}
}