function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { HotKeys } from 'react-hotkeys';
import styled from 'styled-components';
const ModalContainer = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: transparent;
  opacity: ${props => props.visible ? 1 : 0};
  pointer-events: ${props => props.visible ? 'all' : 'none'};
`;

class ModalBlur extends React.PureComponent {
  get keysActions() {
    return {
      requestToClose: this.props.closeKeys
    };
  }

  get keysHandlers() {
    return {
      requestToClose: event => {
        const {
          cancellable,
          onRequestToClose
        } = this.props;
        !cancellable && onRequestToClose && onRequestToClose();
      }
    };
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevProps.visible !== this.props.visible) {
      document.querySelector('#root').style.filter = this.props.visible ? 'blur(5px)' : null;
    }
  }

  render() {
    const autofocus = el => el && el.parentNode.focus();

    return ReactDOM.createPortal(React.createElement(HotKeys, {
      keyMap: this.keysActions,
      handlers: this.keysHandlers
    }, React.createElement(ModalContainer, {
      innerRef: autofocus,
      visible: this.props.visible
    }, this.props.children)), document.body);
  }

}

_defineProperty(ModalBlur, "propTypes", {
  children: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
  visible: PropTypes.bool,
  closeKeys: PropTypes.arrayOf(PropTypes.string),
  onRequestToClose: PropTypes.func,
  cancellable: PropTypes.bool
});

_defineProperty(ModalBlur, "defaultProps", {
  children: null,
  visible: false,
  closeKeys: ['esc'],
  onRequestToClose: null,
  cancellable: false
});

export default ModalBlur;