UNPKG

choerodon-ui

Version:

An enterprise-class UI design language and React-based implementation

698 lines (566 loc) 25.7 kB
"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 _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); 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 _enum = require("../../../lib/_util/enum"); var _UnitConvertor = require("../../../lib/_util/UnitConvertor"); var _measureScrollbar = _interopRequireDefault(require("../../../lib/_util/measureScrollbar")); var _TableCell = _interopRequireDefault(require("./TableCell")); var _TableVirtualCell = _interopRequireDefault(require("./TableVirtualCell")); 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) { if (index !== undefined && groupPath) { var headerGroup = columnGroup.headerGroup; if (headerGroup) { 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, isDragDisabled = props.isDragDisabled, className = props.className, lock = props.lock, columnGroups = props.columnGroups, children = props.children, groupPath = props.groupPath, expandIconColumnIndex = props.expandIconColumnIndex, metaData = props.metaData, propStyle = props.style, intersectionRef = props.intersectionRef, _props$inView = props.inView, inView = _props$inView === void 0 ? true : _props$inView, virtualHeight = props.virtualHeight, isFixedRowHeight = props.isFixedRowHeight, _props$columnsInView = props.columnsInView, columnsInView = _props$columnsInView === void 0 ? true : _props$columnsInView; 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, fullColumnWidth = context.fullColumnWidth, expandRowByClick = context.expandRowByClick; var highLightRow = tableStore.highLightRow, selectedHighLightRow = tableStore.selectedHighLightRow, mouseBatchChooseState = tableStore.mouseBatchChooseState, dragColumnAlign = tableStore.dragColumnAlign, rowDraggable = tableStore.rowDraggable, showRemovedRow = tableStore.showRemovedRow, node = tableStore.node, propVirtual = tableStore.propVirtual, isRenderRange = tableStore.isRenderRange, blankVirtualCell = tableStore.blankVirtualCell, _tableStore$virtualCo = tableStore.virtualColumnRange, left = _tableStore$virtualCo.left, center = _tableStore$virtualCo.center, right = _tableStore$virtualCo.right; var id = record.id, rowKey = record.key; var mounted = (0, _react.useRef)(false); var dragRef = (0, _react.useRef)(false); var needIntersection = intersectionRef; var disabled = (0, _utils.isDisabledRow)(record); var rowRef = (0, _react.useRef)(null); var childrenRenderedRef = (0, _react.useRef)(); var needSaveRowHeight = (0, _utils.isStickySupport)() ? !isFixedRowHeight || propVirtual || needIntersection : !lock && (!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) { // TODO: TABLE 行内编辑并且拖拽操作兼容火狐浏览器的适配 if (inView && columnsInView && height && target.offsetParent && navigator.userAgent.indexOf("Firefox") < 0) { 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.alignEditor(); } }), [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 handleExpandChange = (0, _react.useCallback)(function () { if (expandable) { tableStore.setRowExpanded(record, !isExpanded); } }, [tableStore, record, expandable, isExpanded]); var handleClick = (0, _react.useCallback)((0, _mobx.action)(function (e) { if (expandRowByClick) { handleExpandChange(); } var onClick = rowExternalProps.onClick; if (highLightRow === _enum2.HighLightRowType.click && !tableStore.rowClicked) { tableStore.rowClicked = true; } if (typeof onClick === 'function') { return onClick(e); } }), [tableStore, rowExternalProps, expandRowByClick, handleExpandChange]); 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 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 () { var inlineEdit = tableStore.inlineEdit, currentEditRecord = tableStore.currentEditRecord, editors = tableStore.editors; if (inlineEdit && currentEditRecord && currentEditRecord.index > record.index && editors.size) { tableStore.editors.forEach(function (editor) { editor.alignEditor(); }); } }, [tableStore, record, record.isExpanded]); 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'; var hasExpandTd = expandIconAsCell && !tableStore.expandIconColumnIndex; expandRows.push( /*#__PURE__*/_react["default"].createElement(_Element, (0, _extends2["default"])({}, expandRowExternalProps, _rowProps), hasExpandTd && /*#__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 - (hasExpandTd ? 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) { var actualRecord = getRecord(columnGroup, groupPath, headerGroupIndex, record); var cellProps = { columnGroup: columnGroup, record: actualRecord, isDragging: snapshot ? snapshot.isDragging : false, isFixedRowHeight: isFixedRowHeight, provided: rest.key === _TableStore.DRAG_KEY ? provided : undefined, groupPath: groupPath, rowIndex: virtualIndex === undefined ? index : virtualIndex, children: hasExpandIcon(columnIndex) ? renderExpandIcon() : undefined, isDragDisabled: isDragDisabled, isRenderCell: isRenderRange(columnIndex) }; if (!isFixedRowHeight && propVirtual && !hidden) { return [/*#__PURE__*/_react["default"].createElement(_TableVirtualCell["default"], (0, _extends2["default"])({}, cellProps, rest, { key: rest.key })), actualRecord]; } return [/*#__PURE__*/_react["default"].createElement(_TableCell["default"], (0, _extends2["default"])({}, cellProps, rest, { inView: inView, key: rest.key })), actualRecord]; }; var _ref2 = function () { var customizable = tableStore.customizable, customizedBtn = tableStore.customizedBtn; var leafs = columnGroups.leafs; var sliceLeafs = !propVirtual ? leafs : (left ? leafs.slice.apply(leafs, (0, _toConsumableArray2["default"])(left)) : []).concat(leafs.slice.apply(leafs, (0, _toConsumableArray2["default"])(center))).concat(right ? leafs.slice.apply(leafs, (0, _toConsumableArray2["default"])(right)) : []); var columnLength = sliceLeafs.length; var hasBlankCell = leafs.length > sliceLeafs.length; return sliceLeafs.reduce(function (result, columnGroup, columnIndex) { var key = columnGroup.key; var colIndex = propVirtual && hasBlankCell ? leafs.findIndex(function (x) { return x.key === key; }) : columnIndex; if (key !== _TableStore.CUSTOMIZED_KEY) { var colSpan = customizable && !customizedBtn && 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; } var _getCell = getCell(columnGroup, colIndex, rest), _getCell2 = (0, _slicedToArray2["default"])(_getCell, 2), cell = _getCell2[0], actualRecord = _getCell2[1]; result[0].push(cell); if (highLightRow && actualRecord && actualRecord.isCurrent) { result[1].isCurrent = true; } } return result; }, [[], {}]); }(), _ref3 = (0, _slicedToArray2["default"])(_ref2, 2), columns = _ref3[0], isCurrent = _ref3[1].isCurrent; (0, _react.useEffect)(function () { if (isCurrent) { focusRow(); } }, [isCurrent, focusRow]); var rowPrefixCls = "".concat(prefixCls, "-row"); var classString = (0, _classnames["default"])(rowPrefixCls, (_classNames = {}, (0, _defineProperty2["default"])(_classNames, "".concat(rowPrefixCls, "-current"), 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, 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 = intersectionRef ? virtualHeight !== undefined ? virtualHeight : (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 useEmptyColumn = !fullColumnWidth && lock !== _enum2.ColumnLock.left && !tableStore.overflowX && !tableStore.hasEmptyWidthColumn; if (useEmptyColumn) { columns.push( /*#__PURE__*/_react["default"].createElement("td", { key: "empty-column" })); } if (propVirtual && blankVirtualCell.left.length) { columns.splice.apply(columns, [left ? left[1] : 0, 0].concat((0, _toConsumableArray2["default"])(blankVirtualCell.left))); } if (propVirtual && right && blankVirtualCell.right.length) { columns.splice.apply(columns, [center[1], 0].concat((0, _toConsumableArray2["default"])(blankVirtualCell.right))); } var tr = /*#__PURE__*/_react["default"].createElement(Element, (0, _extends2["default"])({ key: rowKey }, rowExternalProps, rowProps, { style: rowStyle }), columns); 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