"use strict";

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

var _typeof = require("@babel/runtime/helpers/typeof");

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

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

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

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

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

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

var _lodash = _interopRequireDefault(require("lodash.omit"));

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

var _reactResizeDetector = _interopRequireDefault(require("react-resize-detector"));

var _box = _interopRequireDefault(require("../box"));

var _loadingBar = _interopRequireDefault(require("../loadingBar"));

var _isComponentOfType = _interopRequireDefault(require("../utils/is-component-of-type"));

var _isReactElement = _interopRequireDefault(require("../utils/is-react-element"));

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

var _BodyRow = _interopRequireDefault(require("./BodyRow"));

var _Cell = _interopRequireDefault(require("./Cell"));

var _FooterRow = _interopRequireDefault(require("./FooterRow"));

var _HeaderCell = _interopRequireDefault(require("./HeaderCell"));

var _HeaderRow = _interopRequireDefault(require("./HeaderRow"));

var _HeaderRowOverlay = _interopRequireDefault(require("./HeaderRowOverlay/HeaderRowOverlay"));

var _theme = _interopRequireDefault(require("./theme.css"));

var _excluded = ["bordered", "children", "className", "processing", "comparableId", "selectable", "stickyFromLeft", "stickyFromRight", "onSelectionChange"];

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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; }

var DataGrid = function DataGrid(_ref) {
  var _childrenArray$find, _cx, _cx2;

  var _ref$bordered = _ref.bordered,
      bordered = _ref$bordered === void 0 ? false : _ref$bordered,
      children = _ref.children,
      className = _ref.className,
      _ref$processing = _ref.processing,
      processing = _ref$processing === void 0 ? false : _ref$processing,
      comparableId = _ref.comparableId,
      selectable = _ref.selectable,
      _ref$stickyFromLeft = _ref.stickyFromLeft,
      stickyFromLeft = _ref$stickyFromLeft === void 0 ? 0 : _ref$stickyFromLeft,
      _ref$stickyFromRight = _ref.stickyFromRight,
      stickyFromRight = _ref$stickyFromRight === void 0 ? 0 : _ref$stickyFromRight,
      onSelectionChange = _ref.onSelectionChange,
      others = (0, _objectWithoutProperties2.default)(_ref, _excluded);

  var _useState = (0, _react.useState)(null),
      _useState2 = (0, _slicedToArray2.default)(_useState, 2),
      hoveredRow = _useState2[0],
      setHoveredRow = _useState2[1];

  var _useState3 = (0, _react.useState)(false),
      _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
      isOverflowing = _useState4[0],
      setOverflowing = _useState4[1];

  var _useState5 = (0, _react.useState)([]),
      _useState6 = (0, _slicedToArray2.default)(_useState5, 2),
      selectedRows = _useState6[0],
      setSelectedRows = _useState6[1];

  var scrollableNode = (0, _react.useRef)(null);

  var _useState7 = (0, _react.useState)(new Map()),
      _useState8 = (0, _slicedToArray2.default)(_useState7, 2),
      rowNodes = _useState8[0],
      setRowNodes = _useState8[1];

  var totalRowChildrenWidth = (0, _react.useMemo)(function () {
    return Array.from(rowNodes.values()).filter(function (rowDOMNode) {
      return rowDOMNode.children;
    }).map(function (rowDOMNode) {
      return Array.from(rowDOMNode.children).map(function (child) {
        return child.clientWidth;
      }).reduce(function (accumulatedChildWidth, currentChildWidth) {
        return accumulatedChildWidth + currentChildWidth;
      }, 0);
    }).reduce(function (maxRowWidth, currentRowWidth) {
      return currentRowWidth > maxRowWidth ? currentRowWidth : maxRowWidth;
    }, 0);
  }, [rowNodes, rowNodes.size]);
  var childrenArray = !Array.isArray(children) ? [children] : children;
  var bodyRowCount = (_childrenArray$find = childrenArray.find(function (child) {
    return Array.isArray(child);
  })) === null || _childrenArray$find === void 0 ? void 0 : _childrenArray$find.length;

  var handleSelectionChange = function handleSelectionChange(selection) {
    var event = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;

    if (onSelectionChange) {
      onSelectionChange(selection, event);
    }
  };

  var handleHeaderRowSelectionChange = function handleHeaderRowSelectionChange(checked, event) {
    var allBodyRowIndexes = _react.default.Children.map(children, function (child) {
      if ((0, _isReactElement.default)(child) && (0, _isComponentOfType.default)(_BodyRow.default, child)) {
        return child.key;
      }
    });

    var selectedBodyRowIndexes = checked ? allBodyRowIndexes !== null && allBodyRowIndexes !== void 0 ? allBodyRowIndexes : [] : [];
    setSelectedRows(selectedBodyRowIndexes);
    handleSelectionChange(selectedBodyRowIndexes, event);
  };

  var handleBodyRowMouseEnter = function handleBodyRowMouseEnter(row, event) {
    var _row$props = row.props,
        onClick = _row$props.onClick,
        onMouseOver = _row$props.onMouseOver;
    onClick && setHoveredRow(row.key);
    onMouseOver && onMouseOver(event);
  };

  var handleBodyRowMouseLeave = function handleBodyRowMouseLeave(row, event) {
    var _row$props2 = row.props,
        onClick = _row$props2.onClick,
        onMouseOut = _row$props2.onMouseOut;
    onClick && setHoveredRow(null);
    onMouseOut && onMouseOut(event);
  };

  var handleBodyRowSelectionChange = function handleBodyRowSelectionChange(rowIndex, event) {
    if (rowIndex === null) {
      return;
    }

    var rows = selectedRows.includes(rowIndex) ? selectedRows.filter(function (row) {
      return row !== rowIndex;
    }) : [].concat((0, _toConsumableArray2.default)(selectedRows), [rowIndex]);
    setSelectedRows(rows);
    handleSelectionChange(rows, event);
  };

  var handleResize = function handleResize() {
    if ((0, _utils.isElementOverflowingX)(scrollableNode.current)) {
      setOverflowing(true);
    } else {
      setOverflowing(false);
    }
  };

  (0, _react.useEffect)(function () {
    handleResize();
  });
  (0, _react.useEffect)(function () {
    setSelectedRows([]);
    handleSelectionChange([]);
  }, [comparableId]);
  var classNames = (0, _classnames.default)(_theme.default['data-grid'], (_cx = {}, (0, _defineProperty2.default)(_cx, _theme.default['is-bordered'], bordered), (0, _defineProperty2.default)(_cx, _theme.default['is-overflowing'], isOverflowing), _cx), className);
  var rest = (0, _lodash.default)(others, ['comparableId', 'onSelectionChange']);
  var sectionLeftClassNames = (0, _classnames.default)(_theme.default['section'], _theme.default['is-sticky-left'], (_cx2 = {}, (0, _defineProperty2.default)(_cx2, _theme.default['has-blend-right'], selectable || stickyFromLeft > 0), (0, _defineProperty2.default)(_cx2, _theme.default['has-border-right'], selectable || stickyFromLeft > 0), _cx2));
  return /*#__PURE__*/_react.default.createElement(_box.default, (0, _extends2.default)({
    "data-teamleader-ui": "data-grid",
    className: classNames
  }, rest), processing && /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _classnames.default)(_theme.default['loading-bar'])
  }, /*#__PURE__*/_react.default.createElement(_loadingBar.default, null)), selectedRows.length > 0 && _react.default.Children.map(children, function (child) {
    if ((0, _isReactElement.default)(child) && (0, _isComponentOfType.default)(_HeaderRowOverlay.default, child)) {
      return /*#__PURE__*/_react.default.cloneElement(child, {
        numSelectedRows: selectedRows.length
      });
    }
  }), /*#__PURE__*/_react.default.createElement(_box.default, {
    display: "flex",
    className: (0, _classnames.default)(_theme.default['section-wrapper'])
  }, (selectable || stickyFromLeft > 0) && /*#__PURE__*/_react.default.createElement("div", {
    className: sectionLeftClassNames
  }, _react.default.Children.map(children, function (child) {
    if ((0, _isReactElement.default)(child)) {
      if ((0, _isComponentOfType.default)(_HeaderRow.default, child)) {
        return /*#__PURE__*/_react.default.cloneElement(child, {
          onSelectionChange: handleHeaderRowSelectionChange,
          selected: selectedRows.length === bodyRowCount,
          selectable: selectable,
          sliceTo: stickyFromLeft > 0 ? stickyFromLeft : 0
        });
      } else if ((0, _isComponentOfType.default)(_BodyRow.default, child)) {
        return /*#__PURE__*/_react.default.cloneElement(child, {
          hovered: hoveredRow === child.key,
          onMouseEnter: function onMouseEnter(event) {
            return handleBodyRowMouseEnter(child, event);
          },
          onMouseLeave: function onMouseLeave(event) {
            return handleBodyRowMouseLeave(child, event);
          },
          onSelectionChange: function onSelectionChange(checked, event) {
            return handleBodyRowSelectionChange(child.key, event);
          },
          selected: child.key && selectedRows.indexOf(child.key) !== -1,
          selectable: selectable,
          sliceTo: stickyFromLeft > 0 ? stickyFromLeft : 0
        });
      } else if ((0, _isComponentOfType.default)(_FooterRow.default, child)) {
        return /*#__PURE__*/_react.default.cloneElement(child, {
          preserveSelectableSpace: selectable,
          sliceTo: stickyFromLeft > 0 ? stickyFromLeft : 0
        });
      }
    }
  })), /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _classnames.default)(_theme.default['section'], _theme.default['is-scrollable']),
    ref: scrollableNode
  }, _react.default.Children.map(children, function (child, key) {
    if ((0, _isReactElement.default)(child)) {
      if ((0, _isComponentOfType.default)(_HeaderRow.default, child) || (0, _isComponentOfType.default)(_FooterRow.default, child)) {
        return /*#__PURE__*/_react.default.cloneElement(child, {
          sliceFrom: stickyFromLeft > 0 ? stickyFromLeft : 0,
          sliceTo: stickyFromRight > 0 ? -stickyFromRight : undefined,
          ref: function ref(rowNode) {
            return setRowNodes(rowNodes.set(key, rowNode));
          },
          style: isOverflowing ? {
            minWidth: "".concat(totalRowChildrenWidth - 10, "px")
          } : undefined
        });
      } else if ((0, _isComponentOfType.default)(_BodyRow.default, child)) {
        return /*#__PURE__*/_react.default.cloneElement(child, {
          hovered: hoveredRow === child.key,
          onMouseEnter: function onMouseEnter(event) {
            return handleBodyRowMouseEnter(child, event);
          },
          onMouseLeave: function onMouseLeave(event) {
            return handleBodyRowMouseLeave(child, event);
          },
          sliceFrom: stickyFromLeft > 0 ? stickyFromLeft : 0,
          sliceTo: stickyFromRight > 0 ? -stickyFromRight : undefined,
          ref: function ref(rowNode) {
            return setRowNodes(rowNodes.set(key, rowNode));
          },
          style: isOverflowing ? {
            minWidth: "".concat(totalRowChildrenWidth - 10, "px")
          } : undefined
        });
      }
    }
  })), stickyFromRight > 0 && /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _classnames.default)(_theme.default['section'], _theme.default['has-blend-left'])
  }, _react.default.Children.map(children, function (child) {
    if ((0, _isReactElement.default)(child)) {
      if ((0, _isComponentOfType.default)(_HeaderRow.default, child) || (0, _isComponentOfType.default)(_FooterRow.default, child)) {
        return /*#__PURE__*/_react.default.cloneElement(child, {
          sliceFrom: -stickyFromRight
        });
      } else if ((0, _isComponentOfType.default)(_BodyRow.default, child)) {
        return /*#__PURE__*/_react.default.cloneElement(child, {
          hovered: hoveredRow === child.key,
          onMouseEnter: function onMouseEnter(event) {
            return handleBodyRowMouseEnter(child, event);
          },
          onMouseLeave: function onMouseLeave(event) {
            return handleBodyRowMouseLeave(child, event);
          },
          sliceFrom: -stickyFromRight
        });
      }
    }
  }))), /*#__PURE__*/_react.default.createElement(_reactResizeDetector.default, {
    handleWidth: true,
    onResize: handleResize,
    refreshMode: "throttle",
    refreshRate: 16
  }));
};

exports.DataGrid = DataGrid;
DataGrid.HeaderRow = _HeaderRow.default;
DataGrid.HeaderRowOverlay = _HeaderRowOverlay.default;
DataGrid.HeaderCell = _HeaderCell.default;
DataGrid.BodyRow = _BodyRow.default;
DataGrid.Cell = _Cell.default;
DataGrid.FooterRow = _FooterRow.default;
DataGrid.displayName = 'DataGrid';
var _default = DataGrid;
exports.default = _default;