text: "use strict";
  
  Object.defineProperty(exports, "__esModule", {
    value: true
  });
  exports.getSortData = getSortData;
  exports["default"] = useFilterSorter;
  
  var React = _interopRequireWildcard(require("react"));
  
  var _classnames = _interopRequireDefault(require("classnames"));
  
  var _useColumns = require("rc-table/lib/hooks/useColumns");
  
  var _CaretDownOutlined = _interopRequireDefault(require("@ant-design/icons/CaretDownOutlined"));
  
  var _CaretUpOutlined = _interopRequireDefault(require("@ant-design/icons/CaretUpOutlined"));
  
  var _tooltip = _interopRequireDefault(require("../../tooltip"));
  
  var _util = 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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
  
  function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  
  function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
  
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
  
  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 _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 _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 _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); }
  
  var ASCEND = 'ascend';
  var DESCEND = 'descend';
  
  function getMultiplePriority(column) {
    if (_typeof(column.sorter) === 'object' && typeof column.sorter.multiple === 'number') {
      return column.sorter.multiple;
    }
  
    return false;
  }
  
  function getSortFunction(sorter) {
    if (typeof sorter === 'function') {
      return sorter;
    }
  
    if (sorter && _typeof(sorter) === 'object' && sorter.compare) {
      return sorter.compare;
    }
  
    return false;
  }
  
  function nextSortDirection(sortDirections, current) {
    if (!current) {
      return sortDirections[0];
    }
  
    return sortDirections[sortDirections.indexOf(current) + 1];
  }
  
  function collectSortStates(columns, init, pos) {
    var sortStates = [];
  
    function pushState(column, columnPos) {
      sortStates.push({
        column: column,
        key: (0, _util.getColumnKey)(column, columnPos),
        multiplePriority: getMultiplePriority(column),
        sortOrder: column.sortOrder
      });
    }
  
    (columns || []).forEach(function (column, index) {
      var columnPos = (0, _util.getColumnPos)(index, pos);
  
      if (column.children) {
        if ('sortOrder' in column) {
          // Controlled
          pushState(column, columnPos);
        }
  
        sortStates = [].concat(_toConsumableArray(sortStates), _toConsumableArray(collectSortStates(column.children, init, columnPos)));
      } else if (column.sorter) {
        if ('sortOrder' in column) {
          // Controlled
          pushState(column, columnPos);
        } else if (init && column.defaultSortOrder) {
          // Default sorter
          sortStates.push({
            column: column,
            key: (0, _util.getColumnKey)(column, columnPos),
            multiplePriority: getMultiplePriority(column),
            sortOrder: column.defaultSortOrder
          });
        }
      }
    });
    return sortStates;
  }
  
  function injectSorter(prefixCls, columns, sorterSates, triggerSorter, defaultSortDirections, tableLocale, tableShowSorterTooltip, pos) {
    return (columns || []).map(function (column, index) {
      var columnPos = (0, _util.getColumnPos)(index, pos);
      var newColumn = column;
  
      if (newColumn.sorter) {
        var sortDirections = newColumn.sortDirections || defaultSortDirections;
        var showSorterTooltip = newColumn.showSorterTooltip === undefined ? tableShowSorterTooltip : newColumn.showSorterTooltip;
        var columnKey = (0, _util.getColumnKey)(newColumn, columnPos);
        var sorterState = sorterSates.find(function (_ref) {
          var key = _ref.key;
          return key === columnKey;
        });
        var sorterOrder = sorterState ? sorterState.sortOrder : null;
        var nextSortOrder = nextSortDirection(sortDirections, sorterOrder);
        var upNode = sortDirections.includes(ASCEND) && /*#__PURE__*/React.createElement(_CaretUpOutlined["default"], {
          className: (0, _classnames["default"])("".concat(prefixCls, "-column-sorter-up"), {
            active: sorterOrder === ASCEND
          })
        });
        var downNode = sortDirections.includes(DESCEND) && /*#__PURE__*/React.createElement(_CaretDownOutlined["default"], {
          className: (0, _classnames["default"])("".concat(prefixCls, "-column-sorter-down"), {
            active: sorterOrder === DESCEND
          })
        });
  
        var _ref2 = tableLocale || {},
            cancelSort = _ref2.cancelSort,
            triggerAsc = _ref2.triggerAsc,
            triggerDesc = _ref2.triggerDesc;
  
        var sortTip = cancelSort;
  
        if (nextSortOrder === DESCEND) {
          sortTip = triggerDesc;
        } else if (nextSortOrder === ASCEND) {
          sortTip = triggerAsc;
        }
  
        newColumn = _extends(_extends({}, newColumn), {
          className: (0, _classnames["default"])(newColumn.className, _defineProperty({}, "".concat(prefixCls, "-column-sort"), sorterOrder)),
          title: function title(renderProps) {
            var renderSortTitle = /*#__PURE__*/React.createElement("div", {
              className: "".concat(prefixCls, "-column-sorters")
            }, /*#__PURE__*/React.createElement("span", null, (0, _util.renderColumnTitle)(column.title, renderProps)), /*#__PURE__*/React.createElement("span", {
              className: (0, _classnames["default"])("".concat(prefixCls, "-column-sorter"), _defineProperty({}, "".concat(prefixCls, "-column-sorter-full"), upNode && downNode))
            }, /*#__PURE__*/React.createElement("span", {
              className: "".concat(prefixCls, "-column-sorter-inner")
            }, upNode, downNode)));
            return showSorterTooltip ? /*#__PURE__*/React.createElement(_tooltip["default"], {
              title: sortTip
            }, /*#__PURE__*/React.createElement("div", {
              className: "".concat(prefixCls, "-column-sorters-with-tooltip")
            }, renderSortTitle)) : renderSortTitle;
          },
          onHeaderCell: function onHeaderCell(col) {
            var cell = column.onHeaderCell && column.onHeaderCell(col) || {};
            var originOnClick = cell.onClick;
  
            cell.onClick = function (event) {
              triggerSorter({
                column: column,
                key: columnKey,
                sortOrder: nextSortOrder,
                multiplePriority: getMultiplePriority(column)
              });
  
              if (originOnClick) {
                originOnClick(event);
              }
            };
  
            cell.className = (0, _classnames["default"])(cell.className, "".concat(prefixCls, "-column-has-sorters"));
            return cell;
          }
        });
      }
  
      if ('children' in newColumn) {
        newColumn = _extends(_extends({}, newColumn), {
          children: injectSorter(prefixCls, newColumn.children, sorterSates, triggerSorter, defaultSortDirections, tableLocale, tableShowSorterTooltip, columnPos)
        });
      }
  
      return newColumn;
    });
  }
  
  function stateToInfo(sorterStates) {
    var column = sorterStates.column,
        sortOrder = sorterStates.sortOrder;
    return {
      column: column,
      order: sortOrder,
      field: column.dataIndex,
      columnKey: column.key
    };
  }
  
  function generateSorterInfo(sorterStates) {
    var list = sorterStates.filter(function (_ref3) {
      var sortOrder = _ref3.sortOrder;
      return sortOrder;
    }).map(stateToInfo); // =========== Legacy compatible support ===========
    // https://github.com/ant-design/ant-design/pull/19226
  
    if (list.length === 0 && sorterStates.length) {
      return _extends(_extends({}, stateToInfo(sorterStates[0])), {
        column: undefined
      });
    }
  
    if (list.length <= 1) {
      return list[0] || {};
    }
  
    return list;
  }
  
  function getSortData(data, sortStates, childrenColumnName) {
    var innerSorterStates = sortStates.slice().sort(function (a, b) {
      return b.multiplePriority - a.multiplePriority;
    });
    var cloneData = data.slice();
    var runningSorters = innerSorterStates.filter(function (_ref4) {
      var sorter = _ref4.column.sorter,
          sortOrder = _ref4.sortOrder;
      return getSortFunction(sorter) && sortOrder;
    }); // Skip if no sorter needed
  
    if (!runningSorters.length) {
      return cloneData;
    }
  
    return cloneData.sort(function (record1, record2) {
      for (var i = 0; i < runningSorters.length; i += 1) {
        var sorterState = runningSorters[i];
        var sorter = sorterState.column.sorter,
            sortOrder = sorterState.sortOrder;
        var compareFn = getSortFunction(sorter);
  
        if (compareFn && sortOrder) {
          var compareResult = compareFn(record1, record2, sortOrder);
  
          if (compareResult !== 0) {
            return sortOrder === ASCEND ? compareResult : -compareResult;
          }
        }
      }
  
      return 0;
    }).map(function (record) {
      var subRecords = record[childrenColumnName];
  
      if (subRecords) {
        return _extends(_extends({}, record), _defineProperty({}, childrenColumnName, getSortData(subRecords, sortStates, childrenColumnName)));
      }
  
      return record;
    });
  }
  
  function useFilterSorter(_ref5) {
    var prefixCls = _ref5.prefixCls,
        columns = _ref5.columns,
        children = _ref5.children,
        onSorterChange = _ref5.onSorterChange,
        sortDirections = _ref5.sortDirections,
        tableLocale = _ref5.tableLocale,
        showSorterTooltip = _ref5.showSorterTooltip;
    var mergedColumns = React.useMemo(function () {
      return columns || (0, _useColumns.convertChildrenToColumns)(children);
    }, [children, columns]);
  
    var _React$useState = React.useState(collectSortStates(mergedColumns, true)),
        _React$useState2 = _slicedToArray(_React$useState, 2),
        sortStates = _React$useState2[0],
        setSortStates = _React$useState2[1];
  
    var mergedSorterStates = React.useMemo(function () {
      var validate = true;
      var collectedStates = collectSortStates(mergedColumns, false); // Return if not controlled
  
      if (!collectedStates.length) {
        return sortStates;
      }
  
      var validateStates = [];
  
      function patchStates(state) {
        if (validate) {
          validateStates.push(state);
        } else {
          validateStates.push(_extends(_extends({}, state), {
            sortOrder: null
          }));
        }
      }
  
      var multipleMode = null;
      collectedStates.forEach(function (state) {
        if (multipleMode === null) {
          patchStates(state);
  
          if (state.sortOrder) {
            if (state.multiplePriority === false) {
              validate = false;
            } else {
              multipleMode = true;
            }
          }
        } else if (multipleMode && state.multiplePriority !== false) {
          patchStates(state);
        } else {
          validate = false;
          patchStates(state);
        }
      });
      return validateStates;
    }, [mergedColumns, sortStates]); // Get render columns title required props
  
    var columnTitleSorterProps = React.useMemo(function () {
      var sortColumns = mergedSorterStates.map(function (_ref6) {
        var column = _ref6.column,
            sortOrder = _ref6.sortOrder;
        return {
          column: column,
          order: sortOrder
        };
      });
      return {
        sortColumns: sortColumns,
        // Legacy
        sortColumn: sortColumns[0] && sortColumns[0].column,
        sortOrder: sortColumns[0] && sortColumns[0].order
      };
    }, [mergedSorterStates]);
  
    function triggerSorter(sortState) {
      var newSorterStates;
  
      if (sortState.multiplePriority === false || !mergedSorterStates.length || mergedSorterStates[0].multiplePriority === false) {
        newSorterStates = [sortState];
      } else {
        newSorterStates = [].concat(_toConsumableArray(mergedSorterStates.filter(function (_ref7) {
          var key = _ref7.key;
          return key !== sortState.key;
        })), [sortState]);
      }
  
      setSortStates(newSorterStates);
      onSorterChange(generateSorterInfo(newSorterStates), newSorterStates);
    }
  
    var transformColumns = function transformColumns(innerColumns) {
      return injectSorter(prefixCls, innerColumns, mergedSorterStates, triggerSorter, sortDirections, tableLocale, showSorterTooltip);
    };
  
    var getSorters = function getSorters() {
      return generateSorterInfo(mergedSorterStates);
    };
  
    return [transformColumns, mergedSorterStates, columnTitleSorterProps, getSorters];
  }