Commit 262a42b2 by kay delaney Committed by GitHub

UI/ClickOutsideWrapper: Adds parent prop for situations where event should be on document (#27221)

parent 093477c0
...@@ -10,6 +10,7 @@ export interface Props { ...@@ -10,6 +10,7 @@ export interface Props {
* Runs the 'onClick' function when pressing a key outside of the current element. Defaults to true. * Runs the 'onClick' function when pressing a key outside of the current element. Defaults to true.
*/ */
includeButtonPress: boolean; includeButtonPress: boolean;
parent: Window | Document;
} }
interface State { interface State {
...@@ -19,22 +20,24 @@ interface State { ...@@ -19,22 +20,24 @@ interface State {
export class ClickOutsideWrapper extends PureComponent<Props, State> { export class ClickOutsideWrapper extends PureComponent<Props, State> {
static defaultProps = { static defaultProps = {
includeButtonPress: true, includeButtonPress: true,
parent: window,
}; };
state = { state = {
hasEventListener: false, hasEventListener: false,
}; };
componentDidMount() { componentDidMount() {
document.addEventListener('mousedown', this.onOutsideClick, false); this.props.parent.addEventListener('click', this.onOutsideClick, false);
if (this.props.includeButtonPress) { if (this.props.includeButtonPress) {
document.addEventListener('keydown', this.onOutsideClick, false); // Use keyup since keydown already has an eventlistener on window
this.props.parent.addEventListener('keyup', this.onOutsideClick, false);
} }
} }
componentWillUnmount() { componentWillUnmount() {
document.removeEventListener('mousedown', this.onOutsideClick, false); this.props.parent.removeEventListener('click', this.onOutsideClick, false);
if (this.props.includeButtonPress) { if (this.props.includeButtonPress) {
document.removeEventListener('keydown', this.onOutsideClick, false); this.props.parent.removeEventListener('keyup', this.onOutsideClick, false);
} }
} }
......
...@@ -180,7 +180,7 @@ export class PanelHeader extends Component<Props, State> { ...@@ -180,7 +180,7 @@ export class PanelHeader extends Component<Props, State> {
<span className="panel-title-text">{title}</span> <span className="panel-title-text">{title}</span>
<Icon name="angle-down" className="panel-menu-toggle" /> <Icon name="angle-down" className="panel-menu-toggle" />
{this.state.panelMenuOpen && ( {this.state.panelMenuOpen && (
<ClickOutsideWrapper onClick={this.closeMenu}> <ClickOutsideWrapper onClick={this.closeMenu} parent={document}>
<PanelHeaderMenu items={menuItems} /> <PanelHeaderMenu items={menuItems} />
</ClickOutsideWrapper> </ClickOutsideWrapper>
)} )}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment