"use strict";

var _sliceInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/slice");

var _Array$from = require("@babel/runtime-corejs3/core-js-stable/array/from");

var _Symbol2 = require("@babel/runtime-corejs3/core-js-stable/symbol");

var _getIteratorMethod = require("@babel/runtime-corejs3/core-js/get-iterator-method");

var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.treeMetaSymbol = void 0;
exports.treeMode = treeMode;

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/defineProperty"));

var _extends3 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/extends"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/toConsumableArray"));

var _symbol = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/symbol"));

var _set = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/set"));

var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/filter"));

var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat"));

var _findIndex = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/find-index"));

var _classnames = _interopRequireDefault(require("classnames"));

var _react = _interopRequireDefault(require("react"));

var _commonViews = require("../../common-views");

var _internals = require("../../internals");

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

var _styles = require("../../base/styles");

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof _Symbol2 !== "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(_e2) { throw _e2; }, 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(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { var _context2; if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = _sliceInstanceProperty(_context2 = Object.prototype.toString.call(o)).call(_context2, 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; }

var treeMetaSymbol = (0, _symbol.default)('treeMetaSymbol');
exports.treeMetaSymbol = treeMetaSymbol;

function treeMode() {
  var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return function treeModeStep(pipeline) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j;

    var stateKey = 'treeMode';
    var ctx = pipeline.ctx;
    var primaryKey = pipeline.ensurePrimaryKey('treeMode');
    var openKeys = (_c = (_b = (_a = opts.openKeys) !== null && _a !== void 0 ? _a : pipeline.getStateAtKey(stateKey)) !== null && _b !== void 0 ? _b : opts.defaultOpenKeys) !== null && _c !== void 0 ? _c : [];
    var openKeySet = new _set.default(openKeys);

    var onChangeOpenKeys = function onChangeOpenKeys(nextKeys, key, action) {
      var _a;

      (_a = opts.onChangeOpenKeys) === null || _a === void 0 ? void 0 : _a.call(opts, nextKeys, key, action);
      pipeline.setStateAtKey(stateKey, nextKeys, {
        key: key,
        action: action
      });
    };

    var toggle = function toggle(rowKey) {
      var expanded = openKeySet.has(rowKey);

      if (expanded) {
        onChangeOpenKeys((0, _filter.default)(openKeys).call(openKeys, function (key) {
          return key !== rowKey;
        }), rowKey, 'collapse');
      } else {
        var _context;

        onChangeOpenKeys((0, _concat.default)(_context = []).call(_context, (0, _toConsumableArray2.default)(openKeys), [rowKey]), rowKey, 'expand');
      }
    };

    var isLeafNode = (_d = opts.isLeafNode) !== null && _d !== void 0 ? _d : _utils.isLeafNode;
    var clickArea = (_e = opts.clickArea) !== null && _e !== void 0 ? _e : 'cell';
    var treeMetaKey = (_f = opts.treeMetaKey) !== null && _f !== void 0 ? _f : treeMetaSymbol;
    var stopClickEventPropagation = Boolean(opts.stopClickEventPropagation); // indents

    var iconWidth = ctx.indents.iconWidth;
    var iconIndent = (_g = opts.iconIndent) !== null && _g !== void 0 ? _g : ctx.indents.iconIndent;
    var iconGap = (_h = opts.iconGap) !== null && _h !== void 0 ? _h : ctx.indents.iconGap;
    var indentSize = (_j = opts.indentSize) !== null && _j !== void 0 ? _j : ctx.indents.indentSize;
    var Icon = opts.icon;
    return pipeline.mapDataSource(processDataSource).mapColumns(processColumns);

    function processDataSource(input) {
      var result = [];
      dfs(input, 0);

      function dfs(nodes, depth) {
        if (nodes == null) {
          return;
        }

        var _iterator = _createForOfIteratorHelper(nodes),
            _step;

        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var node = _step.value;

            var rowKey = _internals.internals.safeGetRowKey(primaryKey, node, -1);

            var expanded = openKeySet.has(rowKey);
            var isLeaf = isLeafNode(node, {
              depth: depth,
              expanded: expanded,
              rowKey: rowKey
            });
            var treeMeta = {
              depth: depth,
              isLeaf: isLeaf,
              expanded: expanded,
              rowKey: rowKey
            };
            result.push((0, _extends3.default)((0, _defineProperty2.default)({}, treeMetaKey, treeMeta), node));

            if (!isLeaf && expanded) {
              dfs(node.children, depth + 1);
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
      }

      return result;
    }

    function processColumns(columns) {
      if (columns.length === 0) {
        return columns;
      }

      var expandColIndex = (0, _findIndex.default)(columns).call(columns, function (_ref) {
        var code = _ref.code;
        return code && opts.expandColCode === code;
      });
      expandColIndex = expandColIndex === -1 ? 0 : expandColIndex;
      var expandCol = columns[expandColIndex];

      var render = function render(value, record, recordIndex) {
        var content = _internals.internals.safeRender(expandCol, record, recordIndex);

        if (record[treeMetaKey] == null) {
          // 没有 treeMeta 信息的话，就返回原先的渲染结果
          return content;
        }

        var _record$treeMetaKey = record[treeMetaKey],
            rowKey = _record$treeMetaKey.rowKey,
            depth = _record$treeMetaKey.depth,
            isLeaf = _record$treeMetaKey.isLeaf,
            expanded = _record$treeMetaKey.expanded;
        var indent = iconIndent + depth * indentSize;

        if (isLeaf) {
          return /*#__PURE__*/_react.default.createElement(_commonViews.InlineFlexCell, {
            className: (0, _classnames.default)('expansion-cell', _styles.Classes.leaf)
          }, /*#__PURE__*/_react.default.createElement("span", {
            style: {
              marginLeft: indent + iconWidth + iconGap
            }
          }, content));
        }

        var onClick = function onClick(e) {
          if (stopClickEventPropagation) {
            e.stopPropagation();
          }

          toggle(rowKey);
        };

        var expandCls = expanded ? _styles.Classes.expanded : _styles.Classes.collapsed;
        return /*#__PURE__*/_react.default.createElement(_commonViews.ExpansionCell, {
          className: (0, _classnames.default)('expansion-cell', expandCls),
          style: {
            cursor: clickArea === 'content' ? 'pointer' : undefined
          },
          onClick: clickArea === 'content' ? onClick : undefined
        }, Icon ? /*#__PURE__*/_react.default.createElement(Icon, {
          expanded: expanded,
          style: {
            cursor: clickArea === 'icon' ? 'pointer' : undefined,
            marginLeft: indent,
            marginRight: iconGap,
            width: iconWidth
          },
          onClick: clickArea === 'icon' ? onClick : undefined
        }) : /*#__PURE__*/_react.default.createElement(_commonViews.icons.CaretRight, {
          className: (0, _classnames.default)('expansion-icon', expandCls),
          style: {
            cursor: clickArea === 'icon' ? 'pointer' : undefined,
            marginLeft: indent,
            marginRight: iconGap
          },
          onClick: clickArea === 'icon' ? onClick : undefined
        }), content);
      };

      var getCellProps = function getCellProps(value, record, rowIndex) {
        var prevProps = _internals.internals.safeGetCellProps(expandCol, record, rowIndex);

        if (record[treeMetaKey] == null) {
          // 没有 treeMeta 信息的话，就返回原先的 cellProps
          return prevProps;
        }

        var _record$treeMetaKey2 = record[treeMetaKey],
            isLeaf = _record$treeMetaKey2.isLeaf,
            rowKey = _record$treeMetaKey2.rowKey;

        if (isLeaf) {
          return prevProps;
        }

        return (0, _utils.mergeCellProps)(prevProps, {
          onClick: function onClick(e) {
            if (stopClickEventPropagation) {
              e.stopPropagation();
            }

            toggle(rowKey);
          },
          style: {
            cursor: 'pointer'
          }
        });
      };

      columns[expandColIndex] = (0, _extends3.default)((0, _extends3.default)({}, expandCol), {
        title: /*#__PURE__*/_react.default.createElement("span", {
          style: {
            marginLeft: iconIndent + iconWidth + iconGap,
            display: 'flex'
          }
        }, _internals.internals.safeRenderHeader(expandCol)),
        render: render,
        getCellProps: clickArea === 'cell' ? getCellProps : expandCol.getCellProps
      });
      return (0, _toConsumableArray2.default)(columns);
    }
  };
}