forked from react-bootstrap/react-bootstrap-bower
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDropdownStateMixin.js
81 lines (68 loc) · 1.72 KB
/
DropdownStateMixin.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
define(function (require, exports, module) {var React = require('react');
var EventListener = require('./utils/EventListener');
/**
* Checks whether a node is within
* a root nodes tree
*
* @param {DOMElement} node
* @param {DOMElement} root
* @returns {boolean}
*/
function isNodeInRoot(node, root) {
while (node) {
if (node === root) {
return true;
}
node = node.parentNode;
}
return false;
}
var DropdownStateMixin = {
getInitialState: function () {
return {
open: false
};
},
setDropdownState: function (newState, onStateChangeComplete) {
if (newState) {
this.bindRootCloseHandlers();
} else {
this.unbindRootCloseHandlers();
}
this.setState({
open: newState
}, onStateChangeComplete);
},
handleDocumentKeyUp: function (e) {
if (e.keyCode === 27) {
this.setDropdownState(false);
}
},
handleDocumentClick: function (e) {
// If the click originated from within this component
// don't do anything.
if (isNodeInRoot(e.target, this.getDOMNode())) {
return;
}
this.setDropdownState(false);
},
bindRootCloseHandlers: function () {
this._onDocumentClickListener =
EventListener.listen(document, 'click', this.handleDocumentClick);
this._onDocumentKeyupListener =
EventListener.listen(document, 'keyup', this.handleDocumentKeyUp);
},
unbindRootCloseHandlers: function () {
if (this._onDocumentClickListener) {
this._onDocumentClickListener.remove();
}
if (this._onDocumentKeyupListener) {
this._onDocumentKeyupListener.remove();
}
},
componentWillUnmount: function () {
this.unbindRootCloseHandlers();
}
};
module.exports = DropdownStateMixin;
});