blob: 0d6fb8d2a6a53fa40a69d194f7160134a6330dd1 (
plain)
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
57
58
59
|
const React = require('react');
const Mousetrap = require('mousetrap');
const { Map } = require('immutable');
/**
* Defines hotkeys globally when this component is mounted.
*
* keyMap = {
* 'escape': (e) => quit()
* 'mod+s': (e) => save()
* }
*
* <HotKeys keyMap={keyMap}>
* < ... />
* </HotKeys>
*/
const HotKeys = React.createClass({
propTypes: {
children: React.PropTypes.node.isRequired,
keyMap: React.PropTypes.objectOf(React.PropTypes.func)
},
getDefaultProps() {
return { keyMap: [] };
},
updateBindings(keyMap) {
Map(keyMap).forEach((handler, key) => {
Mousetrap.bind(key, handler);
});
},
clearBindings(keyMap) {
Map(keyMap).forEach((handler, key) => {
Mousetrap.unbind(key, handler);
});
},
componentDidMount() {
this.updateBindings(this.props.keyMap);
},
componentDidUpdate(prevProps) {
this.clearBindings(prevProps.keyMap);
this.updateBindings(this.props.keyMap);
},
componentWillUnmount() {
this.clearBindings(this.props.keyMap);
},
render() {
// Simply render the only child
return React.Children.only(this.props.children);
}
});
module.exports = HotKeys;
|