"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

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

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var __importStar = void 0 && (void 0).__importStar || function (mod) {
  if (mod && mod.__esModule) return mod;
  var result = {};
  if (mod != null) for (var k in mod) {
    if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
  }
  result["default"] = mod;
  return result;
};

var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
  return mod && mod.__esModule ? mod : {
    "default": mod
  };
};

Object.defineProperty(exports, "__esModule", {
  value: true
});

var React = __importStar(require("react"));

var mini_store_1 = require("mini-store");

var react_lifecycles_compat_1 = require("react-lifecycles-compat");

var shallowequal_1 = __importDefault(require("shallowequal"));

var TableRow_1 = __importDefault(require("./TableRow"));

var utils_1 = require("./utils");

var ExpandableTable = /*#__PURE__*/function (_React$Component) {
  _inherits(ExpandableTable, _React$Component);

  var _super = _createSuper(ExpandableTable);

  function ExpandableTable(props) {
    var _this;

    _classCallCheck(this, ExpandableTable);

    _this = _super.call(this, props);

    _this.handleExpandChange = function (expanded, record, event, rowKey) {
      var destroy = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;

      if (event) {
        event.stopPropagation();
      }

      var _this$props = _this.props,
          onExpandedRowsChange = _this$props.onExpandedRowsChange,
          onExpand = _this$props.onExpand;

      var _this$store$getState = _this.store.getState(),
          expandedRowKeys = _this$store$getState.expandedRowKeys;

      if (expanded) {
        // row was expanded
        expandedRowKeys = [].concat(_toConsumableArray(expandedRowKeys), [rowKey]);
      } else {
        // row was collapse
        var expandedRowIndex = expandedRowKeys.indexOf(rowKey);

        if (expandedRowIndex !== -1) {
          expandedRowKeys = utils_1.remove(expandedRowKeys, rowKey);
        }
      }

      if (!_this.props.expandedRowKeys) {
        _this.store.setState({
          expandedRowKeys: expandedRowKeys
        });
      } // De-dup of repeat call


      if (!_this.latestExpandedRows || !shallowequal_1.default(_this.latestExpandedRows, expandedRowKeys)) {
        _this.latestExpandedRows = expandedRowKeys;
        onExpandedRowsChange(expandedRowKeys);
      }

      if (!destroy) {
        onExpand(expanded, record);
      }
    };

    _this.renderExpandIndentCell = function (rows, fixed) {
      var _this$props2 = _this.props,
          prefixCls = _this$props2.prefixCls,
          expandIconAsCell = _this$props2.expandIconAsCell;

      if (!expandIconAsCell || fixed === 'right' || !rows.length) {
        return;
      }

      var iconColumn = {
        key: 'rc-table-expand-icon-cell',
        className: "".concat(prefixCls, "-expand-icon-th"),
        title: '',
        rowSpan: rows.length
      };
      rows[0].unshift(_objectSpread({}, iconColumn, {
        column: iconColumn
      }));
    };

    _this.renderRows = function (renderRows, rows, record, index, indent, fixed, parentKey, ancestorKeys) {
      var _this$props3 = _this.props,
          expandedRowClassName = _this$props3.expandedRowClassName,
          expandedRowRender = _this$props3.expandedRowRender,
          childrenColumnName = _this$props3.childrenColumnName;
      var childrenData = record[childrenColumnName];
      var nextAncestorKeys = [].concat(_toConsumableArray(ancestorKeys), [parentKey]);
      var nextIndent = indent + 1;

      if (expandedRowRender) {
        rows.push(_this.renderExpandedRow(record, index, expandedRowRender, expandedRowClassName(record, index, indent), nextAncestorKeys, nextIndent, fixed));
      }

      if (childrenData) {
        rows.push.apply(rows, _toConsumableArray(renderRows(childrenData, nextIndent, nextAncestorKeys)));
      }
    };

    var data = props.data,
        childrenColumnName = props.childrenColumnName,
        defaultExpandAllRows = props.defaultExpandAllRows,
        expandedRowKeys = props.expandedRowKeys,
        defaultExpandedRowKeys = props.defaultExpandedRowKeys,
        getRowKey = props.getRowKey;
    var finalExpandedRowKeys = [];

    var rows = _toConsumableArray(data);

    if (defaultExpandAllRows) {
      for (var i = 0; i < rows.length; i += 1) {
        var row = rows[i];
        finalExpandedRowKeys.push(getRowKey(row, i));
        rows = rows.concat(row[childrenColumnName] || []);
      }
    } else {
      finalExpandedRowKeys = expandedRowKeys || defaultExpandedRowKeys;
    }

    _this.columnManager = props.columnManager;
    _this.store = props.store;

    _this.store.setState({
      expandedRowsHeight: {},
      expandedRowKeys: finalExpandedRowKeys
    });

    return _this;
  }

  _createClass(ExpandableTable, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.handleUpdated();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      if ('expandedRowKeys' in this.props) {
        this.store.setState({
          expandedRowKeys: this.props.expandedRowKeys
        });
      }

      this.handleUpdated();
    }
  }, {
    key: "handleUpdated",
    value: function handleUpdated() {
      /**
       * We should record latest expanded rows to avoid
       * multiple rows remove cause `onExpandedRowsChange` trigger many times
       */
      this.latestExpandedRows = null;
    }
  }, {
    key: "renderExpandedRow",
    value: function renderExpandedRow(record, index, _render, className, ancestorKeys, indent, fixed) {
      var _this2 = this;

      var _this$props4 = this.props,
          prefixCls = _this$props4.prefixCls,
          expandIconAsCell = _this$props4.expandIconAsCell,
          indentSize = _this$props4.indentSize;
      var parentKey = ancestorKeys[ancestorKeys.length - 1];
      var rowKey = "".concat(parentKey, "-extra-row");
      var components = {
        body: {
          row: 'tr',
          cell: 'td'
        }
      };
      var colCount;

      if (fixed === 'left') {
        colCount = this.columnManager.leftLeafColumns().length;
      } else if (fixed === 'right') {
        colCount = this.columnManager.rightLeafColumns().length;
      } else {
        colCount = this.columnManager.leafColumns().length;
      }

      var columns = [{
        key: 'extra-row',
        render: function render() {
          var _this2$store$getState = _this2.store.getState(),
              _this2$store$getState2 = _this2$store$getState.expandedRowKeys,
              expandedRowKeys = _this2$store$getState2 === void 0 ? [] : _this2$store$getState2;

          var expanded = expandedRowKeys.includes(parentKey);
          return {
            props: {
              colSpan: colCount
            },
            children: fixed !== 'right' ? _render(record, index, indent, expanded) : '&nbsp;'
          };
        }
      }];

      if (expandIconAsCell && fixed !== 'right') {
        columns.unshift({
          key: 'expand-icon-placeholder',
          render: function render() {
            return null;
          }
        });
      }

      return React.createElement(TableRow_1.default, {
        key: rowKey,
        columns: columns,
        className: className,
        rowKey: rowKey,
        ancestorKeys: ancestorKeys,
        prefixCls: "".concat(prefixCls, "-expanded-row"),
        indentSize: indentSize,
        indent: indent,
        fixed: fixed,
        components: components,
        expandedRow: true
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props5 = this.props,
          data = _this$props5.data,
          childrenColumnName = _this$props5.childrenColumnName,
          children = _this$props5.children;
      var needIndentSpaced = data.some(function (record) {
        return record[childrenColumnName];
      });
      return children({
        props: this.props,
        needIndentSpaced: needIndentSpaced,
        renderRows: this.renderRows,
        handleExpandChange: this.handleExpandChange,
        renderExpandIndentCell: this.renderExpandIndentCell
      });
    }
  }]);

  return ExpandableTable;
}(React.Component);

ExpandableTable.defaultProps = {
  expandIconAsCell: false,
  expandedRowClassName: function expandedRowClassName() {
    return '';
  },
  expandIconColumnIndex: 0,
  defaultExpandAllRows: false,
  defaultExpandedRowKeys: [],
  childrenColumnName: 'children',
  indentSize: 15,
  onExpand: function onExpand() {},
  onExpandedRowsChange: function onExpandedRowsChange() {}
};
react_lifecycles_compat_1.polyfill(ExpandableTable);
exports.default = mini_store_1.connect()(ExpandableTable);