choerodon-ui
Version:
An enterprise-class UI design language and React-based implementation
631 lines (509 loc) • 22.9 kB
JavaScript
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard")["default"];
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _react = _interopRequireWildcard(require("react"));
var _mobxReactLite = require("mobx-react-lite");
var _mobx = require("mobx");
var _classnames = _interopRequireDefault(require("classnames"));
var _defer = _interopRequireDefault(require("lodash/defer"));
var _reactIntersectionObserver = require("react-intersection-observer");
var _enum = require("../../../lib/_util/enum");
var _UnitConvertor = require("../../../lib/_util/UnitConvertor");
var _measureScrollbar = _interopRequireDefault(require("../../../lib/_util/measureScrollbar"));
var _TableCell = _interopRequireDefault(require("./TableCell"));
var _TableContext = _interopRequireDefault(require("./TableContext"));
var _ExpandIcon = _interopRequireDefault(require("./ExpandIcon"));
var _enum2 = require("./enum");
var _utils = require("./utils");
var _TableStore = require("./TableStore");
var _enum3 = require("../data-set/enum");
var _ResizeObservedRow = _interopRequireDefault(require("./ResizeObservedRow"));
var _spin = _interopRequireDefault(require("../spin"));
var _useComputed = _interopRequireDefault(require("../use-computed"));
var _iteratorUtils = require("../_util/iteratorUtils");
function getGroupByPath(group, groupPath) {
var subGroups = group.subGroups;
if (groupPath.length) {
var path = groupPath.shift();
if (path && subGroups.length) {
var subGroup = subGroups.find(function (sub) {
return sub.value === path[0].value;
});
if (subGroup) {
return getGroupByPath(subGroup, groupPath);
}
return undefined;
}
}
return group;
}
function getRecord(columnGroup, groupPath, index, record) {
var headerGroup = columnGroup.headerGroup;
if (headerGroup && groupPath) {
var group = getGroupByPath(headerGroup, groupPath.slice());
if (group) {
return group.totalRecords[index];
}
return undefined;
}
return record;
}
var VIRTUAL_HEIGHT = '__VIRTUAL_HEIGHT__';
var TableRow = function TableRow(props) {
var _classNames;
var record = props.record,
hidden = props.hidden,
index = props.index,
virtualIndex = props.virtualIndex,
headerGroupIndex = props.headerGroupIndex,
provided = props.provided,
snapshot = props.snapshot,
className = props.className,
lock = props.lock,
columnGroups = props.columnGroups,
children = props.children,
groupPath = props.groupPath,
expandIconColumnIndex = props.expandIconColumnIndex,
metaData = props.metaData,
propStyle = props.style;
var context = (0, _react.useContext)(_TableContext["default"]);
var tableStore = context.tableStore,
prefixCls = context.prefixCls,
dataSet = context.dataSet,
selectionMode = context.selectionMode,
onRow = context.onRow,
rowRenderer = context.rowRenderer,
parityRow = context.parityRow,
expandIconAsCell = context.expandIconAsCell,
expandedRowRenderer = context.expandedRowRenderer,
isTree = context.isTree,
canTreeLoadData = context.canTreeLoadData;
var highLightRow = tableStore.highLightRow,
selectedHighLightRow = tableStore.selectedHighLightRow,
mouseBatchChooseState = tableStore.mouseBatchChooseState,
dragColumnAlign = tableStore.dragColumnAlign,
rowDraggable = tableStore.rowDraggable,
showRemovedRow = tableStore.showRemovedRow,
node = tableStore.node;
var id = record.id,
rowKey = record.key;
var mounted = (0, _react.useRef)(false);
var dragRef = (0, _react.useRef)(false);
var needIntersection = !hidden && tableStore.virtualCell;
var columnsInView = needIntersection ? tableStore.columnGroups.inView : true;
var _useInView = (0, _reactIntersectionObserver.useInView)({
root: needIntersection && tableStore.overflowY ? node.tableBodyWrap || node.element : null,
rootMargin: "".concat(_TableStore.VIRTUAL_ROOT_MARGIN, "px"),
initialInView: !needIntersection || mounted.current || tableStore.isRowInView(index)
}),
intersectionRef = _useInView.ref,
inView = _useInView.inView,
entry = _useInView.entry;
var disabled = (0, _utils.isDisabledRow)(record);
var rowRef = (0, _react.useRef)(null);
var childrenRenderedRef = (0, _react.useRef)();
var needSaveRowHeight = (0, _utils.isStickySupport)() ? tableStore.propVirtual || needIntersection : !lock && (!tableStore.isFixedRowHeight || (0, _iteratorUtils.iteratorSome)(dataSet.fields.values(), function (field) {
return field.get('multiLine', record);
}));
var rowExternalProps = (0, _useComputed["default"])(function () {
return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, typeof rowRenderer === 'function' ? rowRenderer(record, index) : {}), typeof onRow === 'function' ? onRow({
dataSet: dataSet,
record: record,
expandedRow: false,
index: index
}) : {});
}, [record, dataSet, index, onRow, rowRenderer]);
var isLoading = tableStore.isRowPending(record);
var isLoaded = tableStore.isRowLoaded(record);
var isExpanded = tableStore.isRowExpanded(record);
var isHover = tableStore.isRowHover(record);
var expandable = function () {
var isLeaf = rowExternalProps.isLeaf;
if (isLeaf === true) {
return false;
}
return !!expandedRowRenderer || isTree && (!!record.children || canTreeLoadData && !isLoaded);
}();
var setRowHeight = (0, _react.useCallback)((0, _mobx.action)(function (key, height, target) {
if (inView && columnsInView && height && target.offsetParent) {
if (metaData) {
if (metaData.actualHeight !== height) {
tableStore.batchSetRowHeight(key, function () {
return metaData.setHeight(height);
});
}
} else if (needIntersection) {
if (record.getState(VIRTUAL_HEIGHT) !== height) {
record.setState(VIRTUAL_HEIGHT, height);
}
}
if (!(0, _utils.isStickySupport)()) {
if ((0, _mobx.get)(tableStore.lockColumnsBodyRowsHeight, key) !== height) {
(0, _mobx.set)(tableStore.lockColumnsBodyRowsHeight, key, height);
}
}
}
}), [tableStore, metaData, inView, columnsInView, needIntersection, record]);
var saveRef = (0, _react.useCallback)((0, _mobx.action)(function (row) {
rowRef.current = row;
if (needSaveRowHeight) {
if (row) {
setRowHeight(rowKey, row.offsetHeight, row);
} else if (!(0, _utils.isStickySupport)() && (0, _mobx.get)(tableStore.lockColumnsBodyRowsHeight, rowKey)) {
(0, _mobx.remove)(tableStore.lockColumnsBodyRowsHeight, rowKey);
}
}
if (provided) {
provided.innerRef(row);
}
if (needIntersection && typeof intersectionRef === 'function') {
intersectionRef(row);
}
}), [rowRef, intersectionRef, needIntersection, needSaveRowHeight, rowKey, provided, setRowHeight]);
var handleMouseEnter = (0, _react.useCallback)(function () {
if (highLightRow) {
tableStore.setRowHover(record, true);
}
}, [highLightRow, tableStore, record]);
var handleMouseLeave = (0, _react.useCallback)(function () {
if (highLightRow) {
tableStore.setRowHover(record, false);
}
}, [highLightRow, tableStore, record]);
var handleSelection = (0, _react.useCallback)(function () {
dataSet[record.isSelected ? 'unSelect' : 'select'](record);
}, [record, dataSet]);
var handleClickCapture = (0, _react.useCallback)((0, _mobx.action)(function (e) {
if (!(0, _utils.isDisabledRow)(record) && e.target.dataset.selectionKey !== _TableStore.SELECTION_KEY) {
dataSet.current = record;
}
var onClickCapture = rowExternalProps.onClickCapture;
if (typeof onClickCapture === 'function') {
onClickCapture(e);
}
}), [record, dataSet, rowExternalProps]);
var handleClick = (0, _react.useCallback)((0, _mobx.action)(function (e) {
var onClick = rowExternalProps.onClick;
if (highLightRow === _enum2.HighLightRowType.click && !tableStore.rowClicked) {
tableStore.rowClicked = true;
}
if (typeof onClick === 'function') {
return onClick(e);
}
}), [tableStore, rowExternalProps]);
var handleSelectionByClick = (0, _react.useCallback)( /*#__PURE__*/function () {
var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(e) {
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return handleClick(e);
case 2:
_context.t0 = _context.sent;
if (!(_context.t0 !== false)) {
_context.next = 5;
break;
}
handleSelection();
case 5:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function (_x) {
return _ref.apply(this, arguments);
};
}(), [handleClick, handleSelection]);
var handleSelectionByMouseDown = (0, _react.useCallback)(function (e) {
handleSelection();
var onMouseDown = rowExternalProps.onMouseDown;
if (typeof onMouseDown === 'function') {
onMouseDown(e);
}
}, [handleSelection, rowExternalProps]);
var handleSelectionByDblClick = (0, _react.useCallback)(function (e) {
handleSelection();
var onDoubleClick = rowExternalProps.onDoubleClick;
if (typeof onDoubleClick === 'function') {
onDoubleClick(e);
}
}, [handleSelection, rowExternalProps]);
var handleExpandChange = (0, _react.useCallback)(function () {
if (expandable) {
tableStore.setRowExpanded(record, !isExpanded);
}
}, [tableStore, record, expandable, isExpanded]);
var focusRow = (0, _react.useCallback)(function () {
var current = rowRef.current;
if (current) {
if (!lock && !tableStore.editing) {
var element = node.element;
var _document = document,
activeElement = _document.activeElement;
if (element && element.contains(activeElement) && ((0, _utils.isStickySupport)() ? !current.contains(activeElement) : Array.from(element.querySelectorAll("tr[data-index=\"".concat(record.id, "\"]"))).every(function (tr) {
return !tr.contains(activeElement);
}))) {
current.focus();
} // table 包含目前被focus的element
// 找到当前组件对应record生成的组件对象 然后遍历 每个 tr里面不是focus的目标那么这个函数触发row.focus
}
if (tableStore.overflowY) {
var offsetParent = current.offsetParent;
if (offsetParent) {
var tableBodyWrap = offsetParent.parentNode;
if (tableBodyWrap) {
var offsetTop = current.offsetTop,
offsetHeight = current.offsetHeight;
var scrollTop = tableBodyWrap.scrollTop,
_height = tableBodyWrap.offsetHeight;
var bottomSide = offsetTop + offsetHeight - _height + (0, _measureScrollbar["default"])();
var st = scrollTop;
if (st < bottomSide) {
st = bottomSide;
}
if (st > offsetTop) {
st = offsetTop + 1;
}
if (st !== scrollTop) {
tableBodyWrap.scrollTop = st; // node.handleBodyScrollTop({
// target: tableBodyWrap,
// currentTarget: tableBodyWrap,
// });
}
}
}
}
}
}, [rowRef, tableStore, lock, node]); // componentDidMount
(0, _react.useEffect)(function () {
mounted.current = true;
if (record.status === _enum3.RecordStatus.add && tableStore.autoFocus) {
var editor = tableStore.editors.values().next().value;
if (editor && ((0, _utils.isStickySupport)() || (0, _utils.getColumnLock)(editor.props.column.lock) === (0, _utils.getColumnLock)(lock))) {
var cell = (0, _utils.findCell)(tableStore, (0, _utils.getColumnKey)(editor.props.column), lock);
if (cell) {
(0, _defer["default"])(function () {
return cell.focus();
});
}
}
} // componentWillUnmount
return (0, _mobx.action)(function () {
mounted.current = false;
/**
* Fixed the when row resize has scrollbar the expanded row would be collapsed
*/
if (!tableStore.isRowExpanded(record)) {
tableStore.setRowExpanded(record, false, true);
}
if (!(0, _utils.isStickySupport)()) {
(0, _mobx.remove)(tableStore.lockColumnsBodyRowsHeight, rowKey);
}
});
}, []);
(0, _react.useEffect)(function () {
if (!isLoading && expandable && isExpanded && !isLoaded && tableStore.canTreeLoadData && !record.children) {
tableStore.onTreeNodeLoad({
record: record
});
}
}, [isLoading, expandable, isExpanded, isLoaded, tableStore, record]);
(0, _react.useEffect)(function () {
return (0, _mobx.reaction)(function () {
return record.isCurrent;
}, function (isCurrent) {
return isCurrent && focusRow();
});
}, [record, focusRow]);
var renderExpandRow = function renderExpandRow() {
if (expandable && (isExpanded || childrenRenderedRef.current)) {
var expandRows = [];
childrenRenderedRef.current = true;
if (expandedRowRenderer) {
var expandRowExternalProps = typeof onRow === 'function' ? onRow({
dataSet: dataSet,
record: record,
expandedRow: true,
index: index
}) : {};
var _classString = (0, _classnames["default"])("".concat(prefixCls, "-expanded-row"), expandRowExternalProps.className);
var _rowProps = {
key: "".concat(rowKey, "-expanded-row"),
className: _classString,
style: (0, _objectSpread2["default"])({}, expandRowExternalProps.style)
};
if (!(0, _utils.isStickySupport)() && (tableStore.overflowX || !record.isCurrent)) {
_rowProps.onMouseEnter = handleMouseEnter;
_rowProps.onMouseLeave = handleMouseLeave;
}
if (!isExpanded) {
_rowProps.hidden = true;
}
var _Element = isExpanded || !parityRow ? 'tr' : 'div';
expandRows.push( /*#__PURE__*/_react["default"].createElement(_Element, (0, _extends2["default"])({}, expandRowExternalProps, _rowProps), expandIconAsCell && /*#__PURE__*/_react["default"].createElement("td", {
className: "".concat(prefixCls, "-cell"),
key: _TableStore.EXPAND_KEY
}), /*#__PURE__*/_react["default"].createElement("td", {
key: "".concat(_TableStore.EXPAND_KEY, "-rest"),
className: "".concat(prefixCls, "-cell"),
colSpan: columnGroups.leafs.length - (expandIconAsCell ? 1 : 0)
}, /*#__PURE__*/_react["default"].createElement("div", {
className: "".concat(prefixCls, "-cell-inner")
}, expandedRowRenderer({
dataSet: dataSet,
record: record
})))));
}
if ( /*#__PURE__*/(0, _react.isValidElement)(children)) {
expandRows.push( /*#__PURE__*/(0, _react.cloneElement)(children, {
parentExpanded: isExpanded,
key: "".concat(rowKey, "-expanded-rows")
}));
}
return expandRows;
}
return [];
};
var renderExpandIcon = function renderExpandIcon() {
var expandIcon = tableStore.expandIcon;
if (typeof expandIcon === 'function') {
return expandIcon({
prefixCls: prefixCls,
expanded: isExpanded,
expandable: expandable,
needIndentSpaced: !expandable,
record: record,
onExpand: handleExpandChange
});
}
if (tableStore.isRowPending(record)) {
return /*#__PURE__*/_react["default"].createElement(_spin["default"], {
size: _enum.Size.small
});
}
return /*#__PURE__*/_react["default"].createElement(_ExpandIcon["default"], {
prefixCls: prefixCls,
expandable: expandable,
onChange: handleExpandChange,
expanded: isExpanded
});
};
var hasExpandIcon = function hasExpandIcon(columnIndex) {
return expandIconColumnIndex !== undefined && expandIconColumnIndex > -1 && columnIndex + expandIconColumnIndex === tableStore.expandIconColumnIndex;
};
var getCell = function getCell(columnGroup, columnIndex, rest) {
return /*#__PURE__*/_react["default"].createElement(_TableCell["default"], (0, _extends2["default"])({
columnGroup: columnGroup,
record: headerGroupIndex === undefined ? record : getRecord(columnGroup, groupPath, headerGroupIndex, record),
isDragging: snapshot ? snapshot.isDragging : false,
provided: rest.key === _TableStore.DRAG_KEY ? provided : undefined,
inView: needIntersection ? inView : undefined,
groupPath: groupPath,
rowIndex: virtualIndex === undefined ? index : virtualIndex
}, rest), hasExpandIcon(columnIndex) ? renderExpandIcon() : undefined);
};
var getColumns = function getColumns() {
var customizable = tableStore.customizable;
var leafs = columnGroups.leafs;
var columnLength = leafs.length;
return leafs.map(function (columnGroup, columnIndex) {
var key = columnGroup.key;
if (key !== _TableStore.CUSTOMIZED_KEY) {
var colSpan = customizable && lock !== _enum2.ColumnLock.left && (!rowDraggable || dragColumnAlign !== _enum2.DragColumnAlign.right) && columnIndex === columnLength - 2 ? 2 : 1;
var rest = {
key: key,
disabled: disabled
};
if (colSpan > 1) {
rest.colSpan = colSpan;
}
return getCell(columnGroup, columnIndex, rest);
}
return undefined;
});
};
var rowPrefixCls = "".concat(prefixCls, "-row");
var classString = (0, _classnames["default"])(rowPrefixCls, (_classNames = {}, (0, _defineProperty2["default"])(_classNames, "".concat(rowPrefixCls, "-current"), highLightRow && record.isCurrent && (highLightRow === _enum2.HighLightRowType.click ? tableStore.rowClicked : highLightRow === _enum2.HighLightRowType.focus ? node.isFocused : highLightRow)), (0, _defineProperty2["default"])(_classNames, "".concat(rowPrefixCls, "-hover"), !(0, _utils.isStickySupport)() && highLightRow && isHover), (0, _defineProperty2["default"])(_classNames, "".concat(rowPrefixCls, "-selected"), selectedHighLightRow && (0, _utils.isSelectedRow)(record)), (0, _defineProperty2["default"])(_classNames, "".concat(rowPrefixCls, "-disabled"), disabled), (0, _defineProperty2["default"])(_classNames, "".concat(rowPrefixCls, "-mouse-batch-choose"), mouseBatchChooseState && record.selectable && (tableStore.mouseBatchChooseIdList || []).includes(id)), (0, _defineProperty2["default"])(_classNames, "".concat(rowPrefixCls, "-expanded"), expandable && isExpanded), (0, _defineProperty2["default"])(_classNames, "".concat(rowPrefixCls, "-has-next"), metaData && metaData.next), _classNames), className, // 增加可以自定义类名满足拖拽功能
rowExternalProps.className);
var style = rowExternalProps.style;
var rowProps = {
ref: saveRef,
className: classString,
onClick: handleClick,
onClickCapture: handleClickCapture,
tabIndex: -1,
disabled: disabled,
'data-index': id
};
if (!(0, _utils.isStickySupport)() && tableStore.overflowX) {
rowProps.onMouseEnter = handleMouseEnter;
rowProps.onMouseLeave = handleMouseLeave;
}
if (hidden || !showRemovedRow && record.status === _enum3.RecordStatus["delete"]) {
rowProps.hidden = true;
}
var Element = hidden && parityRow ? 'div' : 'tr';
if (selectionMode === _enum2.SelectionMode.click) {
rowProps.onClick = handleSelectionByClick;
} else if (selectionMode === _enum2.SelectionMode.dblclick) {
rowProps.onDoubleClick = handleSelectionByDblClick;
} else if (selectionMode === _enum2.SelectionMode.mousedown) {
rowProps.onMouseDown = handleSelectionByMouseDown;
}
var rowStyle = (0, _objectSpread2["default"])({}, style);
if (rowDraggable && provided) {
(0, _extends2["default"])(rowProps, provided.draggableProps);
(0, _extends2["default"])(rowStyle, provided.draggableProps.style, style);
if (propStyle) {
var transform = propStyle.transform;
if (transform) {
if (rowStyle.transform) {
rowStyle.transform = 'none';
} else {
rowStyle.transform = transform;
if (!dragRef.current) {
rowStyle.transition = 'none';
dragRef.current = true;
}
}
}
} else {
dragRef.current = false;
}
rowStyle.width = Math.max(tableStore.columnGroups.width, tableStore.width || 0);
if (!dragColumnAlign) {
rowStyle.cursor = 'move';
(0, _extends2["default"])(rowProps, provided.dragHandleProps);
}
}
var height = needIntersection && (!inView || !columnsInView) ? entry && entry.target.offsetParent ? (0, _UnitConvertor.pxToRem)(entry.boundingClientRect.height || entry.target.offsetHeight, true) : (0, _UnitConvertor.pxToRem)(metaData ? metaData.height : record.getState(VIRTUAL_HEIGHT) || tableStore.virtualRowHeight, true) : lock ? (0, _UnitConvertor.pxToRem)((0, _mobx.get)(tableStore.lockColumnsBodyRowsHeight, rowKey), true) : undefined;
if (height) {
rowStyle.height = height;
}
var tr = /*#__PURE__*/_react["default"].createElement(Element, (0, _extends2["default"])({
key: rowKey
}, rowExternalProps, rowProps, {
style: rowStyle
}), getColumns());
return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, needSaveRowHeight ? /*#__PURE__*/_react["default"].createElement(_ResizeObservedRow["default"], {
onResize: setRowHeight,
rowIndex: rowKey,
key: rowKey
}, tr) : tr, renderExpandRow());
};
TableRow.displayName = 'TableRow';
var _default = (0, _mobxReactLite.observer)(TableRow);
exports["default"] = _default;
//# sourceMappingURL=TableRow.js.map