"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = expanded;

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

var _propTypes = _interopRequireDefault(require("prop-types"));

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

var _button = _interopRequireDefault(require("../button"));

var _util = require("../util");

var _row = _interopRequireDefault(require("./expanded/row"));

var _column = _interopRequireDefault(require("./column"));

var _util2 = require("./util");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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 _typeof(obj) { 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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

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(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

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 _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

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

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

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

var noop = function noop() {};

function expanded(BaseComponent) {
  /** Table */
  var ExpandedTable =
  /*#__PURE__*/
  function (_React$Component) {
    _inherits(ExpandedTable, _React$Component);

    function ExpandedTable() {
      var _getPrototypeOf2;

      var _this;

      _classCallCheck(this, ExpandedTable);

      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(ExpandedTable)).call.apply(_getPrototypeOf2, [this].concat(args)));

      _defineProperty(_assertThisInitialized(_this), "state", {
        openRowKeys: _this.props.openRowKeys || []
      });

      _defineProperty(_assertThisInitialized(_this), "expandedKeydown", function (value, record, index, e) {
        e.preventDefault();
        e.stopPropagation();

        if (e.keyCode === _util.KEYCODE.ENTER) {
          _this.onExpandedClick(value, record, index, e);
        }
      });

      _defineProperty(_assertThisInitialized(_this), "renderExpandedCell", function (value, index, record) {
        var _classnames;

        var _this$props = _this.props,
            getExpandedColProps = _this$props.getExpandedColProps,
            prefix = _this$props.prefix,
            locale = _this$props.locale;
        var openRowKeys = _this.state.openRowKeys;
        var primaryKey = _this.props.primaryKey;
        var hasExpanded = openRowKeys.indexOf(record[primaryKey]) > -1;
        var switchNode = hasExpanded ? _react["default"].createElement(_button["default"].Icon, {
          type: "secondary",
          color: "gray",
          name: "triangle-down-s"
        }) : _react["default"].createElement(_button["default"].Icon, {
          type: "secondary",
          color: "gray",
          name: "triangle-right-s"
        });
        var attrs = getExpandedColProps(record, index) || {};
        var cls = (0, _classnames2["default"])((_classnames = {}, _defineProperty(_classnames, "".concat(prefix, "table-expanded-ctrl"), true), _defineProperty(_classnames, "disabled", attrs.disabled), _defineProperty(_classnames, attrs.className, attrs.className), _classnames));

        if (!attrs.disabled) {
          attrs.onClick = _this.onExpandedClick.bind(_assertThisInitialized(_this), value, record, index);
        }

        return _react["default"].createElement("span", _extends({}, attrs, {
          role: "button",
          tabIndex: "0",
          onKeyDown: _this.expandedKeydown.bind(_assertThisInitialized(_this), value, record, index),
          "aria-label": hasExpanded ? locale.expanded : locale.folded,
          "aria-expanded": hasExpanded,
          className: cls
        }), switchNode);
      });

      return _this;
    }

    _createClass(ExpandedTable, [{
      key: "getChildContext",
      value: function getChildContext() {
        return {
          openRowKeys: this.state.openRowKeys,
          expandedRowRender: this.props.expandedRowRender,
          expandedIndexSimulate: this.props.expandedIndexSimulate,
          expandedRowIndent: this.props.expandedRowIndent
        };
      }
    }, {
      key: "UNSAFE_componentWillReceiveProps",
      value: function UNSAFE_componentWillReceiveProps(nextProps) {
        if ('openRowKeys' in nextProps) {
          var openRowKeys = nextProps.openRowKeys;
          this.setState({
            openRowKeys: openRowKeys
          });
        }
      }
    }, {
      key: "onExpandedClick",
      value: function onExpandedClick(value, record, i, e) {
        var openRowKeys = _toConsumableArray(this.state.openRowKeys);

        var primaryKey = this.props.primaryKey;
        var id = record[primaryKey];
        var index = openRowKeys.indexOf(id);

        if (index > -1) {
          openRowKeys.splice(index, 1);
        } else {
          openRowKeys.push(id);
        }

        if (!('openRowKeys' in this.props)) {
          this.setState({
            openRowKeys: openRowKeys
          });
        }

        this.props.onRowOpen(openRowKeys, id, index === -1, record);
        e.stopPropagation();
      }
    }, {
      key: "normalizeChildren",
      value: function normalizeChildren(children) {
        var toArrayChildren = _react.Children.map(children, function (child, index) {
          return _react["default"].cloneElement(child, {
            key: index
          });
        });

        var prefix = this.props.prefix;
        toArrayChildren.unshift(_react["default"].createElement(_column["default"], {
          title: "",
          key: "expanded",
          cell: this.renderExpandedCell,
          width: 44,
          className: "".concat(prefix, "table-expanded"),
          __normalized: true
        }));
        return toArrayChildren;
      }
    }, {
      key: "normalizeDataSource",
      value: function normalizeDataSource(ds) {
        var ret = [];
        ds.forEach(function (item) {
          var itemCopy = _objectSpread({}, item);

          itemCopy.__expanded = true;
          ret.push(item, itemCopy);
        });
        return ret;
      }
    }, {
      key: "render",
      value: function render() {
        /* eslint-disable no-unused-vars, prefer-const */
        var _this$props2 = this.props,
            components = _this$props2.components,
            openRowKeys = _this$props2.openRowKeys,
            expandedRowRender = _this$props2.expandedRowRender,
            hasExpandedRowCtrl = _this$props2.hasExpandedRowCtrl,
            children = _this$props2.children,
            dataSource = _this$props2.dataSource,
            getExpandedColProps = _this$props2.getExpandedColProps,
            expandedRowIndent = _this$props2.expandedRowIndent,
            onRowOpen = _this$props2.onRowOpen,
            onExpandedRowClick = _this$props2.onExpandedRowClick,
            others = _objectWithoutProperties(_this$props2, ["components", "openRowKeys", "expandedRowRender", "hasExpandedRowCtrl", "children", "dataSource", "getExpandedColProps", "expandedRowIndent", "onRowOpen", "onExpandedRowClick"]);

        if (expandedRowRender && !components.Row) {
          components = _objectSpread({}, components);
          components.Row = _row["default"];
          dataSource = this.normalizeDataSource(dataSource);
        }

        if (expandedRowRender && hasExpandedRowCtrl) {
          children = this.normalizeChildren(children);
        }

        return _react["default"].createElement(BaseComponent, _extends({}, others, {
          dataSource: dataSource,
          components: components
        }), children);
      }
    }]);

    return ExpandedTable;
  }(_react["default"].Component);

  _defineProperty(ExpandedTable, "ExpandedRow", _row["default"]);

  _defineProperty(ExpandedTable, "propTypes", _objectSpread({
    /**
     * 额外渲染行的渲染函数
     * @param {Object} record 该行所对应的数据
     * @param {Number} index 该行所对应的序列
     * @returns {Element}
     */
    expandedRowRender: _propTypes["default"].func,

    /**
     * 额外渲染行的缩进
     */
    expandedRowIndent: _propTypes["default"].array,

    /**
     * 默认情况下展开的渲染行或者Tree, 传入此属性为受控状态
     */
    openRowKeys: _propTypes["default"].array,

    /**
     * 是否显示点击展开额外渲染行的+号按钮
     */
    hasExpandedRowCtrl: _propTypes["default"].bool,

    /**
     * 设置额外渲染行的属性
     */
    getExpandedColProps: _propTypes["default"].func,

    /**
     * 在额外渲染行或者Tree展开或者收起的时候触发的事件
     * @param {Array} openRowKeys 展开的渲染行的key
     * @param {String} currentRowKey 当前点击的渲染行的key
     * @param {Boolean} expanded 当前点击是展开还是收起
     * @param {Object} currentRecord 当前点击额外渲染行的记录
     */
    onRowOpen: _propTypes["default"].func,

    /**
     * 点击额外渲染行触发的事件
     * @param {Object} record 该行所对应的数据
     * @param {Number} index 该行所对应的序列
     * @param {Event} e DOM事件对象
     */
    onExpandedRowClick: _propTypes["default"].func,
    locale: _propTypes["default"].object
  }, BaseComponent.propTypes));

  _defineProperty(ExpandedTable, "defaultProps", _objectSpread({}, BaseComponent.defaultProps, {
    getExpandedColProps: noop,
    onRowOpen: noop,
    hasExpandedRowCtrl: true,
    components: {},
    expandedRowIndent: [1, 0],
    prefix: 'next-'
  }));

  _defineProperty(ExpandedTable, "childContextTypes", {
    openRowKeys: _propTypes["default"].array,
    expandedRowRender: _propTypes["default"].func,
    expandedIndexSimulate: _propTypes["default"].bool,
    expandedRowIndent: _propTypes["default"].array
  });

  (0, _util2.statics)(ExpandedTable, BaseComponent);
  return ExpandedTable;
}