"use strict";

var _typeof3 = require("@babel/runtime-corejs3/helpers/typeof");
var _mapInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/map");
var _sliceInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/slice");
var _Array$from = require("@babel/runtime-corejs3/core-js-stable/array/from");
var _Symbol = require("@babel/runtime-corejs3/core-js-stable/symbol");
var _getIteratorMethod = require("@babel/runtime-corejs3/core-js/get-iterator-method");
var _WeakMap = require("@babel/runtime-corejs3/core-js-stable/weak-map");
var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor");
var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.addResizeObserver = exports.STYLED_VERSION = exports.STYLED_REF_PROP = exports.OVERSCAN_SIZE = exports.AUTO_VIRTUAL_THRESHOLD = void 0;
exports.composeRowPropsGetter = composeRowPropsGetter;
exports.cssPolifill = void 0;
exports.getScrollbarSize = getScrollbarSize;
exports.getTableScrollFooterDOM = getTableScrollFooterDOM;
exports.getTableScrollHeaderDOM = getTableScrollHeaderDOM;
exports.shallowEqual = shallowEqual;
exports.sum = sum;
exports.syncScrollLeft = syncScrollLeft;
exports.throttledWindowResize$ = void 0;
var _set = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/set"));
var _is = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/is"));
var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/keys"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/typeof"));
var _extends2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/extends"));
var _rxjs = require("rxjs");
var _operators = require("rxjs/operators");
var _resizeObserverPolyfill = _interopRequireDefault(require("resize-observer-polyfill"));
var styledComponents = _interopRequireWildcard(require("styled-components"));
var _cssVarsPonyfill = _interopRequireDefault(require("css-vars-ponyfill"));
var _mergeCellProps = _interopRequireDefault(require("../utils/mergeCellProps"));
var _utils = require("../utils");
var _styles = require("./styles");
var _element = require("../utils/element");
function _getRequireWildcardCache(e) { if ("function" != typeof _WeakMap) return null; var r = new _WeakMap(), t = new _WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof3(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && _Object$getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? _Object$getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof _Symbol && _getIteratorMethod(r) || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { var _context; if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = _sliceInstanceProperty(_context = {}.toString.call(r)).call(_context, 8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? _Array$from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
/** styled-components 类库的版本，ali-react-table 同时支持 v3 和 v5 */
var STYLED_VERSION = exports.STYLED_VERSION = styledComponents.createGlobalStyle != null ? 'v5' : 'v3';
var STYLED_REF_PROP = exports.STYLED_REF_PROP = STYLED_VERSION === 'v3' ? 'innerRef' : 'ref';
var OVERSCAN_SIZE = exports.OVERSCAN_SIZE = 100;
var AUTO_VIRTUAL_THRESHOLD = exports.AUTO_VIRTUAL_THRESHOLD = 100;
function sum(arr) {
  var result = 0;
  arr.forEach(function (x) {
    result += x;
  });
  return result;
}
// 使用 defer 避免过早引用 window，导致在 SSR 场景下报错
var throttledWindowResize$ = exports.throttledWindowResize$ = (0, _rxjs.defer)(function () {
  return (0, _rxjs.fromEvent)(window, 'resize', {
    passive: true
  }).pipe((0, _operators.throttleTime)(150, _rxjs.asyncScheduler, {
    leading: true,
    trailing: true
  }));
});
var addResizeObserver = exports.addResizeObserver = function addResizeObserver(element, handler) {
  var measure = function measure(entries) {
    if (!entries[0] || !entries[0].contentRect) {
      return;
    }
    var contentRect = entries[0].contentRect;
    var hide = contentRect.width === 0 && contentRect.height === 0; // 隐藏条件：高宽都为0
    var rect = (0, _extends2.default)({
      hide: hide
    }, contentRect);
    handler && handler(rect);
  };
  var resizeObserver = new _resizeObserverPolyfill.default(measure);
  resizeObserver && resizeObserver.observe(element);
  return resizeObserver;
};
/** 获取默认的滚动条大小 */
function getScrollbarSizeImpl() {
  var scrollDiv = document.createElement('div');
  scrollDiv.style.position = 'absolute';
  scrollDiv.style.width = '100px';
  scrollDiv.style.height = '100px';
  scrollDiv.style.overflow = 'scroll';
  scrollDiv.style.top = '-9999px';
  document.body.appendChild(scrollDiv);
  var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
  var scrollbarHeight = scrollDiv.offsetHeight - scrollDiv.clientHeight;
  document.body.removeChild(scrollDiv);
  return {
    width: scrollbarWidth,
    height: scrollbarHeight
  };
}
var scrollBarSize$;
function getScrollbarSize() {
  if (scrollBarSize$ == null) {
    scrollBarSize$ = new _rxjs.BehaviorSubject(getScrollbarSizeImpl());
    throttledWindowResize$.pipe((0, _mapInstanceProperty(_operators))(function () {
      return getScrollbarSizeImpl();
    })).subscribe(scrollBarSize$);
  }
  return scrollBarSize$.value;
}
/** 同步多个元素之间的 scrollLeft, 每当 scrollLeft 发生变化时 callback 会被调用 */
function syncScrollLeft(elements, callback) {
  var bypassSet = new _set.default();
  function publishScrollLeft(origin, scrollLeft) {
    bypassSet.clear();
    var _iterator = _createForOfIteratorHelper(elements),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var elem = _step.value;
        if (elem === origin) {
          continue;
        }
        elem.scrollLeft = scrollLeft;
        bypassSet.add(elem);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  }
  var subscription = new _rxjs.Subscription();
  var _iterator2 = _createForOfIteratorHelper(elements),
    _step2;
  try {
    var _loop = function _loop() {
      var ele = _step2.value;
      var listener = function listener() {
        if (bypassSet.has(ele)) {
          bypassSet.delete(ele);
          return;
        }
        var scrollLeft = ele.scrollLeft;
        // 某一元素当滚动条消失时会触发scroll事件（scrolLeft重置为0），不同步其他其他元素的scrollLeft
        if (scrollLeft === 0 && !(0, _element.hasScroll)(ele)) {
          return;
        }
        publishScrollLeft(ele, scrollLeft);
        callback(scrollLeft);
      };
      ele.addEventListener('scroll', listener, {
        passive: true
      });
      subscription.add(function () {
        return ele.removeEventListener('scroll', listener);
      });
    };
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      _loop();
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
  return subscription;
}
/**
 * Performs equality by iterating through keys on an object and returning false
 * when any key has values which are not strictly equal between the arguments.
 * Returns true when the values of all keys are strictly equal.
 */
function shallowEqual(objA, objB) {
  var hasOwnProperty = Object.prototype.hasOwnProperty;
  if ((0, _is.default)(objA, objB)) {
    return true;
  }
  if ((0, _typeof2.default)(objA) !== 'object' || objA === null || (0, _typeof2.default)(objB) !== 'object' || objB === null) {
    return false;
  }
  var keysA = (0, _keys.default)(objA);
  var keysB = (0, _keys.default)(objB);
  if (keysA.length !== keysB.length) {
    return false;
  }
  // Test for A's keys different from B.
  for (var i = 0; i < keysA.length; i++) {
    if (!hasOwnProperty.call(objB, keysA[i]) || !(0, _is.default)(objA[keysA[i]], objB[keysA[i]])) {
      return false;
    }
  }
  return true;
}
// todo: 抽出mergeRowProps
function composeRowPropsGetter(getRowProps, pendingRowProps) {
  var keys = (0, _keys.default)(pendingRowProps);
  if (keys.length) {
    return function (row, rowIndex) {
      return (0, _mergeCellProps.default)(getRowProps(row, rowIndex), pendingRowProps);
    };
  }
  return getRowProps;
}
function getTableScrollHeaderDOM(domHelper) {
  return (0, _utils.isStickyUIDegrade)() ? domHelper.tableHeaderMain : domHelper.tableHeader;
}
function getTableScrollFooterDOM(domHelper) {
  return (0, _utils.isStickyUIDegrade)() ? domHelper.tableFooterMain : domHelper.tableFooter;
}
var cssPolifill = exports.cssPolifill = function cssPolifill(_ref) {
  var variables = _ref.variables,
    enableCSSVariables = _ref.enableCSSVariables,
    bordered = _ref.bordered;
  if (enableCSSVariables === false) {
    return;
  }
  var conditionCSSVariables = {};
  // 默认情况下存在td、th无左右边框，开启`bordered`属性后才开启，否则隐藏这两种属性
  if (!bordered) {
    conditionCSSVariables['--cell-border-vertical'] = 'none';
    conditionCSSVariables['--header-cell-border-vertical'] = 'none';
  }
  (0, _cssVarsPonyfill.default)({
    // exclude: 'link[href*="semantic-ui"]',
    // onlyLegacy: false,
    // rootElement: rootElement,
    include: 'style[data-styled]',
    variables: (0, _extends2.default)({}, _styles.defaultCSSVariables, variables, conditionCSSVariables),
    watch: true,
    silent: true
  });
};