-
Notifications
You must be signed in to change notification settings - Fork 171
/
PortalWithState.js
115 lines (102 loc) · 2.67 KB
/
PortalWithState.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import React from 'react';
import PropTypes from 'prop-types';
import Portal from './PortalCompat';
const KEYCODES = {
ESCAPE: 27
};
class PortalWithState extends React.Component {
constructor(props) {
super(props);
this.portalNode = null;
this.state = { active: !!props.defaultOpen };
this.openPortal = this.openPortal.bind(this);
this.closePortal = this.closePortal.bind(this);
this.wrapWithPortal = this.wrapWithPortal.bind(this);
this.handleOutsideMouseClick = this.handleOutsideMouseClick.bind(this);
this.handleKeydown = this.handleKeydown.bind(this);
}
componentDidMount() {
if (this.props.closeOnEsc) {
document.addEventListener('keydown', this.handleKeydown);
}
if (this.props.closeOnOutsideClick) {
document.addEventListener('click', this.handleOutsideMouseClick);
}
}
componentWillUnmount() {
if (this.props.closeOnEsc) {
document.removeEventListener('keydown', this.handleKeydown);
}
if (this.props.closeOnOutsideClick) {
document.removeEventListener('click', this.handleOutsideMouseClick);
}
}
openPortal(e) {
if (this.state.active) {
return;
}
if (e && e.nativeEvent) {
e.nativeEvent.stopImmediatePropagation();
}
this.setState({ active: true }, this.props.onOpen);
}
closePortal() {
if (!this.state.active) {
return;
}
this.setState({ active: false }, this.props.onClose);
}
wrapWithPortal(children) {
if (!this.state.active) {
return null;
}
return (
<Portal
node={this.props.node}
key="react-portal"
ref={portalNode => (this.portalNode = portalNode)}
>
{children}
</Portal>
);
}
handleOutsideMouseClick(e) {
if (!this.state.active) {
return;
}
const root =
this.portalNode &&
(this.portalNode.props.node || this.portalNode.defaultNode);
if (!root || root.contains(e.target) || (e.button && e.button !== 0)) {
return;
}
this.closePortal();
}
handleKeydown(e) {
if (e.keyCode === KEYCODES.ESCAPE && this.state.active) {
this.closePortal();
}
}
render() {
return this.props.children({
openPortal: this.openPortal,
closePortal: this.closePortal,
portal: this.wrapWithPortal,
isOpen: this.state.active
});
}
}
PortalWithState.propTypes = {
children: PropTypes.func.isRequired,
defaultOpen: PropTypes.bool,
node: PropTypes.any,
closeOnEsc: PropTypes.bool,
closeOnOutsideClick: PropTypes.bool,
onOpen: PropTypes.func,
onClose: PropTypes.func
};
PortalWithState.defaultProps = {
onOpen: () => {},
onClose: () => {}
};
export default PortalWithState;