"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 _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 || _typeof(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$from2(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; }

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