"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.emptyRect = exports.RectState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _mobx = require("mobx");
var _bexCore = require("@wix/bex-core");
const emptyRect = () => ({
  bottom: undefined,
  height: undefined,
  left: undefined,
  right: undefined,
  top: undefined,
  width: undefined
  // x: undefined,
  // y: undefined,
});
exports.emptyRect = emptyRect;
class RectState {
  constructor(params) {
    (0, _defineProperty2.default)(this, "_syncThrottled", void 0);
    (0, _defineProperty2.default)(this, "_syncDebounced", void 0);
    (0, _defineProperty2.default)(this, "container", void 0);
    (0, _defineProperty2.default)(this, "element", void 0);
    (0, _defineProperty2.default)(this, "rect", (0, _mobx.observable)(emptyRect()));
    this.container = params.container;
    (0, _mobx.makeObservable)(this, {
      _sync: _mobx.action.bound
    });
    this._syncThrottled = this.container.lodash.throttle(() => {
      window.requestAnimationFrame(this._sync);
    }, 200);
    this._syncDebounced = () => window.requestAnimationFrame(this._sync);
  }
  _readRect() {
    const {
      element,
      container: {
        window
      }
    } = this;
    if (element == null) {
      return {};
    }
    if (process.env.NODE_ENV === 'test') {
      const {
        matches
      } = window.matchMedia('(min-width: 768px)');
      return matches ? {
        height: 600,
        width: 840,
        top: 0,
        bottom: 0,
        right: 0,
        left: 0,
        y: 0,
        x: 0
      } : {
        height: 600,
        width: 610,
        top: 0,
        bottom: 0,
        right: 0,
        left: 0,
        y: 0,
        x: 0
      };
    }
    const r = element.getBoundingClientRect();
    return {
      bottom: r.bottom,
      height: r.height,
      left: r.left,
      right: r.right,
      top: r.top,
      width: r.width,
      x: r.x,
      y: r.y
    };
  }
  _sync() {
    const {
      rect
    } = this;
    Object.assign(rect, this._readRect());
  }
  init({
    scrollElement
  } = {}) {
    const {
      element
    } = this;
    if (element) {
      this._syncThrottled();
      if (scrollElement) {
        scrollElement.addEventListener('scroll', this._syncThrottled);
      }
      const disposers = [(0, _bexCore.addResizeObserver)(element, this._syncDebounced)];
      return (0, _mobx.action)(() => {
        disposers.forEach(d => d == null ? void 0 : d());
        Object.assign(this.rect, emptyRect());
        if (scrollElement) {
          scrollElement.removeEventListener('scroll', this._syncThrottled);
        }
      });
    }
    return undefined;
  }
}
exports.RectState = RectState;
//# sourceMappingURL=RectState.js.map