"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SortDirection = exports.DataTable = void 0;
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _Styles = require("./Styles");
var _Table = require("./Table");
var _CollapseAll = _interopRequireDefault(require("../Icons/collection/CollapseAll"));
var _CollapseExpandSingle = _interopRequireDefault(require("../Icons/collection/CollapseExpandSingle"));
var _ExpandAll = _interopRequireDefault(require("../Icons/collection/ExpandAll"));
var _SortIcon = _interopRequireDefault(require("../Icons/collection/SortIcon"));
var _Loaders = require("../Loaders");
var _excluded = ["header", "rows", "className", "sortBy", "sortDirection", "onSortCallback", "theadClass", "noResultsCallback", "groupBy", "groupHead", "isCollapsible", "emptyValue", "loading", "loadingRows"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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 _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 _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(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; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
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(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var SortDirection = exports.SortDirection = /*#__PURE__*/function (SortDirection) {
  SortDirection["None"] = "none";
  SortDirection["Asc"] = "asc";
  SortDirection["Desc"] = "desc";
  return SortDirection;
}({});
var groupByKey = function groupByKey(items, key) {
  if (items[0] instanceof Array) {
    items = items[0];
  }
  return items.reduce(function (result, item) {
    return _objectSpread(_objectSpread({}, result), {}, {
      [item[key] !== null ? " " + item[key] : item[key]]: [...(result[item[key] !== null ? " " + item[key] : item[key]] || []), item]
    });
  }, {});
};
var initialCollapsed = function initialCollapsed(rows, groupBy) {
  if (groupBy) {
    var groupedData = groupByKey(rows, groupBy);
    var keys = Object.keys(groupedData);
    var collapsedKeys = {};
    keys.forEach(function (key) {
      collapsedKeys[key] = true;
    });
    return collapsedKeys;
  }
  return {};
};
var DataTable = exports.DataTable = function DataTable(_ref) {
  var header = _ref.header,
    _ref$rows = _ref.rows,
    rows = _ref$rows === void 0 ? [] : _ref$rows,
    className = _ref.className,
    sortBy = _ref.sortBy,
    _ref$sortDirection = _ref.sortDirection,
    sortDirection = _ref$sortDirection === void 0 ? SortDirection.None : _ref$sortDirection,
    onSortCallback = _ref.onSortCallback,
    theadClass = _ref.theadClass,
    noResultsCallback = _ref.noResultsCallback,
    groupBy = _ref.groupBy,
    _ref$groupHead = _ref.groupHead,
    groupHead = _ref$groupHead === void 0 ? function () {
      return null;
    } : _ref$groupHead,
    isCollapsible = _ref.isCollapsible,
    emptyValue = _ref.emptyValue,
    loading = _ref.loading,
    _ref$loadingRows = _ref.loadingRows,
    loadingRows = _ref$loadingRows === void 0 ? 7 : _ref$loadingRows,
    args = _objectWithoutProperties(_ref, _excluded);
  var _useState = (0, _react.useState)(sortDirection),
    _useState2 = _slicedToArray(_useState, 2),
    columnDirection = _useState2[0],
    setColumnDirection = _useState2[1];
  var _useState3 = (0, _react.useState)(sortBy),
    _useState4 = _slicedToArray(_useState3, 2),
    active = _useState4[0],
    setActive = _useState4[1];
  var _useState5 = (0, _react.useState)(),
    _useState6 = _slicedToArray(_useState5, 2),
    hovered = _useState6[0],
    setHovered = _useState6[1];
  var _useState7 = (0, _react.useState)(function () {
      return initialCollapsed(rows, groupBy);
    }),
    _useState8 = _slicedToArray(_useState7, 2),
    collapsed = _useState8[0],
    setCollapsed = _useState8[1];
  var sort = function sort(sortByKey, direction, rowsData) {
    if (direction === SortDirection.None) {
      return rowsData;
    }
    if (rowsData instanceof Array) return rowsData.sort(function (a, b) {
      if (direction === SortDirection.Asc) {
        if (a[sortByKey] === null) {
          return 1;
        }
        if (b[sortByKey] === null) {
          return -1;
        }
      }
      if (a[sortByKey] === null) {
        return -1;
      }
      if (b[sortByKey] === null) {
        return 1;
      }
      if (typeof a[sortByKey] === "number") {
        if (direction === SortDirection.Asc) {
          return a[sortByKey] - b[sortByKey];
        }
        return b[sortByKey] - a[sortByKey];
      }
      var first = a[sortByKey].toString();
      var second = b[sortByKey].toString();
      if (direction === SortDirection.Asc) {
        return first.localeCompare(second);
      }
      return second.localeCompare(first);
    });
    return {};
  };
  var initialData = (0, _react.useCallback)(function () {
    if (sortBy && !groupBy) {
      return sort(sortBy, sortDirection, rows);
    }
    if (sortBy && groupBy) {
      sort(sortBy, sortDirection, rows);
      return groupByKey(rows, groupBy);
    }
    if (!sortBy && groupBy) {
      return groupByKey(rows, groupBy);
    }
    return rows;
  }, [groupBy, rows, sortBy, sortDirection]);
  var _useState9 = (0, _react.useState)(initialData),
    _useState10 = _slicedToArray(_useState9, 2),
    data = _useState10[0],
    setData = _useState10[1];
  var getNextSortDirection = function getNextSortDirection(previousDirection, sameColumn) {
    if (!sameColumn) {
      return SortDirection.Asc;
    }
    if (previousDirection === SortDirection.Asc) {
      return SortDirection.Desc;
    }
    return SortDirection.Asc;
  };
  var sortColumn = (0, _react.useCallback)(function (event) {
    var index = event.currentTarget.dataset.index;
    if (index && header[index] && header[index].sortable) {
      var direction = getNextSortDirection(columnDirection, header[index].key === active);
      setActive(header[index].key);
      setColumnDirection(direction);
      if (groupBy) {
        var grouped = _objectSpread({}, data);
        if (groupBy !== header[index].key) {
          Object.keys(grouped).map(function (key) {
            grouped[key] = sort(header[index].key, direction, grouped[key]);
          });
        } else {
          if (rows instanceof Object) {
            grouped = sort(header[index].key, direction, rows);
            grouped = groupByKey([grouped], groupBy);
          }
        }
        setData(grouped);
      } else {
        setData(sort(header[index].key, direction, data));
      }
      if (onSortCallback) {
        onSortCallback(header[index].key, direction);
      }
    }
    return null;
  }, [setData, data, columnDirection, setColumnDirection, header, active, setActive, onSortCallback, groupBy, rows]);
  var cellMouseOver = (0, _react.useCallback)(function (e) {
    if (e.target instanceof HTMLElement) {
      if (e.target.dataset.key) {
        setHovered(e.target.dataset.key);
      }
    }
  }, []);
  var cellMouseOut = (0, _react.useCallback)(function () {
    setHovered(null);
  }, []);
  (0, _react.useEffect)(function () {
    setData(initialData());
    setCollapsed(initialCollapsed(rows, groupBy));
  }, [rows, groupBy, initialData]);
  var renderNoResults = (0, _react.useCallback)(function () {
    return /*#__PURE__*/_react.default.createElement("tr", null, /*#__PURE__*/_react.default.createElement("td", {
      colSpan: header.length,
      className: (0, _classnames.default)({
        "text-center": !noResultsCallback
      })
    }, noResultsCallback ? noResultsCallback() : "There is no data."));
  }, [header, noResultsCallback]);
  var tableRef = (0, _react.useRef)(null);
  var overlayStyles = function overlayStyles() {
    if (tableRef.current) {
      return tableRef.current.clientHeight + 5;
    }
  };
  var renderCell = (0, _react.useCallback)(function (h, row, colIndex) {
    if (h.renderCallback) {
      return h.renderCallback(row, h.key, colIndex);
    }
    if (row[h.key] === null && emptyValue) {
      return /*#__PURE__*/_react.default.createElement("i", {
        className: "opacity-75"
      }, emptyValue[h.key]);
    }
    return row[h.key];
  }, [emptyValue]);
  var renderRow = (0, _react.useCallback)(function (row, rowIndex) {
    return /*#__PURE__*/_react.default.createElement("tr", {
      key: rowIndex,
      "data-index": rowIndex,
      "data-direction": "asc",
      className: "c-table__row",
      onMouseOver: cellMouseOver,
      onMouseLeave: cellMouseOut
    }, header.map(function (h, colIndex) {
      return /*#__PURE__*/_react.default.createElement("td", {
        key: colIndex,
        className: (0, _classnames.default)("c-table__cell c-data-table__item", {
          hovered: hovered === h.key
        }),
        "data-key": h.key,
        style: header[colIndex].style ? header[colIndex].style : {}
      }, renderCell(h, row, colIndex));
    }));
  }, [cellMouseOut, cellMouseOver, header, hovered, renderCell]);
  var toggleCollapse = (0, _react.useCallback)(function (event) {
    var collapseKey = event.currentTarget.dataset.groupkey;
    setCollapsed(function (prevState) {
      var newState = _objectSpread({}, prevState);
      newState[collapseKey] = !prevState[collapseKey];
      return newState;
    });
  }, []);
  var renderPlaceholders = (0, _react.useMemo)(function () {
    var placeholders = Array(loadingRows).fill({}).map(function (_, index) {
      return /*#__PURE__*/_react.default.createElement("tr", {
        key: index,
        className: "c-table__row",
        onMouseOver: cellMouseOver,
        onMouseLeave: cellMouseOut
      }, header.map(function (col, colIndex) {
        return /*#__PURE__*/_react.default.createElement("td", {
          key: colIndex,
          className: (0, _classnames.default)("c-table__cell c-data-table__item", {
            hovered: hovered === col.key
          }),
          "data-key": col.key
        }, /*#__PURE__*/_react.default.createElement(_Loaders.SkeletonLoader, null));
      }));
    });
    return /*#__PURE__*/_react.default.createElement(_Table.Tbody, null, placeholders);
  }, [cellMouseOut, cellMouseOver, header, hovered, loadingRows]);
  var renderRows = (0, _react.useMemo)(function () {
    if (data && data instanceof Array && data.length > 0 || typeof data === "object" && Object.keys(data).length > 0) {
      if (groupBy) {
        var keys = Object.keys(data);
        return keys.map(function (key, i) {
          return /*#__PURE__*/_react.default.createElement(_react.Fragment, {
            key: key
          }, isCollapsible && /*#__PURE__*/_react.default.createElement(_Table.Tbody, {
            className: "c-table__collapse_body"
          }, /*#__PURE__*/_react.default.createElement("tr", null, /*#__PURE__*/_react.default.createElement("td", {
            "data-groupkey": key,
            onClick: toggleCollapse,
            className: "c-table__body__icon c-table--toggle-collapsed"
          }, /*#__PURE__*/_react.default.createElement(_CollapseExpandSingle.default, {
            className: (0, _classnames.default)({
              "c-table__collapse_icon--expanded": !collapsed[key],
              "c-table__collapse_icon--collapsed": collapsed[key]
            })
          })))), /*#__PURE__*/_react.default.createElement(_Table.Tbody, {
            className: (0, _classnames.default)("c-table__grouped__head", "head_".concat(i), {
              "c-table__grouped__head--expanded": isCollapsible && !collapsed[key],
              "c-table__grouped__head--collapsed": isCollapsible && collapsed[key],
              last: i === keys.length - 1,
              first: i === 0
            })
          }, groupHead(data[key], keys[i] !== "null" ? keys[i].trim() : null)), /*#__PURE__*/_react.default.createElement(_Table.Tbody, {
            className: (0, _classnames.default)("c-table__group c-table_group_".concat(i), {
              hidden: collapsed[key]
            })
          }, data[key].map(function (row, index) {
            return renderRow(row, index);
          })));
        });
      }
      return /*#__PURE__*/_react.default.createElement(_Table.Tbody, null, data instanceof Array && data.map(function (row, rowIndex) {
        return renderRow(row, rowIndex);
      }));
    }
    return renderNoResults();
  }, [data, groupBy, renderRow, groupHead, collapsed, isCollapsible, renderNoResults, toggleCollapse]);
  var allGroupsCollapsed = (0, _react.useMemo)(function () {
    return Object.keys(collapsed).every(function (key) {
      return collapsed[key];
    });
  }, [collapsed]);
  var hasCollapsed = (0, _react.useMemo)(function () {
    return Object.keys(collapsed).some(function (key) {
      return collapsed[key];
    });
  }, [collapsed]);
  var toggleAllCollapsed = (0, _react.useCallback)(function () {
    if (hasCollapsed) {
      setCollapsed(function (prevState) {
        var newState = _objectSpread({}, prevState);
        Object.keys(newState).forEach(function (key) {
          newState[key] = false;
        });
        return newState;
      });
    } else {
      setCollapsed(function (prevState) {
        var newState = _objectSpread({}, prevState);
        Object.keys(newState).forEach(function (key) {
          newState[key] = true;
        });
        return newState;
      });
    }
  }, [hasCollapsed]);
  return /*#__PURE__*/_react.default.createElement(_Styles.StyledDataTable, _extends({
    as: _Table.Table,
    innerRef: tableRef,
    className: (0, _classnames.default)("c-data-table", className, {
      "c-table__grouped": groupBy,
      "c-table__collapsible": isCollapsible,
      "padding-b-0": groupBy && collapsed[Object.keys(data).slice(-1)[0]]
    })
  }, args), /*#__PURE__*/_react.default.createElement(_Table.Thead, {
    className: theadClass
  }, header.length > 0 && /*#__PURE__*/_react.default.createElement("tr", {
    className: "c-table__row"
  }, header.map(function (h, index) {
    return /*#__PURE__*/_react.default.createElement("th", {
      key: h.key,
      className: (0, _classnames.default)("c-table__cell", {
        "c-table__cell--hovered": hovered === h.key,
        "c-table__head--hidden": groupBy && allGroupsCollapsed && h.hideCollapsed
      }),
      onMouseOver: cellMouseOver,
      onMouseLeave: cellMouseOut,
      "data-key": h.key,
      style: h.style
    }, isCollapsible && groupBy && index === 0 && /*#__PURE__*/_react.default.createElement("span", {
      className: "c-table__head__icon-wrapper",
      onClick: toggleAllCollapsed,
      "data-test": "toggle-collapse"
    }, hasCollapsed ? /*#__PURE__*/_react.default.createElement(_ExpandAll.default, {
      className: "c-table__head__icon-wrapper__icon"
    }) : /*#__PURE__*/_react.default.createElement(_CollapseAll.default, {
      className: "c-table__head__icon-wrapper__icon"
    })), hovered === h.key && /*#__PURE__*/_react.default.createElement("div", {
      className: "c-table__overlay",
      style: {
        height: overlayStyles() + "px"
      }
    }), /*#__PURE__*/_react.default.createElement("div", {
      onClick: sortColumn,
      "data-index": index,
      className: (0, _classnames.default)("c-table__icon-wrapper", {
        "cursor-pointer": h.sortable === true
      })
    }, /*#__PURE__*/_react.default.createElement("span", {
      className: "c-table__label"
    }, h.label), h.sortable && /*#__PURE__*/_react.default.createElement(_SortIcon.default, {
      width: "10px",
      height: "10px",
      className: (0, _classnames.default)("c-table__icon", {
        "c-table__icon--inactive": h.key !== active,
        "c-table__icon--active": h.key === active,
        "c-table__icon--asc": columnDirection === SortDirection.Asc && h.key === active,
        "c-table__icon--desc": columnDirection === SortDirection.Desc && h.key === active
      })
    })));
  }))), loading ? renderPlaceholders : renderRows);
};
DataTable.displayName = "DataTable";
//# sourceMappingURL=DataTable.js.map