wix-style-react
Version:
858 lines (717 loc) • 40 kB
JavaScript
"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.DataTableHeader = void 0;
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _SortByArrowUp = _interopRequireDefault(require("wix-ui-icons-common/system/SortByArrowUp"));
var _SortByArrowDown = _interopRequireDefault(require("wix-ui-icons-common/system/SortByArrowDown"));
var _wixAnimations = require("wix-animations");
var _classnames = _interopRequireDefault(require("classnames"));
var _defaultTo = _interopRequireDefault(require("lodash/defaultTo"));
var _reactWindow = require("react-window");
var _reactScrollSync = require("react-scroll-sync");
var _TooltipCommon = require("../../common/PropTypes/TooltipCommon");
var _context = require("../../WixStyleReactProvider/context");
var _DataTableSt = require("./DataTable.st.css");
var _InfiniteScroll = _interopRequireDefault(require("../../utils/InfiniteScroll"));
var _InfoIcon = _interopRequireDefault(require("../../InfoIcon"));
var _DataTable = require("./DataTable.utils");
var _excluded = ["children"],
_excluded2 = ["content"];
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; }
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(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var getDefaultRowVerticalPadding = function getDefaultRowVerticalPadding(reducedSpacingAndImprovedLayout) {
return reducedSpacingAndImprovedLayout ? 'small' : 'medium';
};
var DataTableHeader = function DataTableHeader(props) {
var dataHook = props.dataHook,
horizontalScroll = props.horizontalScroll,
leftShadowVisible = props.leftShadowVisible,
rightShadowVisible = props.rightShadowVisible,
stickyColumns = props.stickyColumns,
rowVerticalPadding = props.rowVerticalPadding;
var wrapWithHorizontalScroll = function wrapWithHorizontalScroll(table) {
var _classNames;
return /*#__PURE__*/_react["default"].createElement("div", {
className: (0, _classnames["default"])(_DataTableSt.classes.scrollWrapper, (_classNames = {}, (0, _defineProperty2["default"])(_classNames, _DataTableSt.classes.leftShadowVisible, !!leftShadowVisible), (0, _defineProperty2["default"])(_classNames, _DataTableSt.classes.rightShadowVisible, !!rightShadowVisible), (0, _defineProperty2["default"])(_classNames, _DataTableSt.classes.withStickyColumns, !!stickyColumns), _classNames))
}, /*#__PURE__*/_react["default"].createElement(_reactScrollSync.ScrollSyncPane, null, table));
};
var table = /*#__PURE__*/_react["default"].createElement("div", {
"data-hook": dataHook,
className: (0, _classnames["default"])((0, _defineProperty2["default"])({}, _DataTableSt.classes.tableHeaderScrollContent, horizontalScroll))
}, /*#__PURE__*/_react["default"].createElement(_context.WixStyleReactContext.Consumer, null, function (_ref) {
var reducedSpacingAndImprovedLayout = _ref.reducedSpacingAndImprovedLayout;
return /*#__PURE__*/_react["default"].createElement("table", {
style: {
width: props.width
},
className: (0, _DataTableSt.st)(_DataTableSt.classes.table, {
reducedSpacingAndImprovedLayout: reducedSpacingAndImprovedLayout,
rowVerticalPadding: rowVerticalPadding || getDefaultRowVerticalPadding(reducedSpacingAndImprovedLayout)
})
}, /*#__PURE__*/_react["default"].createElement(TableHeader, (0, _extends2["default"])({
reducedSpacingAndImprovedLayout: reducedSpacingAndImprovedLayout
}, props)));
}));
return horizontalScroll ? wrapWithHorizontalScroll(table) : table;
};
exports.DataTableHeader = DataTableHeader;
DataTableHeader.propTypes = {
width: _propTypes["default"].string
};
var DataTable = /*#__PURE__*/function (_React$Component) {
(0, _inherits2["default"])(DataTable, _React$Component);
var _super = _createSuper(DataTable);
function DataTable(_props) {
var _this;
(0, _classCallCheck2["default"])(this, DataTable);
_this = _super.call(this, _props);
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_updateScrollShadows", function () {
var onUpdateScrollShadows = _this.props.onUpdateScrollShadows;
if (!onUpdateScrollShadows) {
return;
}
var _this$contentRef$curr = _this.contentRef.current,
scrollLeft = _this$contentRef$curr.scrollLeft,
scrollWidth = _this$contentRef$curr.scrollWidth,
clientWidth = _this$contentRef$curr.clientWidth;
var leftShadowVisible = scrollLeft > 0;
var rightShadowVisible = scrollWidth - scrollLeft > clientWidth;
onUpdateScrollShadows(leftShadowVisible, rightShadowVisible);
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "wrapWithInfiniteScroll", function (table) {
return /*#__PURE__*/_react["default"].createElement(_InfiniteScroll["default"], {
ref: _this.props.infiniteScrollRef,
pageStart: 0,
loadMore: _this.loadMore,
data: _this.props.data,
hasMore: _this.state.currentPage < _this.state.lastPage || _this.props.hasMore,
loader: _this.props.loader,
useWindow: _this.props.useWindow,
scrollElement: _this.props.scrollElement,
initialLoad: _this.props.initialLoad
}, table);
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "wrapWithHorizontalScroll", function (table) {
var _classNames3;
var _this$props = _this.props,
leftShadowVisible = _this$props.leftShadowVisible,
rightShadowVisible = _this$props.rightShadowVisible,
stickyColumns = _this$props.stickyColumns;
return /*#__PURE__*/_react["default"].createElement("div", {
className: (0, _classnames["default"])(_this.style.scrollWrapper, (_classNames3 = {}, (0, _defineProperty2["default"])(_classNames3, _this.style.leftShadowVisible, !!leftShadowVisible), (0, _defineProperty2["default"])(_classNames3, _this.style.rightShadowVisible, !!rightShadowVisible), (0, _defineProperty2["default"])(_classNames3, _this.style.withStickyColumns, !!stickyColumns), _classNames3))
}, /*#__PURE__*/_react["default"].createElement(_reactScrollSync.ScrollSyncPane, null, table));
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "renderTable", function (rowsToRender) {
var _this$props2 = _this.props,
dataHook = _this$props2.dataHook,
showLastRowDivider = _this$props2.showLastRowDivider,
horizontalScroll = _this$props2.horizontalScroll,
rowVerticalPadding = _this$props2.rowVerticalPadding,
removeRowDetailsPadding = _this$props2.removeRowDetailsPadding;
var style = {
width: _this.props.width
};
return /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({
"data-hook": dataHook
}, horizontalScroll ? {
className: _DataTableSt.classes.tableBodyScrollContent,
ref: _this.contentRef,
onScroll: _this._updateScrollShadows
} : undefined), /*#__PURE__*/_react["default"].createElement(_context.WixStyleReactContext.Consumer, null, function (_ref2) {
var reducedSpacingAndImprovedLayout = _ref2.reducedSpacingAndImprovedLayout;
return /*#__PURE__*/_react["default"].createElement("table", {
id: _this.props.id,
style: style,
className: (0, _DataTableSt.st)(_DataTableSt.classes.table, {
showLastRowDivider: showLastRowDivider,
reducedSpacingAndImprovedLayout: reducedSpacingAndImprovedLayout,
removeRowDetailsPadding: removeRowDetailsPadding,
rowVerticalPadding: rowVerticalPadding || getDefaultRowVerticalPadding(reducedSpacingAndImprovedLayout)
})
}, !_this.props.hideHeader && /*#__PURE__*/_react["default"].createElement(TableHeader, (0, _extends2["default"])({
reducedSpacingAndImprovedLayout: reducedSpacingAndImprovedLayout
}, _this.props)), _this.renderBody(rowsToRender));
}));
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "renderBody", function (rows) {
return /*#__PURE__*/_react["default"].createElement("tbody", null, rows.map(function (rowData, index) {
return _this.renderRow(rowData, index);
}));
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onRowClick", function (rowData, rowNum) {
var _this$props3 = _this.props,
onRowClick = _this$props3.onRowClick,
rowDetails = _this$props3.rowDetails,
isRowDisabled = _this$props3.isRowDisabled;
onRowClick && !isRowDisabled(rowData) && onRowClick(rowData, rowNum);
rowDetails && rowDetails(rowData, rowNum) && _this.toggleRowDetails(rowData);
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "renderRow", function (rowData, rowNum, style) {
var _this$props4 = _this.props,
onRowClick = _this$props4.onRowClick,
onMouseEnterRow = _this$props4.onMouseEnterRow,
onMouseLeaveRow = _this$props4.onMouseLeaveRow,
rowDataHook = _this$props4.rowDataHook,
dynamicRowClass = _this$props4.dynamicRowClass,
isRowHighlight = _this$props4.isRowHighlight,
rowDetails = _this$props4.rowDetails,
rowClass = _this$props4.rowClass,
columns = _this$props4.columns,
selectedRowsIds = _this$props4.selectedRowsIds,
isRowSelected = _this$props4.isRowSelected,
isRowDisabled = _this$props4.isRowDisabled;
var rowClasses = [rowClass];
var key = (0, _defaultTo["default"])(rowData.id, rowNum);
var optionalRowProps = {};
var handlers = [{
rowEventHandler: _this.onRowClick,
eventHandler: 'onClick'
}, {
rowEventHandler: onMouseEnterRow,
eventHandler: 'onMouseEnter'
}, {
rowEventHandler: onMouseLeaveRow,
eventHandler: 'onMouseLeave'
}];
handlers.forEach(function (_ref3) {
var rowEventHandler = _ref3.rowEventHandler,
eventHandler = _ref3.eventHandler;
if (rowEventHandler) {
optionalRowProps[eventHandler] = function (event) {
if (event.isDefaultPrevented()) {
return;
}
rowEventHandler(rowData, rowNum);
};
}
});
if (onRowClick && !isRowDisabled(rowData)) {
rowClasses.push(_this.style.clickableDataRow);
}
if (rowDetails) {
rowClasses.push(_this.style.animatedDataRow);
}
if (rowDataHook) {
if (typeof rowDataHook === 'string') {
optionalRowProps['data-hook'] = rowDataHook;
} else {
optionalRowProps['data-hook'] = rowDataHook(rowData, rowNum);
}
}
if (dynamicRowClass) {
rowClasses.push(dynamicRowClass(rowData, rowNum));
}
if (isRowHighlight && isRowHighlight(rowData, rowNum)) {
rowClasses.push(_this.style.highlight);
}
if (isRowSelected ? isRowSelected(rowData, rowNum) : selectedRowsIds && selectedRowsIds.includes(key)) {
rowClasses.push(_this.style.selected);
}
optionalRowProps.className = (0, _classnames["default"])(rowClasses);
var rowsToRender = [/*#__PURE__*/_react["default"].createElement(_context.WixStyleReactContext.Consumer, {
key: key
}, function (_ref4) {
var reducedSpacingAndImprovedLayout = _ref4.reducedSpacingAndImprovedLayout;
return /*#__PURE__*/_react["default"].createElement("tr", (0, _extends2["default"])({
"data-table-row": "dataTableRow",
style: style,
key: key
}, optionalRowProps, {
"data-animated": !!rowDetails ? true : null,
"data-clickable": onRowClick && !isRowDisabled(rowData) ? true : null
}), columns.map(function (column, colNum) {
return _this.renderCell(rowData, column, rowNum, colNum, reducedSpacingAndImprovedLayout);
}));
})];
if (rowDetails) {
var showDetails = !!_this.state.selectedRows.get(rowData);
rowsToRender.push( /*#__PURE__*/_react["default"].createElement("tr", {
key: "".concat(key, "_details"),
className: _this.style.rowDetails
}, /*#__PURE__*/_react["default"].createElement("td", {
"data-hook": "".concat(rowNum, "_details"),
className: (0, _classnames["default"])(_this.style.details, showDetails ? _this.style.active : ''),
colSpan: columns.length
}, /*#__PURE__*/_react["default"].createElement("div", {
className: _this.style.rowDetailsInner
}, /*#__PURE__*/_react["default"].createElement(_wixAnimations.Animator, {
show: showDetails,
height: true
}, rowDetails(rowData, rowNum))))));
}
return rowsToRender;
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getCellClasses", function (_ref5) {
var _classNames4;
var column = _ref5.column,
colNum = _ref5.colNum,
rowData = _ref5.rowData;
var _this$props5 = _this.props,
stickyColumns = _this$props5.stickyColumns,
rowDetails = _this$props5.rowDetails;
var selectedRows = _this.state.selectedRows;
return (0, _classnames["default"])((_classNames4 = {}, (0, _defineProperty2["default"])(_classNames4, _this.style.important, column.important), (0, _defineProperty2["default"])(_classNames4, _this.style.alignStart, column.align === 'start'), (0, _defineProperty2["default"])(_classNames4, _this.style.alignCenter, column.align === 'center'), (0, _defineProperty2["default"])(_classNames4, _this.style.alignEnd, column.align === 'end'), (0, _defineProperty2["default"])(_classNames4, _this.style.sticky, colNum < stickyColumns), (0, _defineProperty2["default"])(_classNames4, _this.style.lastSticky, colNum === stickyColumns - 1), (0, _defineProperty2["default"])(_classNames4, _this.style.stickyActionCell, column.stickyActionCell), (0, _defineProperty2["default"])(_classNames4, _this.style.hasRowDetails, rowDetails), (0, _defineProperty2["default"])(_classNames4, _this.style.rowDetailsExtended, !!selectedRows.get(rowData) && rowDetails(rowData)), _classNames4));
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "renderCell", function (rowData, column, rowNum, colNum, reducedSpacingAndImprovedLayout) {
var _this$props6 = _this.props,
virtualized = _this$props6.virtualized,
stickyColumns = _this$props6.stickyColumns,
columns = _this$props6.columns,
hideHeader = _this$props6.hideHeader;
var width = (virtualized || rowNum === 0) && hideHeader ? column.width : undefined;
var style = typeof column.style === 'function' ? column.style(column, rowData, rowNum) : column.style;
var stickyColumnStyle = colNum < stickyColumns ? (0, _DataTable.getStickyColumnStyle)(columns, column, reducedSpacingAndImprovedLayout) : undefined;
var cellClasses = _this.getCellClasses({
column: column,
colNum: colNum,
rowData: rowData
});
return /*#__PURE__*/_react["default"].createElement("td", {
key: colNum,
style: _objectSpread(_objectSpread({}, style), stickyColumnStyle),
width: width,
className: cellClasses,
onClick: column.onCellClick ? function (event) {
return column.onCellClick(column, rowData, rowNum, event);
} : undefined
}, column.render && column.render(rowData, rowNum));
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "calcLastPage", function (_ref6) {
var data = _ref6.data,
itemsPerPage = _ref6.itemsPerPage;
return Math.ceil(data.length / itemsPerPage) - 1;
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "loadMore", function () {
if (_this.state.currentPage < _this.state.lastPage) {
_this.setState({
currentPage: _this.state.currentPage + 1
});
} else {
_this.props.loadMore && _this.props.loadMore();
}
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "toggleRowDetails", function (selectedRow) {
var selectedRows = _this.state.selectedRows;
var allowMultipleRowDetails = _this.props.allowMultiDetailsExpansion && !_this.props.virtualized;
var newSelectedRows = new Map([].concat((0, _toConsumableArray2["default"])(allowMultipleRowDetails ? (0, _toConsumableArray2["default"])(selectedRows) : []), [[selectedRow, !selectedRows.get(selectedRow)]]));
_this.setState({
selectedRows: newSelectedRows
});
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "renderVirtualizedRow", function (_ref7) {
var data = _ref7.data,
index = _ref7.index,
style = _ref7.style;
return _this.renderRow(data.data[index], index, style)[0];
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "renderVirtualizedMemoizedRow", /*#__PURE__*/(0, _react.memo)(_this.renderVirtualizedRow, _DataTable.virtualRowsAreEqual));
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getVirtualRowHeight", function () {
return _this.props.virtualizedLineHeight;
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "virtualizedTableElementWithRefForward", /*#__PURE__*/_react["default"].forwardRef(function (props, ref) {
return _this.renderVirtualizedTableElement(_objectSpread(_objectSpread({}, props), {}, {
ref: ref
}));
}));
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "renderVirtualizedTableElement", function (_ref8) {
var children = _ref8.children,
rest = (0, _objectWithoutProperties2["default"])(_ref8, _excluded);
return /*#__PURE__*/_react["default"].createElement("table", rest, /*#__PURE__*/_react["default"].createElement(TableHeader, _this.props), children);
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "renderVirtualizedTable", function () {
var _this$props7 = _this.props,
dataHook = _this$props7.dataHook,
data = _this$props7.data,
virtualizedTableHeight = _this$props7.virtualizedTableHeight,
virtualizedListRef = _this$props7.virtualizedListRef;
return /*#__PURE__*/_react["default"].createElement("div", {
"data-hook": dataHook
}, /*#__PURE__*/_react["default"].createElement(_reactWindow.VariableSizeList, {
ref: virtualizedListRef,
className: (0, _classnames["default"])(_this.style.table, _this.style.virtualized),
height: virtualizedTableHeight,
itemCount: data.length,
itemData: _this.props,
width: '100%',
itemSize: _this.getVirtualRowHeight,
outerElementType: _this.virtualizedTableElementWithRefForward,
innerElementType: 'tbody'
}, _this.renderVirtualizedMemoizedRow));
});
var state = {
selectedRows: new Map()
};
if (_props.infiniteScroll) {
state = _objectSpread(_objectSpread({}, state), _this.createInitialScrollingState(_props));
}
_this.state = state;
_this.contentRef = /*#__PURE__*/_react["default"].createRef();
if (_props.horizontalScroll && 'ResizeObserver' in window) {
_this.contentResizeObserver = new ResizeObserver(_this._updateScrollShadows);
}
return _this;
}
(0, _createClass2["default"])(DataTable, [{
key: "componentDidMount",
value: function componentDidMount() {
var contentResizeObserver = this.contentResizeObserver,
contentRef = this.contentRef;
if (contentResizeObserver && contentRef.current) {
contentResizeObserver.observe(contentRef.current);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
var contentResizeObserver = this.contentResizeObserver,
contentRef = this.contentRef;
if (contentResizeObserver && contentRef.current) {
contentResizeObserver.unobserve(contentRef.current);
}
}
}, {
key: "style",
get: function get() {
return _DataTableSt.classes;
}
}, {
key: "UNSAFE_componentWillReceiveProps",
value: function UNSAFE_componentWillReceiveProps(nextProps) {
var isLoadingMore = false;
if (this.props.infiniteScroll && nextProps.data !== this.props.data) {
if (nextProps.data instanceof Array && this.props.data instanceof Array) {
isLoadingMore = true;
var lastPage = this.calcLastPage(nextProps);
var currentPage = this.state.currentPage < lastPage ? this.state.currentPage + 1 : this.state.currentPage;
this.setState({
lastPage: lastPage,
currentPage: currentPage
});
}
if (!isLoadingMore) {
this.setState(this.createInitialScrollingState(nextProps));
}
}
}
}, {
key: "createInitialScrollingState",
value: function createInitialScrollingState(props) {
return {
currentPage: 0,
lastPage: this.calcLastPage(props)
};
}
}, {
key: "render",
value: function render() {
var _this$props8 = this.props,
virtualized = _this$props8.virtualized,
data = _this$props8.data,
showHeaderWhenEmpty = _this$props8.showHeaderWhenEmpty,
horizontalScroll = _this$props8.horizontalScroll,
infiniteScroll = _this$props8.infiniteScroll,
itemsPerPage = _this$props8.itemsPerPage;
if (!data.length && !showHeaderWhenEmpty) {
return null;
}
if (virtualized) {
return this.renderVirtualizedTable(data);
}
var rowsToRender = infiniteScroll ? data.slice(0, (this.state.currentPage + 1) * itemsPerPage) : data;
var table = this.renderTable(rowsToRender);
if (horizontalScroll) {
table = this.wrapWithHorizontalScroll(table);
}
if (infiniteScroll) {
table = this.wrapWithInfiniteScroll(table);
}
return table;
}
}]);
return DataTable;
}(_react["default"].Component);
var TableHeader = /*#__PURE__*/function (_Component) {
(0, _inherits2["default"])(TableHeader, _Component);
var _super2 = _createSuper(TableHeader);
function TableHeader() {
var _this2;
(0, _classCallCheck2["default"])(this, TableHeader);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this2 = _super2.call.apply(_super2, [this].concat(args));
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "renderSortingArrow", function (sortDescending, colNum) {
if (sortDescending === undefined) {
return null;
}
var Arrow = sortDescending ? _SortByArrowDown["default"] : _SortByArrowUp["default"];
return /*#__PURE__*/_react["default"].createElement("span", {
"data-hook": "".concat(colNum, "_title"),
className: _this2.style.sortArrow
}, /*#__PURE__*/_react["default"].createElement(Arrow, {
height: 12,
"data-hook": sortDescending ? 'sort_arrow_dec' : 'sort_arrow_asc'
}));
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "renderInfoTooltip", function (tooltipProps, colNum) {
if (tooltipProps === undefined) {
return null;
}
var content = tooltipProps.content,
otherTooltipProps = (0, _objectWithoutProperties2["default"])(tooltipProps, _excluded2);
return /*#__PURE__*/_react["default"].createElement(_InfoIcon["default"], {
content: content,
tooltipProps: otherTooltipProps,
dataHook: "".concat(colNum, "_info_tooltip"),
className: _this2.style.infoTooltipWrapper
});
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "renderHeaderCell", function (column, colNum) {
var _classNames5, _classNames6;
var _this2$props = _this2.props,
stickyColumns = _this2$props.stickyColumns,
columns = _this2$props.columns,
reducedSpacingAndImprovedLayout = _this2$props.reducedSpacingAndImprovedLayout;
var stickyColumnStyle = colNum < stickyColumns ? (0, _DataTable.getStickyColumnStyle)(columns, column, reducedSpacingAndImprovedLayout) : undefined;
var style = _objectSpread({
width: column.width,
padding: _this2.props.thPadding,
height: _this2.props.thHeight,
fontSize: _this2.props.thFontSize,
border: _this2.props.thBorder,
boxShadow: _this2.props.thBoxShadow,
color: _this2.props.thColor,
opacity: _this2.props.thOpacity,
letterSpacing: _this2.props.thLetterSpacing,
cursor: column.sortable === undefined ? 'auto' : 'pointer'
}, stickyColumnStyle);
var optionalHeaderCellProps = {};
if (column.sortable) {
optionalHeaderCellProps.onClick = function () {
return _this2.props.onSortClick && _this2.props.onSortClick(column, colNum);
};
}
return /*#__PURE__*/_react["default"].createElement("th", (0, _extends2["default"])({
style: style,
key: colNum,
className: (0, _classnames["default"])(_this2.style.thText, (_classNames5 = {}, (0, _defineProperty2["default"])(_classNames5, _this2.style.thSkinStandard, !_this2.props.skin || _this2.props.skin === 'standard'), (0, _defineProperty2["default"])(_classNames5, _this2.style.thSkinNeutral, _this2.props.skin === 'neutral'), (0, _defineProperty2["default"])(_classNames5, _this2.style.sticky, colNum < stickyColumns), (0, _defineProperty2["default"])(_classNames5, _this2.style.lastSticky, colNum === stickyColumns - 1), _classNames5))
}, optionalHeaderCellProps), /*#__PURE__*/_react["default"].createElement("div", {
className: (0, _classnames["default"])(_this2.style.thContainer, (_classNames6 = {}, (0, _defineProperty2["default"])(_classNames6, _this2.style.alignStart, !column.align || column.align === 'start'), (0, _defineProperty2["default"])(_classNames6, _this2.style.alignCenter, column.align === 'center'), (0, _defineProperty2["default"])(_classNames6, _this2.style.alignEnd, column.align === 'end'), _classNames6))
}, column.title, _this2.renderSortingArrow(column.sortDescending, colNum), _this2.renderInfoTooltip(column.infoTooltipProps, colNum)));
});
return _this2;
}
(0, _createClass2["default"])(TableHeader, [{
key: "style",
get: function get() {
return _DataTableSt.classes;
}
}, {
key: "render",
value: function render() {
return /*#__PURE__*/_react["default"].createElement("thead", null, /*#__PURE__*/_react["default"].createElement("tr", null, this.props.columns.map(this.renderHeaderCell)));
}
}]);
return TableHeader;
}(_react.Component);
(0, _defineProperty2["default"])(TableHeader, "propTypes", {
onSortClick: _propTypes["default"].func,
thPadding: _propTypes["default"].string,
thHeight: _propTypes["default"].string,
thFontSize: _propTypes["default"].string,
thBorder: _propTypes["default"].string,
thColor: _propTypes["default"].string,
thOpacity: _propTypes["default"].string,
thLetterSpacing: _propTypes["default"].string,
thBoxShadow: _propTypes["default"].string,
columns: _propTypes["default"].array,
skin: _propTypes["default"].oneOf(['standard', 'neutral']),
leftShadowVisible: _propTypes["default"].bool,
rightShadowVisible: _propTypes["default"].bool
});
function validateData(props, propName) {
if (props[propName]) {
if (props[propName].constructor && props[propName].constructor.name && props[propName].constructor.name.toLowerCase().indexOf('array') > -1) {
return null;
} else {
return Error('Data element must be an array type');
}
}
return null;
}
DataTable.defaultProps = {
data: [],
columns: [],
selectedRowsIds: [],
isRowSelected: null,
showHeaderWhenEmpty: false,
infiniteScroll: false,
itemsPerPage: 20,
width: '100%',
loadMore: null,
hasMore: false,
initialLoad: true,
loader: /*#__PURE__*/_react["default"].createElement("div", {
className: "loader"
}, "Loading ..."),
scrollElement: null,
useWindow: true,
showLastRowDivider: true,
virtualizedLineHeight: 60,
skin: 'standard',
horizontalScroll: false,
stickyColumns: 0,
isRowDisabled: function isRowDisabled() {
return false;
},
removeRowDetailsPadding: false
};
DataTable.propTypes = {
dataHook: _propTypes["default"].string,
/** An id to pass to the table */
id: _propTypes["default"].string,
/** The data to display. (If data.id exists then it will be used as the React key value for each row, otherwise, the rowIndex will be used) */
data: validateData,
/** Configuration of the table's columns. See table below */
columns: _propTypes["default"].arrayOf(_propTypes["default"].shape({
title: _propTypes["default"].oneOfType([_propTypes["default"].node, _propTypes["default"].string]).isRequired,
render: _propTypes["default"].func.isRequired,
sortable: _propTypes["default"].bool,
infoTooltipProps: _propTypes["default"].shape(_TooltipCommon.TooltipCommonProps),
sortDescending: _propTypes["default"].bool,
align: _propTypes["default"].oneOf(['start', 'center', 'end']),
important: _propTypes["default"].bool,
style: _propTypes["default"].oneOfType([_propTypes["default"].func, _propTypes["default"].object]),
width: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]),
stickyActionCell: _propTypes["default"].bool
})).isRequired,
/** Should the table show the header when data is empty */
showHeaderWhenEmpty: _propTypes["default"].bool,
/** A string data-hook to apply to all table body rows. or a func which calculates the data-hook for each row - Signature: `(rowData, rowNum) => string` */
rowDataHook: _propTypes["default"].oneOfType([_propTypes["default"].func, _propTypes["default"].string]),
/** A class to apply to all table body rows */
rowClass: _propTypes["default"].string,
/** A func that gets row data and returns a class(es) to apply to that specific row */
dynamicRowClass: _propTypes["default"].func,
/** A func that gets row data and returns boolean if row is selected or not */
isRowSelected: _propTypes["default"].func,
/** A func that gets row data and returns boolean if row is highlighted or not */
isRowHighlight: _propTypes["default"].func,
/** A callback method to be called on row click. Signature: `onRowClick(rowData, rowNum)` */
onRowClick: _propTypes["default"].func,
/** A callback method to be called on row mouse enter. Signature: `onMouseEnterRow(rowData, rowNum)` */
onMouseEnterRow: _propTypes["default"].func,
/** A callback method to be called on row mouse leave. Signature: `onMouseLeaveRow(rowData, rowNum)` */
onMouseLeaveRow: _propTypes["default"].func,
/** If true, table will not render all data to begin with, but will gradually render the data as the user scrolls */
infiniteScroll: _propTypes["default"].bool,
/** If infiniteScroll is on, this prop will determine how many rows will be rendered on each load */
itemsPerPage: _propTypes["default"].number,
/** The width of the fixed table. Can be in percentages or pixels. */
width: _propTypes["default"].string,
/** Table styling. Supports `standard` and `neutral`. */
skin: _propTypes["default"].oneOf(['standard', 'neutral']),
/** A callback when more items are requested by the user. */
loadMore: _propTypes["default"].func,
/** Whether there are more items to be loaded. Event listeners are removed if false. */
hasMore: _propTypes["default"].bool,
/** The loader to show when loading more items. */
loader: _propTypes["default"].node,
/** Add scroll listeners to the window, or else, the component's parentNode. */
useWindow: _propTypes["default"].bool,
/** Add scroll listeners to specified DOM Object. */
scrollElement: _propTypes["default"].object,
/** Indicates whether to invoke `loadMore` on the initial rendering. */
initialLoad: _propTypes["default"].bool,
/** Table cell vertical padding:
* - `large`: 24px
* - `medium`: 18px
* - `small`: with the feature toggle: 15px, without the feature toggle: 12px
* - `tiny`: 12px
* */
rowVerticalPadding: _propTypes["default"].oneOf(['tiny', 'small', 'medium', 'large']),
/** this prop is deprecated and should not be used
* @deprecated
*/
thPadding: _propTypes["default"].string,
/** this prop is deprecated and should not be used
* @deprecated
*/
thHeight: _propTypes["default"].string,
/** this prop is deprecated and should not be used
* @deprecated
*/
thFontSize: _propTypes["default"].string,
/** this prop is deprecated and should not be used
* @deprecated
*/
thBorder: _propTypes["default"].string,
/** this prop is deprecated and should not be used
* @deprecated
*/
thColor: _propTypes["default"].string,
/** this prop is deprecated and should not be used
* @deprecated
*/
thOpacity: _propTypes["default"].string,
/** this prop is deprecated and should not be used
* @deprecated
*/
thBoxShadow: _propTypes["default"].string,
/** this prop is deprecated and should not be used
* @deprecated
*/
thLetterSpacing: _propTypes["default"].string,
/** Function that returns React component that will be rendered in row details section. Example: `rowDetails={(row, rowNum) => <MyRowDetailsComponent {...row} />}` */
rowDetails: _propTypes["default"].func,
/** Removes row details padding */
removeRowDetailsPadding: _propTypes["default"].bool,
/** Allows to open multiple row details */
allowMultiDetailsExpansion: _propTypes["default"].bool,
/** Should we hide the header of the table. */
hideHeader: _propTypes["default"].bool,
/** A flag specifying weather to show a divider after the last row */
showLastRowDivider: _propTypes["default"].bool,
/** ++EXPERIMENTAL++ virtualize the table scrolling for long list items */
virtualized: _propTypes["default"].bool,
/** ++EXPERIMENTAL++ Set virtualized table height */
virtualizedTableHeight: _propTypes["default"].number,
/** ++EXPERIMENTAL++ Set virtualized table row height */
virtualizedLineHeight: _propTypes["default"].number,
/** ++EXPERIMENTAL++ Set ref on virtualized List containing table rows */
virtualizedListRef: _propTypes["default"].any,
/** array of selected ids in the table. Note that `isRowSelected` prop provides greater selection logic flexibility and is recommended to use instead. */
selectedRowsIds: _propTypes["default"].arrayOf(_propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number])),
/** A callback function called on each column title click. Signature `onSortClick(colData, colNum)` */
onSortClick: _propTypes["default"].func,
/** a function which will be called for every row in `data` to specify if it should appear as disabled. Example: `isRowDisabled={(rowData) => !rowData.isEnabled}` */
isRowDisabled: _propTypes["default"].func,
/* Horizontal scroll support props. */
horizontalScroll: _propTypes["default"].bool,
stickyColumns: _propTypes["default"].number,
leftShadowVisible: _propTypes["default"].bool,
rightShadowVisible: _propTypes["default"].bool,
onUpdateScrollShadows: _propTypes["default"].func
};
DataTable.displayName = 'DataTable';
var _default = DataTable;
exports["default"] = _default;