"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _react = _interopRequireWildcard(require("react"));

var _reactMeasure = _interopRequireDefault(require("react-measure"));

var _utils = require("../utils");

// Copyright 1999-2020. Plesk International GmbH. All rights reserved.
class Squeezer extends _react.Component {
  constructor(...args) {
    super(...args);
    (0, _defineProperty2.default)(this, "rootRef", /*#__PURE__*/(0, _react.createRef)());
    (0, _defineProperty2.default)(this, "measuring", false);
    (0, _defineProperty2.default)(this, "measurements", []);
    (0, _defineProperty2.default)(this, "minWidth", 0);
    (0, _defineProperty2.default)(this, "handleResize", () => {
      this.measure();
    });
  }

  addMeasurement(width) {
    this.measurements.push(width);

    if (this.measurements.length > 2) {
      this.measurements.shift();
    }
  }

  measure(force = false) {
    // eslint-disable-next-line react/prop-types
    const {
      compact,
      uncompact
    } = this.props;

    if (this.measuring && !force) {
      return;
    }

    this.measuring = true;
    const root = this.rootRef.current;
    const width = Math.ceil(root.getBoundingClientRect().width);
    const scrollWidth = Math.ceil(root.scrollWidth);
    let checkForce = false;

    if (width < scrollWidth) {
      if (compact()) {
        this.minWidth = scrollWidth;
        checkForce = true;
      }
    } else if (width > this.minWidth) {
      if (uncompact()) {
        this.minWidth = width;
        checkForce = true;
      }
    }

    this.addMeasurement(width);
    this.check(checkForce);
  }

  check(force = false) {
    if (!force && this.measurements.length === 2 && this.measurements[0] === this.measurements[1]) {
      this.measuring = false;
    } else {
      this.setState({}, () => {
        this.measure(true);
      });
    }
  }

  render() {
    // eslint-disable-next-line react/prop-types
    const {
      children,
      innerRef,
      innerMeasure
    } = this.props;
    return /*#__PURE__*/_react.default.createElement(_reactMeasure.default, {
      onResize: this.handleResize,
      innerRef: el => {
        if (el) {
          this.rootRef.current = el;
          (0, _utils.safeInvoke)(innerRef, el);
          (0, _utils.safeInvoke)(innerMeasure, () => {
            this.measure(true);
          });
        }
      }
    }, ({
      measureRef
    }) => children({
      ref: measureRef
    }));
  }

}

var _default = Squeezer;
exports.default = _default;