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
|
const React = require('react');
const Mousetrap = require('mousetrap');
const { string, node, func, shape, arrayOf } = React.PropTypes;
const bindingShape = shape({
// A key "escape", a combination of key "mod+s", or a key sequence "ctrl+x ctrl+s"
key: string.isRequired,
// function (event) {}
handler: func.isRequired
});
/**
* Defines hotkeys globally when this component is mounted.
*
* keymap = [{
* key: 'escape',
* handler: (e) => quit()
* }, {
* key: 'mod+s',
* handler: (e) => save()
* }]
*
* <HotKeys keymap={keymap}>
* < ... />
* </HotKeys>
*/
const HotKeys = React.createClass({
propTypes: {
children: node.isRequired,
keymap: arrayOf(bindingShape)
},
getDefaultProps() {
return { keymap: [] };
},
componentDidMount() {
this.props.keymap.forEach((binding) => {
Mousetrap.bind(binding.key, binding.handler);
});
},
componentWillUnmount() {
this.props.keymap.forEach((binding) => {
Mousetrap.unbind(binding.key, binding.handler);
});
},
render() {
// Simply render the only child
return React.Children.only(this.props.children);
}
});
module.exports = HotKeys;
|