"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireWildcard(require("react"));
var _popper = _interopRequireDefault(require("popper.js"));
var _rafSchd = _interopRequireDefault(require("raf-schd"));
var _helpers = require("./internal/helpers");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } // eslint-disable-line import/extensions
var defaultState = {
  hasExtractedStyles: false,
  // We set these default offsets to prevent a flash of popper content in the wrong position
  // which can cause incorrect height calculations. Popper will calculate these values
  offsets: {
    popper: {
      left: -9999,
      top: -9999,
      position: null
    }
  },
  // fix Safari parent width: https://product-fabric.atlassian.net/browse/ED-1784
  cssPosition: 'absolute',
  originalHeight: null,
  maxHeight: null
};
var Layer = exports.default = /*#__PURE__*/function (_Component) {
  (0, _inherits2.default)(Layer, _Component);
  var _super = _createSuper(Layer);
  function Layer(props) {
    var _this;
    (0, _classCallCheck2.default)(this, Layer);
    _this = _super.call(this, props);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "targetRef", /*#__PURE__*/_react.default.createRef());
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "contentRef", /*#__PURE__*/_react.default.createRef());
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "extractStyles", function (state) {
      if (state) {
        var popperHeight = state.offsets.popper.height;
        var left = Math.round(state.offsets.popper.left);
        var top = Math.round(state.offsets.popper.top);
        var cssPosition = 'absolute';
        var originalHeight = _this.state.originalHeight || popperHeight;
        var maxHeight = _this.calculateMaxHeight(originalHeight, popperHeight, top, cssPosition);
        _this.setState({
          // position: fixed or absolute
          cssPosition: cssPosition,
          hasExtractedStyles: true,
          transform: "translate3d(".concat(left, "px, ").concat(top, "px, 0px)"),
          originalHeight: originalHeight,
          maxHeight: maxHeight
        });
      }
    });
    _this.state = defaultState;
    _this.extractStyles = (0, _rafSchd.default)(_this.extractStyles.bind((0, _assertThisInitialized2.default)(_this)));
    return _this;
  }
  (0, _createClass2.default)(Layer, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.applyPopper(this.props);
    }
  }, {
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      this.applyPopper(nextProps);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState) {
      var onPositioned = this.props.onPositioned;
      var hasExtractedStyles = this.state.hasExtractedStyles;

      // This flag is set the first time the position is calculated from Popper and applied to the content
      if (!prevState.hasExtractedStyles && hasExtractedStyles && onPositioned) {
        onPositioned();
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      // this.extractStyles.cancel();
      if (this.popper) {
        this.popper.destroy();
      }
    }

    /* Calculate the max height of the popper if it's height is greater than the viewport to prevent
     * the bottom of the popper not being viewable.
     * Only works if the popper uses viewport as the boundary and has a fixed position ancestor.
     */
  }, {
    key: "calculateMaxHeight",
    value: function calculateMaxHeight(originalHeight, currentHeight, positionTop, cssPosition) {
      var DocumentElementClientHeight = 0;
      if (document.documentElement) {
        DocumentElementClientHeight = document.documentElement.clientHeight;
      }
      if (cssPosition !== 'fixed') {
        return null;
      }
      var viewportHeight = Math.max(DocumentElementClientHeight, window.innerHeight || 0);
      return viewportHeight < originalHeight && currentHeight + positionTop >= viewportHeight - 50 ?
      // allow some spacing either side of viewport height
      viewportHeight - 12 : null;
    }
  }, {
    key: "applyPopper",
    value: function applyPopper(props) {
      if (!this.targetRef.current || !this.contentRef.current) {
        return;
      }
      if (this.popper) {
        this.popper.destroy();
      }

      // "new Popper(...)" operation is very expensive when called on virtual DOM.
      // This condition reduces the number of calls so we can run our tests faster
      // (time was reduced from 100s to 13s).
      if (!props.content) {
        return;
      }

      // we wrap our target in a div so that we can safely get a reference to it, but we pass the
      // actual target to popper
      var isAlwaysFixed = false;
      var actualTarget = this.targetRef.current.children[0];
      var popperOpts = {
        placement: (0, _helpers.positionPropToPopperPosition)(props.position),
        onCreate: this.extractStyles,
        onUpdate: this.extractStyles,
        modifiers: {
          applyStyle: {
            enabled: false
          },
          hide: {
            enabled: false
          },
          offset: {
            enabled: true,
            offset: this.props.offset
          },
          flip: {
            enabled: false,
            flipVariations: true,
            boundariesElement: 'viewport',
            padding: 0 // leave 0 pixels between popper and the boundariesElement
          },
          preventOverflow: {
            enabled: false,
            escapeWithReference: true
          }
        },
        positionFixed: isAlwaysFixed
      };
      if (actualTarget) {
        this.popper = new _popper.default(actualTarget, this.contentRef.current, popperOpts);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this$state = this.state,
        transform = _this$state.transform,
        hasExtractedStyles = _this$state.hasExtractedStyles,
        maxHeight = _this$state.maxHeight;
      var opacity = hasExtractedStyles ? {} : {
        opacity: 0
      };
      return /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("div", {
        ref: this.targetRef
      }, this.props.children), /*#__PURE__*/_react.default.createElement("div", {
        ref: this.contentRef,
        style: _objectSpread({
          top: 0,
          left: 0,
          position: 'absolute',
          transform: transform,
          maxHeight: maxHeight ? maxHeight : 'auto'
        }, opacity)
      }, this.props.content));
    }
  }]);
  return Layer;
}(_react.Component);
// working with extract-react-types
(0, _defineProperty2.default)(Layer, "defaultProps", {
  boundariesElement: 'viewport',
  children: null,
  content: null,
  offset: '0, 0',
  position: 'right middle',
  zIndex: 400,
  lockScroll: false,
  isAlwaysFixed: false,
  onPositioned: function onPositioned() {}
});