-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathHasCommand.js
85 lines (75 loc) · 1.97 KB
/
HasCommand.js
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* HasCommand applies a keyboard shortcut to a wrapped section of the UI
* Given a 'name' prop, it assigns a handler function to the associated
* Shortcut from a parent 'CommandList'
*/
import React from 'react';
import PropTypes from 'prop-types';
import isEqual from 'lodash/isEqual';
import { HotKeys } from '../HotKeys';
class HasCommand extends React.Component {
static propTypes = {
children: PropTypes.oneOfType([
PropTypes.node,
PropTypes.arrayOf(PropTypes.node),
]).isRequired,
commands: PropTypes.arrayOf(PropTypes.object),
id: PropTypes.string,
isWithinScope: PropTypes.func,
scope: PropTypes.oneOfType([PropTypes.node, PropTypes.instanceOf(Element), PropTypes.object])
}
constructor(props) {
super(props);
this.getHandlers = this.getHandlers.bind(this);
this.getKeyMap = this.getKeyMap.bind(this);
this.handlers = this.getHandlers();
this.keyMap = this.getKeyMap();
}
componentDidUpdate(prevProps) {
const { commands } = this.props;
if (!isEqual(commands, prevProps.commands)) {
this.handlers = this.getHandlers();
this.keyMap = this.getKeyMap();
this.forceUpdate();
}
}
getHandlers() {
const { commands } = this.props;
const handlers = {};
commands.forEach(c => {
if (c.handler) {
handlers[c.name] = c.handler;
}
});
return handlers;
}
getKeyMap() {
const { commands } = this.props;
const keyMap = {};
commands.forEach(c => {
if (c.shortcut) {
keyMap[c.name] = c.shortcut;
}
});
if (Object.keys(keyMap).length === 0) {
return null;
}
return keyMap;
}
render() {
const { children, id, isWithinScope, scope } = this.props;
return (
<HotKeys
id={id}
keyMap={this.keyMap}
handlers={this.handlers}
focused={isWithinScope}
attach={scope}
noWrapper
>
{ children }
</HotKeys>
);
}
}
export default HasCommand;