HotkeysDetector.jsx 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { GlobalHotKeys } from 'react-hotkeys';
  4. export default class HotkeysDetector extends React.Component {
  5. constructor(props) {
  6. super(props);
  7. this.hotkeyList = this.props.hotkeyList;
  8. this.state = {
  9. userCommand: [],
  10. };
  11. this.processingCommands = [];
  12. this.check = this.check.bind(this);
  13. }
  14. check(event) {
  15. const target = event.target;
  16. // ignore when target dom is input
  17. const inputPattern = /^input|textinput|textarea$/i;
  18. if (inputPattern.test(target.tagName) || target.isContentEditable) {
  19. return;
  20. }
  21. // don't fire when not needed
  22. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  23. console.log(event.key);
  24. this.setState({
  25. userCommand: this.state.userCommand.concat(event.key),
  26. });
  27. // filters the corresponding hotkeys(keys) that the user has pressed so far
  28. const tempUserCommand = this.state.userCommand;
  29. this.processingCommands = this.hotkeyList.filter((value) => {
  30. return value.slice(0, tempUserCommand.length).toString() === tempUserCommand.toString();
  31. });
  32. // executes if there were keymap that matches what the user pressed fully.
  33. if ((this.processingCommands.length === 1) && (this.hotkeyList.find(ary => ary.toString() === this.state.userCommand.toString()))) {
  34. this.props.onDetected(this.processingCommands[0]);
  35. this.setState({
  36. userCommand: [],
  37. });
  38. }
  39. else if (this.processingCommands.toString() === [].toString()) {
  40. this.setState({
  41. userCommand: [],
  42. });
  43. }
  44. }
  45. return null;
  46. }
  47. render() {
  48. const keyMap = { check: this.props.keymap };
  49. const handlers = { check: (event) => { return this.check(event) } };
  50. return (
  51. <GlobalHotKeys keyMap={keyMap} handlers={handlers}>
  52. </GlobalHotKeys>
  53. );
  54. }
  55. }
  56. HotkeysDetector.propTypes = {
  57. onDetected: PropTypes.func.isRequired,
  58. keymap: PropTypes.array.isRequired,
  59. hotkeyList: PropTypes.array.isRequired,
  60. };