File size: 1,434 Bytes
1e92f2d |
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 |
import PropTypes from 'prop-types';
import { Component } from 'react';
import { connect } from 'react-redux';
import { modifierKeyIsActive } from '../helpers/input';
import getKeyboardShortcutsEnabled from '../state/selectors/get-keyboard-shortcuts-enabled';
const dispatch = ( event, action ) => {
event.preventDefault();
event.stopPropagation();
action();
};
export class HotkeyContainer extends Component {
static propTypes = {
shortcuts: PropTypes.arrayOf(
PropTypes.shape( {
action: PropTypes.func.isRequired,
hotkey: PropTypes.number.isRequired,
withModifiers: PropTypes.bool,
} )
),
};
componentDidMount() {
window.addEventListener( 'keydown', this.handleKeyDown, false );
}
componentWillUnmount() {
window.removeEventListener( 'keydown', this.handleKeyDown, false );
}
handleKeyDown = ( event ) => {
if ( ! this.props.shortcuts || ! this.props.keyboardShortcutsAreEnabled ) {
return;
}
this.props.shortcuts
.filter( ( shortcut ) => shortcut.hotkey === event.keyCode )
.filter(
( shortcut ) => ( shortcut.withModifiers || false ) === modifierKeyIsActive( event )
)
.forEach( ( shortcut ) => dispatch( event, shortcut.action ) );
};
render() {
return this.props.children;
}
}
const mapStateToProps = ( state ) => ( {
keyboardShortcutsAreEnabled: getKeyboardShortcutsEnabled( state ),
} );
export default connect( mapStateToProps )( HotkeyContainer );
|