"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 _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
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 _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
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 _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
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
    }
  },
  cssPosition: 'absolute',
  originalHeight: null,
  maxHeight: null
};

// Ignored via go/ees005
// eslint-disable-next-line @repo/internal/react/no-class-components
var Layer = exports.default = /*#__PURE__*/function (_Component) {
  function Layer(props) {
    var _this;
    (0, _classCallCheck2.default)(this, Layer);
    _this = _callSuper(this, Layer, [props]);
    (0, _defineProperty2.default)(_this, "targetRef", /*#__PURE__*/_react.default.createRef());
    (0, _defineProperty2.default)(_this, "contentRef", /*#__PURE__*/_react.default.createRef());
    (0, _defineProperty2.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(_this));
    return _this;
  }
  (0, _inherits2.default)(Layer, _Component);
  return (0, _createClass2.default)(Layer, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.applyPopper(this.props);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState) {
      var onPositioned = this.props.onPositioned;
      var hasExtractedStyles = this.state.hasExtractedStyles;
      if (this.props !== prevProps) {
        this.applyPopper(this.props);
      }

      // 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({
          // eslint-disable-next-line @atlaskit/ui-styling-standard/enforce-style-prop -- Ignored via go/DSP-18766
          top: 0,
          // eslint-disable-next-line @atlaskit/ui-styling-standard/enforce-style-prop -- Ignored via go/DSP-18766
          left: 0,
          // eslint-disable-next-line @atlaskit/ui-styling-standard/enforce-style-prop -- Ignored via go/DSP-18766
          position: 'absolute',
          // eslint-disable-next-line @atlaskit/ui-styling-standard/enforce-style-prop -- Ignored via go/DSP-18766
          transform: transform,
          maxHeight: maxHeight ? maxHeight : 'auto'
        }, opacity)
      }, this.props.content));
    }
  }]);
}(_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() {}
});