"use strict";

var _typeof = require("@babel/runtime-corejs3/helpers/typeof");
var _sliceInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/slice");
var _Array$from2 = 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.useAutoWidthTransform = useAutoWidthTransform;
var _from = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/array/from"));
var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat"));
var _extends2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/extends"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/slicedToArray"));
var _taggedTemplateLiteral2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/taggedTemplateLiteral"));
var _react = _interopRequireWildcard(require("react"));
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _base = require("../base");
var _internals = require("../internals");
var _utils = require("../utils");
var _warnTransformsDeprecated = require("./warnTransformsDeprecated");
var _templateObject;
function _interopRequireWildcard(e, t) { if ("function" == typeof _WeakMap) var r = new _WeakMap(), n = new _WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && _Object$getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
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$from2(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; }
var AUTO_WIDTH_WRAPPER_CLS = 'auto-width-wrapper';
var AUTO_WIDTH_EXPANDER_CLS = 'auto-width-expander';
var AutoWidthWrapper = _styledComponents.default.div(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2.default)(["\n  height: 100%;\n  display: inline-flex;\n  align-items: center;\n  white-space: nowrap;\n  padding: 8px 12px;\n"])));
function isSameArray(arr1, arr2) {
  return arr1.length === arr2.length && arr1.every(function (x, i) {
    return x === arr2[i];
  });
}
/** 自适应列宽
 *
 * @deprecated transform 用法已经过时，请使用 pipeline 来对表格进行拓展
 *
 * @param tableRef BaseTable 的 ref
 * @param options 参数
 * @param deps 重新调整列宽的依赖数组，每当依赖数组发生变化时， useAutoWidthTransform 会根据单元格内容的实际渲染宽度 设置单元格的宽度
 *
 * options 说明：
 * - options.appendExpander 是否在列的末尾追加可伸缩列
 * - options.expanderVisibility 设置为 `'hidden'` 可以隐藏可伸缩列
 * - options.wrapperStyle 单元格中 div.auto-width-wrapper 的样式
 * - options.initColumnWidth 自适应的初始列宽
 *
 * 注意 useAutoWidthTransform 是一个 React hooks，要遵循 hooks 的用法规范
 * */
function useAutoWidthTransform(tableRef, options, deps) {
  (0, _warnTransformsDeprecated.warnTransformsDeprecated)('useAutoWidthTransform');
  var _useState = (0, _react.useState)([]),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    widthList = _useState2[0],
    setWidthList = _useState2[1];
  (0, _react.useEffect)(function () {
    var artTable = tableRef.current.getDoms().artTable;
    var rows = (0, _from.default)(artTable.querySelectorAll(".".concat(_base.Classes.tableRow)));
    if (rows.length === 0) {
      return;
    }
    var preferredWidthList = [];
    var _iterator = _createForOfIteratorHelper(rows),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var row = _step.value;
        var autoWidthDivList = row.querySelectorAll(".".concat(AUTO_WIDTH_WRAPPER_CLS));
        autoWidthDivList.forEach(function (div, i) {
          var _a;
          preferredWidthList[i] = Math.max((_a = preferredWidthList[i]) !== null && _a !== void 0 ? _a : 0, div.scrollWidth);
        });
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
    if (!isSameArray(preferredWidthList, widthList)) {
      setWidthList(preferredWidthList);
    }
  }, deps);
  var i = 0;
  var innerTransform = (0, _utils.traverseColumn)(function (col) {
    var _a, _b, _c;
    if (!(0, _utils.isLeafNode)(col)) {
      return col;
    }
    if (!((_a = col.features) === null || _a === void 0 ? void 0 : _a.autoWidth)) {
      return col;
    }
    var _col$features$autoWid = col.features.autoWidth,
      _col$features$autoWid2 = _col$features$autoWid.max,
      max = _col$features$autoWid2 === void 0 ? Infinity : _col$features$autoWid2,
      _col$features$autoWid3 = _col$features$autoWid.min,
      min = _col$features$autoWid3 === void 0 ? -Infinity : _col$features$autoWid3;
    var width = (_c = (_b = widthList[i++]) !== null && _b !== void 0 ? _b : col.width) !== null && _c !== void 0 ? _c : options === null || options === void 0 ? void 0 : options.initColumnWidth;
    var clampedWidth = Math.max(min, Math.min(max, width));
    return (0, _extends2.default)((0, _extends2.default)({}, col), {
      width: clampedWidth,
      getCellProps: function getCellProps(_, record, rowIndex) {
        return (0, _utils.mergeCellProps)(_internals.internals.safeGetCellProps(col, record, rowIndex), {
          style: {
            padding: 0
          }
        });
      },
      render: function render(_, record, rowIndex) {
        return /*#__PURE__*/_react.default.createElement(AutoWidthWrapper, {
          className: AUTO_WIDTH_WRAPPER_CLS,
          style: options === null || options === void 0 ? void 0 : options.wrapperStyle
        }, _internals.internals.safeRender(col, record, rowIndex));
      }
    });
  });
  return function (input) {
    var _a;
    var _innerTransform = innerTransform(input),
      columns = _innerTransform.columns,
      dataSource = _innerTransform.dataSource;
    var expanderVisibility = (_a = options === null || options === void 0 ? void 0 : options.expanderVisibility) !== null && _a !== void 0 ? _a : 'visible';
    return {
      columns: (options === null || options === void 0 ? void 0 : options.appendExpander) ? (0, _concat.default)(columns).call(columns, [{
        name: '',
        headerCellProps: {
          className: AUTO_WIDTH_EXPANDER_CLS,
          style: {
            background: expanderVisibility === 'hidden' ? 'var(--bgcolor)' : undefined,
            border: expanderVisibility === 'hidden' ? 'none' : undefined
          }
        },
        getCellProps: function getCellProps() {
          return {
            className: AUTO_WIDTH_EXPANDER_CLS,
            style: {
              visibility: expanderVisibility
            }
          };
        }
      }]) : columns,
      dataSource: dataSource
    };
  };
}