"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(nodeInterop) { if (typeof _WeakMap !== "function") return null; var cacheBabelInterop = new _WeakMap(); var cacheNodeInterop = new _WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof3(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && _Object$getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? _Object$getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof _Symbol !== "undefined" && _getIteratorMethod(o) || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, 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 normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { var _context; if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = _sliceInstanceProperty(_context = Object.prototype.toString.call(o)).call(_context, 8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return _Array$from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

/** styled-components 类库的版本，ali-react-table 同时支持 v3 和 v5 */
var STYLED_VERSION = styledComponents.createGlobalStyle != null ? 'v5' : 'v3';
exports.STYLED_VERSION = STYLED_VERSION;
var STYLED_REF_PROP = STYLED_VERSION === 'v3' ? 'innerRef' : 'ref';
exports.STYLED_REF_PROP = STYLED_REF_PROP;
var OVERSCAN_SIZE = 100;
exports.OVERSCAN_SIZE = OVERSCAN_SIZE;
var AUTO_VIRTUAL_THRESHOLD = 100;
exports.AUTO_VIRTUAL_THRESHOLD = AUTO_VIRTUAL_THRESHOLD;

function sum(arr) {
  var result = 0;
  arr.forEach(function (x) {
    result += x;
  });
  return result;
} // 使用 defer 避免过早引用 window，导致在 SSR 场景下报错


var throttledWindowResize$ = (0, _rxjs.defer)(function () {
  return (0, _rxjs.fromEvent)(window, 'resize', {
    passive: true
  }).pipe((0, _operators.throttleTime)(150, _rxjs.asyncScheduler, {
    leading: true,
    trailing: true
  }));
});
exports.throttledWindowResize$ = throttledWindowResize$;

var 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;
};
/** 获取默认的滚动条大小 */


exports.addResizeObserver = addResizeObserver;

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 _utils.browserType.isIE ? domHelper.tableHeaderMain : domHelper.tableHeader;
}

function getTableScrollFooterDOM(domHelper) {
  return _utils.browserType.isIE ? domHelper.tableFooterMain : domHelper.tableFooter;
}

var 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
  });
};

exports.cssPolifill = cssPolifill;