import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/inherits";
import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
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) { _defineProperty(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 = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
import React, { Component } from 'react';
import Popper from 'popper.js'; // eslint-disable-line import/extensions
import rafSchedule from 'raf-schd';
import { positionPropToPopperPosition } from './internal/helpers';
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 = /*#__PURE__*/function (_Component) {
  _inherits(Layer, _Component);
  var _super = _createSuper(Layer);
  function Layer(props) {
    var _this;
    _classCallCheck(this, Layer);
    _this = _super.call(this, props);
    _defineProperty(_assertThisInitialized(_this), "targetRef", /*#__PURE__*/React.createRef());
    _defineProperty(_assertThisInitialized(_this), "contentRef", /*#__PURE__*/React.createRef());
    _defineProperty(_assertThisInitialized(_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 = rafSchedule(_this.extractStyles.bind(_assertThisInitialized(_this)));
    return _this;
  }
  _createClass(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: 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(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.createElement("div", null, /*#__PURE__*/React.createElement("div", {
        ref: this.targetRef
      }, this.props.children), /*#__PURE__*/React.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;
}(Component);
// working with extract-react-types
_defineProperty(Layer, "defaultProps", {
  boundariesElement: 'viewport',
  children: null,
  content: null,
  offset: '0, 0',
  position: 'right middle',
  zIndex: 400,
  lockScroll: false,
  isAlwaysFixed: false,
  onPositioned: function onPositioned() {}
});
export { Layer as default };