Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Ui Framework] Refactor "click outside to close" logic #13414

Closed
stacey-gammon opened this issue Aug 9, 2017 · 1 comment
Closed

[Ui Framework] Refactor "click outside to close" logic #13414

stacey-gammon opened this issue Aug 9, 2017 · 1 comment
Assignees
Labels
chore Team:Platform-Design Team Label for Kibana Design Team. Support the Analyze group of plugins.

Comments

@stacey-gammon
Copy link
Contributor

Both Popover (coming soon) and Colorpicker use the same kind of logic so it'd be nice to extract into a common component.

Something like:

export class KuiClickOutsideToClose extends Component {
  constructor(props) {
    super(props);

    // Use this variable to differentiate between clicks on the element that should not cause the pop up
    // to close, and external clicks that should cause the pop up to close.
    this.didClickMyself = false;
  }

  onClickOutside = () => {
    if (this.didClickMyself) {
      this.didClickMyself = false;
      return;
    }
 
    this.props.onClickOutside();
  };

  onClickRootElement = () => {
    // This prevents clicking on the element from closing it, due to the event handler on the
    // document object.
    this.didClickMyself = true;
  };

  componentDidMount() {
    // When the user clicks somewhere outside of the color picker, we will dismiss it.
    document.addEventListener('click', this.onClickOutside);
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.onClickOutside);
  }

  render() {
    const props = Object.assign({}, this.props.children.props, {
      onClick: this.onClickRootElement,
    });

    return cloneElement(this.props.children, props);
  }
}

with usage like:

<KuiClickOutsideToClose
  onClickOutside={this.props.closePopover}
>
  <div
    className={ classes }
    { ...rest }
  >
    {button}
    {body}
  </div>
</KuiClickOutsideToClose>

cc @cjcenizal

@stacey-gammon stacey-gammon added Team:Platform-Design Team Label for Kibana Design Team. Support the Analyze group of plugins. chore labels Aug 9, 2017
@cjcenizal
Copy link
Contributor

Note the caveat regarding child types raised by #13322 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
chore Team:Platform-Design Team Label for Kibana Design Team. Support the Analyze group of plugins.
Projects
None yet
Development

No branches or pull requests

2 participants