import _defineProperty from "@babel/runtime/helpers/defineProperty";
// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

import { Component, createRef } from 'react';
import Measure from 'react-measure';
import { safeInvoke } from '../utils';
import { jsx as _jsx } from "react/jsx-runtime";
class Squeezer extends Component {
  constructor() {
    super(...arguments);
    _defineProperty(this, "rootRef", /*#__PURE__*/createRef());
    _defineProperty(this, "measuring", false);
    _defineProperty(this, "measurements", []);
    _defineProperty(this, "minWidth", 0);
    _defineProperty(this, "handleResize", () => {
      this.measure();
    });
  }
  addMeasurement(width) {
    this.measurements.push(width);
    if (this.measurements.length > 2) {
      this.measurements.shift();
    }
  }
  measure() {
    let force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    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() {
    let force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    if (!force && this.measurements.length === 2 && this.measurements[0] === this.measurements[1]) {
      this.measuring = false;
    } else {
      this.setState({}, () => {
        this.measure(true);
      });
    }
  }
  render() {
    const {
      children,
      innerRef,
      innerMeasure
    } = this.props;
    return /*#__PURE__*/_jsx(Measure, {
      onResize: this.handleResize,
      innerRef: el => {
        if (el) {
          this.rootRef.current = el;
          safeInvoke(innerRef, el);
          safeInvoke(innerMeasure, () => {
            this.measure(true);
          });
        }
      },
      children: _ref => {
        let {
          measureRef
        } = _ref;
        return children({
          ref: measureRef
        });
      }
    });
  }
}
export default Squeezer;