This repository was archived by the owner on May 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathindex.js
86 lines (79 loc) · 2.71 KB
/
index.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
86
var React = require('react'),
parseEvents = require('./src/parse_events.js'),
isInput = require('./src/is_input.js'),
match = require('./src/match.js');
/**
* A React mixin that provides keybinding support for components
*/
var Keybinding = {
/**
* Housekeeping to pass around a single array of all
* currently-active keybinding objects.
*/
childContextTypes: {
__keybindings: React.PropTypes.array
},
contextTypes: {
__keybindings: React.PropTypes.array
},
getChildContext: function() {
return { __keybindings: this.__getKeybindings() };
},
__getKeybindings: function() {
this.__keybindings = this.__keybindings ||
(this.context && this.context.__keybindings) || [];
return this.__keybindings;
},
/**
* This is the only method meant to be exposed to the user: it
* returns the global keybinding index for the purposes of documentation
* generation.
*/
getAllKeybindings: function() {
return this.__getKeybindings();
},
/**
* Internal method: avoids firing keybindings in textareas,
* figures out if they match any of the bindings from this component,
* and then either fires an inline method or the .keybinding() method.
*/
__keybinding: function(event) {
if (isInput(event) && !this.keybindingsOnInputs) return;
for (var i = 0; i < this.matchers.length; i++) {
if (match(this.matchers[i].expectation, event)) {
if (typeof this.matchers[i].action === 'function') {
this.matchers[i].action.apply(this, [event]);
} else {
if (typeof this.keybinding !== 'function') {
throw new Error('non-function keybinding action given but no .keybinding method found on component');
}
this.keybinding(event, this.matchers[i].action);
}
}
}
},
/**
* When the component mounts, bind our event listener and
* add our keybindings to the global index.
*/
componentDidMount: function() {
if (this.keybindings !== undefined) {
this.matchers = parseEvents(this.keybindings, !!this.keybindingsPlatformAgnostic);
this.__boundKeybinding = this.__keybinding.bind(this);
document.addEventListener('keydown', this.__boundKeybinding);
this.__getKeybindings().push(this.keybindings);
}
},
/**
* When the component unmounts, unbind our event listener and
* remove our keybindings from the global index.
*/
componentWillUnmount: function() {
if (this.keybindings !== undefined && this.__boundKeybinding !== undefined) {
document.removeEventListener('keydown', this.__boundKeybinding);
this.__getKeybindings()
.splice(this.__getKeybindings().indexOf(this.keybindings), 1);
}
}
};
module.exports = Keybinding;