-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
index.js
99 lines (87 loc) · 1.97 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
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* WordPress Dependeencies
*/
import { Component } from '@wordpress/element';
/**
* Internal Dependencies
*/
import Popover from '../popover';
class Dropdown extends Component {
constructor() {
super( ...arguments );
this.toggle = this.toggle.bind( this );
this.close = this.close.bind( this );
this.clickOutside = this.clickOutside.bind( this );
this.bindContainer = this.bindContainer.bind( this );
this.state = {
isOpen: false,
};
}
componentWillUnmount() {
const { isOpen } = this.state;
const { onToggle } = this.props;
if ( isOpen && onToggle ) {
onToggle( false );
}
}
componentWillUpdate( nextProps, nextState ) {
const { isOpen } = nextState;
const { onToggle } = nextProps;
if ( this.state.isOpen !== isOpen && onToggle ) {
onToggle( isOpen );
}
}
bindContainer( ref ) {
this.container = ref;
}
toggle() {
this.setState( ( state ) => ( {
isOpen: ! state.isOpen,
} ) );
}
clickOutside( event ) {
if ( ! this.container.contains( event.target ) ) {
this.close();
}
}
close() {
this.setState( { isOpen: false } );
}
render() {
const { isOpen } = this.state;
const {
renderContent,
renderToggle,
position = 'bottom',
className,
contentClassName,
expandOnMobile,
headerTitle,
} = this.props;
const args = { isOpen, onToggle: this.toggle, onClose: this.close };
return (
<div className={ className } ref={ this.bindContainer }>
{ /**
* This seemingly redundant wrapper node avoids root return
* element styling impacting popover positioning.
*/ }
<div>
{ renderToggle( args ) }
{ isOpen && (
<Popover
className={ contentClassName }
position={ position }
onClose={ this.close }
onClickOutside={ this.clickOutside }
expandOnMobile={ expandOnMobile }
headerTitle={ headerTitle }
>
{ renderContent( args ) }
</Popover>
) }
</div>
</div>
);
}
}
export default Dropdown;