-
-
Notifications
You must be signed in to change notification settings - Fork 921
/
RootCloseWrapper.js
93 lines (83 loc) 路 2.53 KB
/
RootCloseWrapper.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
87
88
89
90
91
92
93
/**
* modified version of:
* https://github.com/react-bootstrap/react-overlays/blob/f1528af806236627df49e0f661aec7cb48980863/src/RootCloseWrapper.js
*/
import React from 'react';
import ReactDOM from 'react-dom';
import { on } from 'dom-lib';
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
let counter = 0;
function getSuppressRootClose() {
let id = '__click_was_inside_' + (counter++);
return {
id,
suppressRootClose(event) {
// Tag the native event to prevent the root close logic on document click.
// This seems safer than using event.nativeEvent.stopImmediatePropagation(),
// which is only supported in IE >= 9.
event.nativeEvent[id] = true;
}
};
}
let RootCloseWrapper = React.createClass({
propTypes: {
onRootClose: React.PropTypes.func.isRequired
},
componentWillMount() {
let {
id,
suppressRootClose
} = getSuppressRootClose();
this._suppressRootId = id;
this._suppressRootCloseHandler = suppressRootClose;
},
componentDidMount() {
this.bindRootCloseHandlers();
},
componentWillUnmount() {
this.unbindRootCloseHandlers();
},
bindRootCloseHandlers() {
let doc = window.document;
this._onDocumentClickListener = on(doc, 'click', this.handleDocumentClick);
this._onDocumentKeyupListener = on(doc, 'keyup', this.handleDocumentKeyUp);
},
handleDocumentClick(event) {
if (event[this._suppressRootId]) {
return;
}
if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
return;
}
this.props.onRootClose();
},
handleDocumentKeyUp(event) {
if (event.keyCode === 27) {
this.props.onRootClose();
}
},
unbindRootCloseHandlers() {
if (this._onDocumentClickListener) {
this._onDocumentClickListener.off();
}
if (this._onDocumentKeyupListener) {
this._onDocumentKeyupListener.off();
}
},
getWrappedDOMNode() {
return ReactDOM.findDOMNode(this);
},
render() {
let {children} = this.props;
let child = React.Children.only(children);
return React.cloneElement(child, {
onClick: this._suppressRootCloseHandler || child.props.onClick
});
}
});
export default RootCloseWrapper;