text: 'use strict';
  
  Object.defineProperty(exports, "__esModule", {
    value: true
  });
  
  var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  
  var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  
  var _react = require('react');
  
  var _react2 = _interopRequireDefault(_react);
  
  var _reactDom = require('react-dom');
  
  var _reactDom2 = _interopRequireDefault(_reactDom);
  
  var _reactEventListener = require('react-event-listener');
  
  var _reactEventListener2 = _interopRequireDefault(_reactEventListener);
  
  var _RenderToLayer = require('../internal/RenderToLayer');
  
  var _RenderToLayer2 = _interopRequireDefault(_RenderToLayer);
  
  var _propTypes = require('../utils/propTypes');
  
  var _propTypes2 = _interopRequireDefault(_propTypes);
  
  var _Paper = require('../Paper');
  
  var _Paper2 = _interopRequireDefault(_Paper);
  
  var _lodash = require('lodash.throttle');
  
  var _lodash2 = _interopRequireDefault(_lodash);
  
  var _PopoverAnimationDefault = require('./PopoverAnimationDefault');
  
  var _PopoverAnimationDefault2 = _interopRequireDefault(_PopoverAnimationDefault);
  
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  
  function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
  
  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  
  function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  
  function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  
  var Popover = function (_Component) {
    _inherits(Popover, _Component);
  
    function Popover(props, context) {
      _classCallCheck(this, Popover);
  
      var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Popover).call(this, props, context));
  
      _this.renderLayer = function () {
        var _this$props = _this.props;
        var animated = _this$props.animated;
        var // eslint-disable-line no-unused-vars
        animation = _this$props.animation;
        var children = _this$props.children;
        var style = _this$props.style;
  
        var other = _objectWithoutProperties(_this$props, ['animated', 'animation', 'children', 'style']);
  
        var Animation = animation || _PopoverAnimationDefault2.default;
        var styleRoot = style;
  
        if (!Animation) {
          Animation = _Paper2.default;
          styleRoot = {
            position: 'fixed'
          };
          if (!_this.state.open) {
            return null;
          }
        }
  
        return _react2.default.createElement(
          Animation,
          _extends({}, other, { style: styleRoot, open: _this.state.open && !_this.state.closing }),
          children
        );
      };
  
      _this.componentClickAway = function () {
        _this.requestClose('clickAway');
      };
  
      _this.setPlacement = function (scrolling) {
        if (!_this.state.open) {
          return;
        }
  
        var anchorEl = _this.props.anchorEl || _this.anchorEl;
  
        if (!_this.refs.layer.getLayer()) {
          return;
        }
  
        var targetEl = _this.refs.layer.getLayer().children[0];
        if (!targetEl) {
          return;
        }
  
        var _this$props2 = _this.props;
        var targetOrigin = _this$props2.targetOrigin;
        var anchorOrigin = _this$props2.anchorOrigin;
  
  
        var anchor = _this.getAnchorPosition(anchorEl);
        var target = _this.getTargetPosition(targetEl);
  
        var targetPosition = {
          top: anchor[anchorOrigin.vertical] - target[targetOrigin.vertical],
          left: anchor[anchorOrigin.horizontal] - target[targetOrigin.horizontal]
        };
  
        if (scrolling && _this.props.autoCloseWhenOffScreen) {
          _this.autoCloseWhenOffScreen(anchor);
        }
  
        if (_this.props.canAutoPosition) {
          target = _this.getTargetPosition(targetEl); // update as height may have changed
          targetPosition = _this.applyAutoPositionIfNeeded(anchor, target, targetOrigin, anchorOrigin, targetPosition);
        }
  
        targetEl.style.top = Math.max(0, targetPosition.top) + 'px';
        targetEl.style.left = Math.max(0, targetPosition.left) + 'px';
        targetEl.style.maxHeight = window.innerHeight + 'px';
      };
  
      _this.handleResize = (0, _lodash2.default)(_this.setPlacement, 100);
      _this.handleScroll = (0, _lodash2.default)(_this.setPlacement.bind(_this, true), 100);
  
      _this.state = {
        open: props.open,
        closing: false
      };
      return _this;
    }
  
    _createClass(Popover, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps) {
        var _this2 = this;
  
        if (nextProps.open !== this.state.open) {
          if (nextProps.open) {
            this.anchorEl = nextProps.anchorEl || this.props.anchorEl;
            this.setState({
              open: true,
              closing: false
            });
          } else {
            if (nextProps.animated) {
              this.setState({ closing: true });
              this.timeout = setTimeout(function () {
                _this2.setState({
                  open: false
                });
              }, 500);
            } else {
              this.setState({
                open: false
              });
            }
          }
        }
      }
    }, {
      key: 'componentDidUpdate',
      value: function componentDidUpdate() {
        this.setPlacement();
      }
    }, {
      key: 'componentWillUnmount',
      value: function componentWillUnmount() {
        clearTimeout(this.timeout);
      }
    }, {
      key: 'requestClose',
      value: function requestClose(reason) {
        if (this.props.onRequestClose) {
          this.props.onRequestClose(reason);
        }
      }
    }, {
      key: '_resizeAutoPosition',
      value: function _resizeAutoPosition() {
        this.setPlacement();
      }
    }, {
      key: 'getAnchorPosition',
      value: function getAnchorPosition(el) {
        if (!el) {
          el = _reactDom2.default.findDOMNode(this);
        }
  
        var rect = el.getBoundingClientRect();
        var a = {
          top: rect.top,
          left: rect.left,
          width: el.offsetWidth,
          height: el.offsetHeight
        };
  
        a.right = rect.right || a.left + a.width;
        a.bottom = rect.bottom || a.top + a.height;
        a.middle = a.left + (a.right - a.left) / 2;
        a.center = a.top + (a.bottom - a.top) / 2;
  
        return a;
      }
    }, {
      key: 'getTargetPosition',
      value: function getTargetPosition(targetEl) {
        return {
          top: 0,
          center: targetEl.offsetHeight / 2,
          bottom: targetEl.offsetHeight,
          left: 0,
          middle: targetEl.offsetWidth / 2,
          right: targetEl.offsetWidth
        };
      }
    }, {
      key: 'autoCloseWhenOffScreen',
      value: function autoCloseWhenOffScreen(anchorPosition) {
        if (anchorPosition.top < 0 || anchorPosition.top > window.innerHeight || anchorPosition.left < 0 || anchorPosition.left > window.innerWith) {
          this.requestClose('offScreen');
        }
      }
    }, {
      key: 'getOverlapMode',
      value: function getOverlapMode(anchor, target, median) {
        if ([anchor, target].indexOf(median) >= 0) return 'auto';
        if (anchor === target) return 'inclusive';
        return 'exclusive';
      }
    }, {
      key: 'getPositions',
      value: function getPositions(anchor, target) {
        var a = _extends({}, anchor);
        var t = _extends({}, target);
  
        var positions = {
          x: ['left', 'right'].filter(function (p) {
            return p !== t.horizontal;
          }),
          y: ['top', 'bottom'].filter(function (p) {
            return p !== t.vertical;
          })
        };
  
        var overlap = {
          x: this.getOverlapMode(a.horizontal, t.horizontal, 'middle'),
          y: this.getOverlapMode(a.vertical, t.vertical, 'center')
        };
  
        positions.x.splice(overlap.x === 'auto' ? 0 : 1, 0, 'middle');
        positions.y.splice(overlap.y === 'auto' ? 0 : 1, 0, 'center');
  
        if (overlap.y !== 'auto') {
          a.vertical = a.vertical === 'top' ? 'bottom' : 'top';
          if (overlap.y === 'inclusive') {
            t.vertical = t.vertical;
          }
        }
  
        if (overlap.x !== 'auto') {
          a.horizontal = a.horizontal === 'left' ? 'right' : 'left';
          if (overlap.y === 'inclusive') {
            t.horizontal = t.horizontal;
          }
        }
  
        return {
          positions: positions,
          anchorPos: a
        };
      }
    }, {
      key: 'applyAutoPositionIfNeeded',
      value: function applyAutoPositionIfNeeded(anchor, target, targetOrigin, anchorOrigin, targetPosition) {
        var _getPositions = this.getPositions(anchorOrigin, targetOrigin);
  
        var positions = _getPositions.positions;
        var anchorPos = _getPositions.anchorPos;
  
  
        if (targetPosition.top < 0 || targetPosition.top + target.bottom > window.innerHeight) {
          var newTop = anchor[anchorPos.vertical] - target[positions.y[0]];
          if (newTop + target.bottom <= window.innerHeight) targetPosition.top = Math.max(0, newTop);else {
            newTop = anchor[anchorPos.vertical] - target[positions.y[1]];
            if (newTop + target.bottom <= window.innerHeight) targetPosition.top = Math.max(0, newTop);
          }
        }
        if (targetPosition.left < 0 || targetPosition.left + target.right > window.innerWidth) {
          var newLeft = anchor[anchorPos.horizontal] - target[positions.x[0]];
          if (newLeft + target.right <= window.innerWidth) targetPosition.left = Math.max(0, newLeft);else {
            newLeft = anchor[anchorPos.horizontal] - target[positions.x[1]];
            if (newLeft + target.right <= window.innerWidth) targetPosition.left = Math.max(0, newLeft);
          }
        }
        return targetPosition;
      }
    }, {
      key: 'render',
      value: function render() {
        return _react2.default.createElement(
          'div',
          { style: { display: 'none' } },
          _react2.default.createElement(_reactEventListener2.default, {
            elementName: 'window',
            onScroll: this.handleScroll,
            onResize: this.handleResize
          }),
          _react2.default.createElement(_RenderToLayer2.default, {
            ref: 'layer',
            open: this.state.open,
            componentClickAway: this.componentClickAway,
            useLayerForClickAway: this.props.useLayerForClickAway,
            render: this.renderLayer
          })
        );
      }
    }]);
  
    return Popover;
  }(_react.Component);
  
  Popover.propTypes = {
    /**
     * This is the DOM element that will be used to set the position of the
     * popover.
     */
    anchorEl: _react.PropTypes.object,
    /**
     * This is the point on the anchor where the popover's
     * `targetOrigin` will attach to.
     * Options:
     * vertical: [top, middle, bottom];
     * horizontal: [left, center, right].
     */
    anchorOrigin: _propTypes2.default.origin,
    /**
     * If true, the popover will apply transitions when
     * it is added to the DOM.
     */
    animated: _react.PropTypes.bool,
    /**
     * Override the default animation component used.
     */
    animation: _react.PropTypes.func,
    /**
     * If true, the popover will hide when the anchor is scrolled off the screen.
     */
    autoCloseWhenOffScreen: _react.PropTypes.bool,
    /**
     * If true, the popover (potentially) ignores `targetOrigin`
     * and `anchorOrigin` to make itself fit on screen,
     * which is useful for mobile devices.
     */
    canAutoPosition: _react.PropTypes.bool,
    /**
     * The content of the popover.
     */
    children: _react.PropTypes.node,
    /**
     * The CSS class name of the root element.
     */
    className: _react.PropTypes.string,
    /**
     * Callback function fired when the popover is requested to be closed.
     *
     * @param {string} reason The reason for the close request. Possibles values
     * are 'clickAway' and 'offScreen'.
     */
    onRequestClose: _react.PropTypes.func,
    /**
     * If true, the popover is visible.
     */
    open: _react.PropTypes.bool,
    /**
     * Override the inline-styles of the root element.
     */
    style: _react.PropTypes.object,
    /**
     * This is the point on the popover which will attach to
     * the anchor's origin.
     * Options:
     * vertical: [top, middle, bottom];
     * horizontal: [left, center, right].
     */
    targetOrigin: _propTypes2.default.origin,
    /**
     * If true, the popover will render on top of an invisible
     * layer, which will prevent clicks to the underlying
     * elements, and trigger an `onRequestClose('clickAway')` call.
     */
    useLayerForClickAway: _react.PropTypes.bool,
    /**
     * The zDepth of the popover.
     */
    zDepth: _propTypes2.default.zDepth
  };
  Popover.defaultProps = {
    anchorOrigin: {
      vertical: 'bottom',
      horizontal: 'left'
    },
    animated: true,
    autoCloseWhenOffScreen: true,
    canAutoPosition: true,
    onRequestClose: function onRequestClose() {},
    open: false,
    style: {
      overflowY: 'auto'
    },
    targetOrigin: {
      vertical: 'top',
      horizontal: 'left'
    },
    useLayerForClickAway: true,
    zDepth: 1
  };
  Popover.contextTypes = {
    muiTheme: _react.PropTypes.object.isRequired
  };
  exports.default = Popover;