es-grid-template
Version:
es-grid-template
1,312 lines (1,236 loc) • 69.2 kB
JavaScript
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _react = _interopRequireWildcard(require("react"));
var _usehooksTs = require("usehooks-ts");
var _utils = require("./hook/utils");
var _reactVirtual = require("@tanstack/react-virtual");
var _reactHookForm = require("react-hook-form");
var _antd = require("antd");
var _pagination = _interopRequireDefault(require("rc-master-ui/es/pagination"));
var _reactNumericComponent = require("react-numeric-component");
var _useContext = require("./useContext");
var _yup = require("@hookform/resolvers/yup");
var _rcMasterUi = require("rc-master-ui");
var _classnames = _interopRequireDefault(require("classnames"));
var _becoxyIcons = require("becoxy-icons");
var _ColumnsChoose = require("./ColumnsChoose");
var _TableWrapper = _interopRequireDefault(require("./table/TableWrapper"));
var _sweetalert2ReactContent = _interopRequireDefault(require("sweetalert2-react-content"));
var _sweetalert = _interopRequireDefault(require("sweetalert2"));
var _locale = require("rc-master-ui/es/locale");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
const MySwal = (0, _sweetalert2ReactContent.default)(_sweetalert.default);
const {
Paragraph,
Title
} = _antd.Typography;
const validateData = async (data, formSchema) => {
if (!formSchema) {
return [];
} else {
const errors = [];
for (let i = 0; i < data.length; i++) {
try {
await formSchema.validate(data[i], {
abortEarly: false
});
} catch (error) {
errors.push(error.inner.reduce((acc, err) => {
acc[err.path] = {
field: err.path,
index: i,
message: err.message,
type: err.type,
ref: {
name: err.path
}
};
return {
...acc,
index: i,
id: data[i].rowId
};
}, {}));
}
}
return errors;
}
};
const TableContainerEdit = props => {
const {
t,
table,
title,
id,
prefix,
commandClick,
editAble,
rowEditable,
rowKey,
format,
dataSource,
originData,
expandable,
wrapSettings,
recordDoubleClick,
// triggerFilter,
selectionSettings,
isSelectionChange,
setIsSelectionChange,
// onContextMenu,
contextMenuItems,
setSorterChange,
setFilterChange,
onCellPaste,
// triggerPaste,
validate,
// triggerChangeData,
onCellChange,
onDataChange,
defaultValue,
toolbarItems,
mergedFilterKeys,
setMergedFilterKeys,
expanded,
setExpanded,
onBlur,
fullScreen,
pagination,
showToolbar,
actionTemplate,
showColumnChoose,
height,
minHeight,
summary,
locale,
lang,
groupColumns,
columns,
propsColumns,
triggerChangeColumns,
columnHidden,
showEmptyText,
isFullScreen,
setIsFullScreen,
infiniteScroll,
windowSize,
next,
loading,
contextMenuOpen,
contextMenuClick,
contextMenuHidden,
commandSettings,
isDataTree,
onCellClick,
// setColumnSizing,
setColumns,
columnSizing,
columnSizingInfo,
rowClassName,
onRowStyles,
dataSourceFilter,
setIsExpandClick
} = props;
const [paginationLocal] = (0, _locale.useLocale)('Pagination');
const [tableLocal] = (0, _locale.useLocale)('Table');
const containerRef = _react.default.useRef(null);
const bottomToolbarRef = _react.default.useRef(null);
const topToolbarRef = _react.default.useRef(null);
const childrenColumnName = 'children';
// const visibleColumns = table.getVisibleLeafColumns()
// //The virtualizers need to know the scrollable container element
const tableContainerRef = _react.default.useRef(null);
const [, copy] = (0, _usehooksTs.useCopyToClipboard)();
// const columnSizingState = table.getState().columnSizing;
const itemsAdd = _react.default.useMemo(() => {
return [{
key: '10',
label: `10 ${t ? t('rows') : 'rows'}`
}, {
key: '50',
label: `50 ${t ? t('rows') : 'rows'}`
}, {
key: '100',
label: `100 ${t ? t('rows') : 'rows'}`
}];
}, [t]);
const [dataErrors, setDataErrors] = _react.default.useState([]);
_react.default.useEffect(() => {
if (validate && dataSource && dataSource.length) {
validateData(dataSource, validate).then(error => {
setDataErrors([...error]);
// if (getErrors) {
// getErrors([...error])
// }
});
}
}, [validate, dataSource]);
const visibleColumns = table.getVisibleLeafColumns();
// const visibleColumns = table.getVisibleFlatColumns();
const fixedLeftColumns = table.getState().columnPinning.left ? visibleColumns.filter(vc => table.getState().columnPinning.left?.includes(vc.id)) : [];
const fixedRightColumns = table.getState().columnPinning.right ? visibleColumns.filter(vc => table.getState().columnPinning.right?.includes(vc.id)) : [];
//we are using a slightly different virtualization strategy for columns (compared to virtual rows) in order to support dynamic row heights
const columnVirtualizer = (0, _reactVirtual.useVirtualizer)({
count: visibleColumns.length,
estimateSize: index => visibleColumns[index].getSize(),
//estimate width of each column for accurate scrollbar dragging
getScrollElement: () => tableContainerRef.current,
horizontal: true,
// measureElement(element) {
// return element?.getBoundingClientRect().width;
// },
measureElement: typeof window !== 'undefined' && navigator.userAgent.indexOf('Firefox') === -1 ? element => element?.getBoundingClientRect().height : undefined,
overscan: 0 //how many columns to render on each side off screen each way (adjust this for performance)
});
const virtualColumns = columnVirtualizer.getVirtualItems();
const cacheColumns = columnVirtualizer.measurementsCache;
const rightCols = table.getState().columnPinning.right?.length ? [...cacheColumns].slice(-(table.getState().columnPinning.right?.length ?? 0)) : [];
const leftCols = [...cacheColumns].slice(0, table.getState().columnPinning.left?.length ?? 0);
const rightWidth = (0, _utils.sumSize)(rightCols);
const leftWidth = (0, _utils.sumSize)(leftCols);
//different virtualization strategy for columns - instead of absolute and translateY, we add empty columns to the left and right
let virtualPaddingLeft;
let virtualPaddingRight;
const pdRight = columnVirtualizer.getTotalSize() - (virtualColumns[virtualColumns.length - 1]?.end ?? 0);
if (columnVirtualizer && virtualColumns?.length) {
virtualPaddingLeft = fixedLeftColumns && fixedLeftColumns.length > 0 ? (virtualColumns[0]?.start ?? 0) - leftWidth > 0 ? (virtualColumns[0]?.start ?? 0) - leftWidth : 0 : virtualColumns[0]?.start ?? 0;
// virtualPaddingLeft = leftCols.length === rss.length ? (virtualColumns[0]?.start ?? 0) : 0;
// columnVirtualizer.getTotalSize() - (virtualColumns[virtualColumns.length - 1]?.end ?? 0) - rightWidth > 0 ? columnVirtualizer.getTotalSize() - (virtualColumns[virtualColumns.length - 1]?.end ?? 0) - rightWidth : 0;
virtualPaddingRight = fixedRightColumns && fixedRightColumns.length > 0 ? pdRight - rightWidth > 0 ? pdRight - rightWidth : 0 : pdRight;
// virtualPaddingRight = columnVirtualizer.getTotalSize() - (virtualColumns[virtualColumns.length - 1]?.end ?? 0)
}
const [editingKey, setEditingKey] = _react.default.useState('');
const [rangeState, setRangeState] = _react.default.useState({
startRowIndex: undefined,
endRowIndex: undefined,
startColIndex: undefined,
endColIndex: undefined,
rowIds: [],
colIds: [],
colRange: [],
rowRange: []
});
const [rangePasteState, setRangePasteState] = _react.default.useState({
startRowIndex: undefined,
endRowIndex: undefined,
startColIndex: undefined,
endColIndex: undefined,
rowIds: [],
colIds: [],
colRange: [],
rowRange: []
});
const [focusedCell, setFocusedCell] = _react.default.useState(undefined);
const [startCell, setStartCell] = _react.default.useState(undefined);
const [endCell, setEndCell] = _react.default.useState(undefined);
const [startPasteCell, setStartPasteCell] = _react.default.useState(undefined);
const [endPasteCell, setEndPasteCell] = _react.default.useState(undefined);
const [isSelecting, setIsSelecting] = _react.default.useState(false);
const [isPasting, setIsPasting] = _react.default.useState(false);
// const [isFullScreen] = React.useState(false);
const [tableHeight, settableHeight] = _react.default.useState(0);
// const [isAddNewRow, setIsAddNewRow] = React.useState(false)
const rowsFocus = _react.default.useMemo(() => {
return startCell && endCell ? (0, _utils.getRowIdsBetween)(table, startCell.rowId, endCell.rowId) : [];
}, [endCell, startCell, table]);
const copySelectionToClipboard = _react.default.useCallback(() => {
if (!startCell || !endCell) {
return;
}
// const allRows = table.getRowModel().rows;
const allRows = table.getRowModel().flatRows;
// const allColumns = table.getAllLeafColumns();
const rowIds = (0, _utils.getRowIdsBetween)(table, startCell.rowId, endCell.rowId);
const colIds = (0, _utils.getColIdsBetween)(table, startCell.colId, endCell.colId);
const dataToCopy = [];
rowIds.forEach(rowId => {
const row = allRows.find(r => r.id === rowId);
if (!row) return;
const rowData = [];
colIds.forEach(colId => {
const cellll = row.getVisibleCells().find(c => c.column.id === colId);
const value = cellll?.getValue();
rowData.push(value !== undefined ? String(value) : '');
});
dataToCopy.push(rowData);
});
// Convert to TSV string
const tsv = dataToCopy.map(row => row.join('\t')).join('\n');
// Copy to clipboard
// navigator.clipboard.writeText(tsv).then(() => {
// });
copy(tsv).then(() => {}).catch(() => {});
}, [startCell, endCell, table]);
const triggerChangeData = _react.default.useCallback(newData => {
onDataChange?.(newData);
}, [onDataChange, dataSource]);
const triggerPaste = _react.default.useCallback((pastedRows, pastedColumnsArray, newData, copyRows) => {
const handlePasteCallback = callbackData => {
const rsFilterData = (0, _utils.updateOrInsert)((0, _utils.flattenArray)([...originData]), (0, _utils.flattenArray)([...callbackData]));
const rs = (0, _utils.unFlattenData)(rsFilterData);
triggerChangeData(rs);
};
if (onCellPaste && onCellPaste.onPasted) {
if (onCellPaste.onPasted.length > 1) {
// có callback
onCellPaste.onPasted({
pasteData: pastedRows,
copyRows,
type: 'onPaste',
data: originData,
pastedColumns: pastedColumnsArray
}, handlePasteCallback);
} else {
// không có callback
onCellPaste.onPasted({
pasteData: pastedRows,
type: 'onPaste',
copyRows,
data: originData,
pastedColumns: pastedColumnsArray
}, handlePasteCallback);
triggerChangeData(newData);
}
} else {
triggerChangeData(newData);
}
}, [onCellPaste, originData, triggerChangeData]);
const handlePasted = _react.default.useCallback(pasteData => {
if (!startCell) {
return;
}
const rows = pasteData.slice(0, onCellPaste?.maxRowsPaste ?? 200);
// const allRows = table.getRowModel().rows;
const allRows = table.getRowModel().flatRows;
const allCols = table.getVisibleLeafColumns();
const startRowIdx = allRows.findIndex(r => r.id === startCell.rowId);
const startColIdx = allCols.findIndex(c => c.id === startCell.colId);
// const record: any = allRows[startRowIdx].original
const record = table.getRow(startCell.rowId).original;
const row = table.getRow(startCell.rowId);
if (!row.parentId) {
// Cập nhật data mới
const newData = (0, _utils.flattenArray)([...dataSource]);
// Lấy vị trí bắt đầu
// const startRow = newData.findIndex((it) => it[rowKey as any] === record[rowKey])
const startRow = startRowIdx;
const startCol = startColIdx;
const pastedRows = [];
const pastedColumns = new Set();
rows.forEach((rowValues, rowIndex) => {
const targetRow = startRow + rowIndex;
// Nếu vượt quá số dòng hiện có, thêm dòng mới
if (targetRow >= newData.length) {
const newID = (0, _utils.newGuid)();
const defaultRowValue = (0, _utils.getDefaultValue)(defaultValue);
newData.push(defaultValue ? {
...defaultRowValue,
id: undefined,
rowId: newID
} : {
id: undefined,
rowId: newID
});
}
rowValues.forEach((cellValue, colIndex) => {
const targetCol = startCol + colIndex;
if (targetCol >= allCols.length) {
// Không vượt quá số cột
return;
}
const columnTarget = allCols[targetCol];
const columnOri = columnTarget.columnDef.meta ?? {};
const isEdit = typeof columnOri?.editEnable === 'function' ? columnOri.editEnable(newData[targetRow]) : columnOri.editEnable;
if (isEdit) {
const columnKey = allCols[targetCol].id;
// if (columnOri.type === 'number' && isFormattedNumber(cellValue.trim())) {
if (columnOri.type === 'number') {
if (cellValue.trim() === '') {
newData[targetRow] = {
...newData[targetRow],
[columnKey]: null
};
}
if ((0, _utils.isFormattedNumber)(cellValue.trim()) || !isNaN(Number(cellValue.trim()))) {
const colFormat = typeof columnOri.format === 'function' ? columnOri.format(record) : columnOri.format;
const valuePasteFormat = (0, _utils.detectSeparators)(cellValue.trim());
const cellFormat = (0, _utils.getFormat)(colFormat, format);
const thousandSeparator = valuePasteFormat?.thousandSeparator;
const decimalSeparator = valuePasteFormat?.decimalSeparator;
const dec = cellFormat?.decimalScale;
const numericFormatProps = {
thousandSeparator: (0, _utils.checkThousandSeparator)(thousandSeparator, decimalSeparator),
decimalSeparator: (0, _utils.checkDecimalSeparator)(thousandSeparator, decimalSeparator),
allowNegative: cellFormat?.allowNegative ?? true,
prefix: cellFormat?.prefix,
suffix: cellFormat?.suffix,
decimalScale: dec,
fixedDecimalScale: cellFormat?.fixedDecimalScale ?? false
};
const val = (0, _reactNumericComponent.removeNumericFormat)(cellValue.trim(), undefined, numericFormatProps);
newData[targetRow] = {
...newData[targetRow],
[columnKey]: Number(val)
};
}
} else {
newData[targetRow] = {
...newData[targetRow],
[columnKey]: cellValue.trim()
};
}
pastedColumns.add(columnKey);
}
});
// Lưu dòng được paste
pastedRows.push(newData[targetRow]);
});
const pastedColumnsArray = Array.from(pastedColumns) ?? [];
const rsFilterData = (0, _utils.updateOrInsert)((0, _utils.flattenArray)([...originData]), newData);
const rs = (0, _utils.unFlattenData)(rsFilterData);
triggerPaste?.(pastedRows, pastedColumnsArray, rs, []);
} else {
// const parent = findItemByKey(dataSource, rowKey as any, record.parentId)
const parent = row.getParentRow()?.original;
// Cập nhật childData mới
const childData = parent?.children ? [...parent.children] : [];
// Lấy vị trí bắt đầu
// const { row: startRow, col: startCol } = selectedCell;
const startRow = childData.findIndex(it => it[rowKey] === record[rowKey]);
const startCol = startColIdx;
const pastedRows = [];
const pastedColumns = new Set();
rows.forEach((rowValues, rowIndex) => {
const targetRow = startRow + rowIndex;
// Nếu vượt quá số dòng hiện có, thêm dòng mới
if (targetRow >= childData.length) {
childData.push({
id: undefined,
rowId: (0, _utils.newGuid)(),
parentId: parent[rowKey ?? 'id']
});
}
rowValues.forEach((cellValue, colIndex) => {
const targetCol = startCol + colIndex;
if (targetCol >= allCols.length) {
// Không vượt quá số cột
return;
}
const columnTarget = allCols[targetCol];
// const isEdit = typeof columnTarget.editEnable === 'function' ? columnTarget.editEnable(childData[targetRow]) : columnTarget.editEnable
const columnOri = columnTarget.columnDef.meta ?? {};
const isEdit = typeof columnOri?.editEnable === 'function' ? columnOri.editEnable(childData[targetRow]) : columnOri.editEnable;
// if (isEdit) {
// const columnKey = allCols[targetCol].id
// childData[targetRow] = { ...childData[targetRow], [columnKey]: cellValue.trim() }
// pastedColumns.add(columnKey)
// }
if (isEdit) {
const columnKey = allCols[targetCol].id;
// if (columnOri.type === 'number' && isFormattedNumber(cellValue.trim())) {
if (columnOri.type === 'number') {
if (cellValue.trim() === '') {
childData[targetRow] = {
...childData[targetRow],
[columnKey]: null
};
}
if ((0, _utils.isFormattedNumber)(cellValue.trim()) || !isNaN(Number(cellValue.trim()))) {
const colFormat = typeof columnOri.format === 'function' ? columnOri.format(record) : columnOri.format;
const valuePasteFormat = (0, _utils.detectSeparators)(cellValue.trim());
const cellFormat = (0, _utils.getFormat)(colFormat, format);
const thousandSeparator = valuePasteFormat?.thousandSeparator;
const decimalSeparator = valuePasteFormat?.decimalSeparator;
const dec = cellFormat?.decimalScale;
const numericFormatProps = {
thousandSeparator: (0, _utils.checkThousandSeparator)(thousandSeparator, decimalSeparator),
decimalSeparator: (0, _utils.checkDecimalSeparator)(thousandSeparator, decimalSeparator),
allowNegative: cellFormat?.allowNegative ?? true,
prefix: cellFormat?.prefix,
suffix: cellFormat?.suffix,
decimalScale: dec,
fixedDecimalScale: cellFormat?.fixedDecimalScale ?? false
};
const val = (0, _reactNumericComponent.removeNumericFormat)(cellValue.trim(), undefined, numericFormatProps);
childData[targetRow] = {
...childData[targetRow],
[columnKey]: Number(val)
};
}
} else {
childData[targetRow] = {
...childData[targetRow],
[columnKey]: cellValue.trim()
};
}
pastedColumns.add(columnKey);
}
});
// Lưu dòng được paste
pastedRows.push(childData[targetRow]);
});
const pastedColumnsArray = Array.from(pastedColumns) ?? [];
const newRowData = {
...parent,
children: childData
}; // item đã được filter
const newDataSource = (0, _utils.updateArrayByKey)(originData, newRowData, rowKey);
triggerPaste?.(pastedRows, pastedColumnsArray, newDataSource, []);
}
}, [dataSource, format, onCellPaste?.maxRowsPaste, originData, rowKey, startCell, table, triggerPaste]);
const handlePasteToTable = _react.default.useCallback(pasteData => {
if (!startCell) return;
// const pastedRows = pasted.trim().split('\n').map(row => row.split('\t'));
// const clipboardText = e.clipboardData?.getData('text/plain') ?? '';
// Chuyển đổi dữ liệu từ clipboard thành mảng
// const rowsPasted = pasteData.split("\n").filter((row: any) => row !== '').map((row: any) =>
// row.replace(/\r/g, "").split("\t")
// )
// const rowsPasted = parseExcelText(pasteData)
const rowsPasted = (0, _utils.parseExcelClipboardText)(pasteData);
if (rowsPasted.length > (onCellPaste?.maxRowsPaste ?? 200)) {
// bật popup thông báo
_antd.Modal.confirm({
content: /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(Paragraph, {
style: {
marginBottom: '.25rem',
fontSize: 14
}
}, "D\u1EEF li\u1EC7u sao ch\xE9p v\u01B0\u1EE3t qu\xE1 s\u1ED1 d\xF2ng cho ph\xE9p (", onCellPaste?.maxRowsPaste ?? 200, " d\xF2ng).Ph\u1EA7n m\u1EC1n s\u1EBD ch\u1EC9 l\u1EA5y (", onCellPaste?.maxRowsPaste ?? 200, " d\xF2ng \u0111\u1EA7u ti\xEAn."), /*#__PURE__*/_react.default.createElement(Title, {
level: 5,
style: {
marginTop: '.75rem'
}
}, "B\u1EA1n c\xF3 mu\u1ED1n ti\u1EBFp t\u1EE5c sao ch\xE9p kh\xF4ng?")),
centered: true,
className: 'be-popup-container',
onOk: () => {
handlePasted(rowsPasted);
}
// footer: (_, { OkBtn, CancelBtn }) => (
// <>
// <OkBtn />
// <CancelBtn />
// </>
// ),
});
} else {
handlePasted(rowsPasted);
}
}, [handlePasted, onCellPaste?.maxRowsPaste, startCell]);
_react.default.useEffect(() => {
const handleKeyDown = e => {
if (e.ctrlKey && e.key === 'c' && startCell && endCell && !editingKey) {
e.preventDefault();
copySelectionToClipboard();
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [startCell, endCell, table, copySelectionToClipboard, editingKey]);
_react.default.useEffect(() => {
const handlePaste = e => {
if (startCell && !editingKey) {
e.preventDefault(); // Chặn hành vi mặc định
const clipboardText = e.clipboardData?.getData('text/plain') ?? '';
handlePasteToTable(clipboardText);
}
};
document.addEventListener('paste', handlePaste);
return () => document.removeEventListener('paste', handlePaste);
}, [startCell, endCell, table, handlePasteToTable, editingKey]);
_react.default.useEffect(() => {
const handleClickOutside = event => {
const element = event.target;
const container = document.querySelector(".be-popup-container");
const containerContextMenu = document.querySelector(".popup-context-menu");
const tableBody = document.querySelector(`#${id} .ui-rc-grid-tbody`);
const itemContainer = document.querySelector(`#${id} .ui-rc-toolbar-selection-overflow-item`);
const itemHeader = document.querySelector(`#${id} .ui-rc-table-thead`);
const isInsideContainer = element.closest(".be-popup-container") && container;
const isInsideContainerContext = containerContextMenu && element.closest(".popup-context-menu");
const isInsideToolbar = element.closest(`.ui-rc-toolbar-selection-overflow-item`) && itemContainer;
const isInsideHeader = itemHeader && itemHeader.contains(event.target);
if (isInsideContainer || isInsideToolbar || isInsideHeader || isInsideContainerContext || element.id === id) {
return;
}
if (containerRef.current && tableBody && !tableBody.contains(event.target)) {
if (editingKey) {
onBlur?.(dataSource);
}
setTimeout(() => {
setEditingKey('');
// editingKey.current = ''
});
setEndCell(undefined);
setStartCell(undefined);
setRangeState(undefined);
setFocusedCell(undefined);
}
};
// document.addEventListener('click', handleClickOutside)
document.addEventListener('mousedown', handleClickOutside);
// document.addEventListener('touchstart', handleClickOutside)
return () => {
// document.removeEventListener('click', handleClickOutside)
document.removeEventListener('mousedown', handleClickOutside);
// document.removeEventListener('touchstart', handleClickOutside)
};
}, [dataSource, editingKey, id, onBlur]);
const columnSizingState = table.getState().columnSizing;
_react.default.useEffect(() => {
requestAnimationFrame(() => {
columnVirtualizer.measure();
});
}, [columnSizingState, columnVirtualizer]);
_react.default.useEffect(() => {
if (!tableContainerRef.current) {
return;
}
if (columnSizingInfo.isResizingColumn === false) {
const aa = (0, _utils.updateColumnWidthsRecursive)(propsColumns, columnSizing);
setColumns(aa);
}
}, [columnSizingInfo]);
_react.default.useEffect(() => {
// const totalHeight = minHeight ?? height
const totalHeight = (0, _utils.getTableHeight)(height, minHeight);
if (totalHeight) {
const topHeight = topToolbarRef.current ? topToolbarRef.current.offsetHeight : 0;
const bottomHeight = bottomToolbarRef.current ? bottomToolbarRef.current.offsetHeight : 0;
settableHeight(totalHeight - topHeight - bottomHeight);
}
}, [id, height, editAble, minHeight, toolbarItems]);
const {
control,
handleSubmit,
setValue,
// trigger,
getValues,
reset,
formState: {
errors
}
} = (0, _reactHookForm.useForm)({
mode: 'onChange',
resolver: validate ? (0, _yup.yupResolver)(validate) : undefined
});
const handleAddMulti = _react.default.useCallback((item, n, newId) => {
if (item.onClick) {
item.onClick({
toolbar: item
});
} else {
const defaultRowValue = (0, _utils.getDefaultValue)(defaultValue);
const newRows = Array.from({
length: n
}).map(() => defaultRowValue ? {
...defaultRowValue,
id: undefined,
rowId: n === 1 && newId ? newId : (0, _utils.newGuid)()
} : {
id: undefined,
rowId: n === 1 && newId ? newId : (0, _utils.newGuid)()
});
const kkk = (0, _utils.getAllRowKey)(newRows) ?? [];
const rs = mergedFilterKeys ? [...mergedFilterKeys, ...kkk] : [...kkk];
setMergedFilterKeys?.(rs);
const newData = dataSource.concat(newRows);
triggerChangeData?.(newData);
}
}, [dataSource, defaultValue, mergedFilterKeys, setMergedFilterKeys, triggerChangeData]);
const onSubmit = formData => {
try {
// const record = (await form.validateFields()) as RecordType;
const row = {
...formData
};
// const newData = [...dataSource]
const newData = [...originData];
// @ts-ignore
const index = (0, _utils.flattenData)(childrenColumnName, newData).findIndex(item => formData[rowKey] === item[rowKey]);
const rs = (0, _utils.updateArrayByKey)(newData, row, rowKey);
if (index > -1) {
triggerChangeData?.(rs);
}
} catch (errInfo) {
console.log('Validate Failed:', errInfo);
}
};
const onSubmit2 = (formData, newOriginData) => {
try {
// const record = (await form.validateFields()) as RecordType;
const row = {
...formData
};
// const newData = [...dataSource]
const newData = [...newOriginData];
// @ts-ignore
const index = (0, _utils.flattenData)(childrenColumnName, newData).findIndex(item => formData[rowKey] === item[rowKey]);
const rs = (0, _utils.updateArrayByKey)(newData, row, rowKey);
if (index > -1) {
triggerChangeData?.(rs);
}
} catch (errInfo) {
console.log('Validate Failed:', errInfo);
}
};
const handleCellChange = args => {
const {
record,
type: changeType,
newState,
prevState,
option,
field,
indexCol,
indexRow,
key
} = args;
if (changeType === 'blur') {
const handleChangeCallback = callbackData => {
const callbackRecord = callbackData;
Object.entries(callbackRecord).forEach(([name, value]) => {
setValue(name, value);
});
onSubmit(callbackRecord);
};
if (onCellChange) {
if (onCellChange.length > 1) {
onCellChange({
field,
indexCol,
type: 'onChange',
value: newState,
option,
indexRow,
rowData: record,
rowId: key,
// rowsData: [...dataSource],
rowsData: [...originData],
sumValue: []
}, handleChangeCallback);
} else {
onCellChange({
field,
indexCol,
type: 'onChange',
option,
value: newState,
indexRow,
rowData: record,
rowId: key,
// rowsData: [...dataSource],
rowsData: [...originData],
sumValue: []
}, handleChangeCallback);
onSubmit(record);
}
}
}
if (prevState && newState && prevState !== newState && changeType === 'enter') {
onSubmit(record);
}
};
const handleCellChangeAndAddRow = args => {
const {
record,
type: changeType,
newState,
option,
field,
indexCol,
indexRow,
key
} = args;
// add new row
const defaultRowValue = (0, _utils.getDefaultValue)(defaultValue);
const newRowId = (0, _utils.newGuid)();
const newRows = Array.from({
length: 1
}).map(() => defaultRowValue ? {
...defaultRowValue,
id: undefined,
rowId: newRowId
} : {
id: undefined,
rowId: newRowId
});
const kkk = (0, _utils.getAllRowKey)(newRows) ?? [];
const rs = mergedFilterKeys ? [...mergedFilterKeys, ...kkk] : [...kkk];
setMergedFilterKeys?.(rs);
const newData = originData.concat(newRows);
setFocusedCell?.({
rowId: newRowId,
colId: field
});
setStartCell?.({
rowId: newRowId,
colId: field
});
setEndCell?.({
rowId: newRowId,
colId: field
});
setTimeout(() => {
setRangeState?.((0, _utils.getSelectedCellMatrix)(table, {
rowId: newRowId,
colId: field
}, {
rowId: newRowId,
colId: field
}));
});
setTimeout(() => {
const row = document.querySelector(`.ui-rc-grid-row[data-row-key="${newRowId}"]`);
const cellFocus = row?.querySelector('.ui-rc-grid-cell:not(.ui-rc-grid-cell-selection)');
if (cellFocus) {
cellFocus.scrollIntoView({
behavior: "smooth",
block: "start"
});
cellFocus.focus();
}
}, 100);
if (changeType === 'blur') {
const handleChangeCallback = callbackData => {
const callbackRecord = callbackData;
onSubmit2(callbackRecord, [...newData]);
};
if (onCellChange) {
if (onCellChange.length > 1) {
onCellChange({
field,
indexCol,
type: 'onChange',
value: newState,
option,
indexRow,
rowData: record,
rowId: key,
rowsData: [...newData],
sumValue: []
}, handleChangeCallback);
} else {
onCellChange({
field,
indexCol,
type: 'onChange',
option,
value: newState,
indexRow,
rowData: record,
rowId: key,
rowsData: [...newData],
sumValue: []
}, handleChangeCallback);
onSubmit2(record, [...newData]);
}
}
}
// if (prevState && newState && prevState !== newState && changeType === 'enter') {
// onSubmit(record)
// }
};
const handleDuplicate = _react.default.useCallback(() => {
// không tính tree
// Cập nhật data mới
const newData = (0, _utils.flattenArray)([...dataSource]);
// const duplicatedItems = rowsFocus.map(index => ({ ...newData[index], rowId: newGuid(), id: undefined, isDuplicate: true }))
const duplicatedItem = table.getRowModel().flatRows.find(it => it.id === focusedCell?.rowId);
// setStartCell(focusedCell)
// setEndCell(focusedCell)
// setRangeState(getSelectedCellMatrix(table, focusedCell, focusedCell))
const duplicatedItems = [{
...duplicatedItem?.original,
rowId: (0, _utils.newGuid)(),
id: undefined,
isDuplicate: true
}];
// Vị trí chèn là ngay sau phần tử lớn nhất trong rowsFocus
// const insertAfter = Math.max(...rowsFocus)
const insertAfter = newData.findIndex(it => it[rowKey] === focusedCell?.rowId);
const rsFilter = [...newData.slice(0, insertAfter + 1), ...duplicatedItems, ...newData.slice(insertAfter + 1)];
// const rs = updateOrInsertInOrder(originData, rsFilter)
const rs = (0, _utils.updateOrInsert)(originData, rsFilter);
// const rs2 = mergeWithFilter(originData, rsFilter)
triggerChangeData?.(rs);
}, [dataSource, focusedCell, originData, rowKey, table, triggerChangeData]);
// thêm n dòng bên trên
const handleInsertBefore = _react.default.useCallback((item, n) => {
const defaultRowValue = (0, _utils.getDefaultValue)(defaultValue);
setStartCell(focusedCell);
setEndCell(focusedCell);
setRangeState((0, _utils.getSelectedCellMatrix)(table, focusedCell, focusedCell));
// const record: any = table.getRowModel().rows.find((it) => it.id === rowsFocus[rowsFocus.length - 1])?.original
const record = table.getRowModel().flatRows.find(it => it.id === rowsFocus[rowsFocus.length - 1])?.original;
if (item.onClick) {
item.onClick({
toolbar: item
});
} else {
if (!record?.parentId) {
// Cập nhật data mới
const newData = [...originData];
const newRows = Array.from({
length: n
}).map(() => defaultRowValue ? {
...defaultRowValue,
id: undefined,
rowId: (0, _utils.newGuid)()
} : {
id: undefined,
rowId: (0, _utils.newGuid)()
});
const kkk = (0, _utils.getAllRowKey)(newRows) ?? [];
const rs = mergedFilterKeys ? [...mergedFilterKeys, ...kkk] : [...kkk];
setMergedFilterKeys?.(rs);
const index = newData.findIndex(obj => obj[rowKey] === record[rowKey]);
newData.splice(index, 0, ...newRows);
triggerChangeData?.(newData);
} else {
const newData = [...originData];
const parent = (0, _utils.findItemByKey)(newData, rowKey, record.parentId);
const newRows = Array.from({
length: n
}).map(() => defaultRowValue ? {
...defaultRowValue,
id: undefined,
rowId: (0, _utils.newGuid)(),
parentId: parent.rowId
} : {
id: undefined,
rowId: (0, _utils.newGuid)(),
parentId: parent.rowId
});
// Cập nhật childData mới
const childData = parent?.children ? [...parent.children] : [];
const index = childData.findIndex(obj => obj[rowKey] === record[rowKey]);
childData.splice(index, 0, ...newRows);
const newRowData = {
...parent,
children: childData
};
const newDataSource = (0, _utils.updateArrayByKey)(newData, newRowData, rowKey);
triggerChangeData?.(newDataSource);
}
}
}, [defaultValue, focusedCell, mergedFilterKeys, originData, rowKey, rowsFocus, setMergedFilterKeys, table, triggerChangeData]);
//thêm 1 dòng bên dưới
const handleInsertAfter = _react.default.useCallback((item, n) => {
const defaultRowValue = (0, _utils.getDefaultValue)(defaultValue);
// const insertAfter = Math.max(...rowsFocus)
// const record: RecordType = flattenData(childrenColumnName, dataSource)[insertAfter]
// const record: any = table.getRowModel().rows.find((it) => it.id === focusedCell?.rowId)?.original
const record = table.getRowModel().flatRows.find(it => it.id === focusedCell?.rowId)?.original;
if (item.onClick) {
item.onClick({
toolbar: item
});
} else {
if (!record?.parentId) {
// Cập nhật data mới
const newData = [...originData];
const newRows = Array.from({
length: n
}).map(() => defaultRowValue ? {
...defaultRowValue,
id: undefined,
rowId: (0, _utils.newGuid)()
} : {
id: undefined,
rowId: (0, _utils.newGuid)()
});
const kkk = (0, _utils.getAllRowKey)(newRows) ?? [];
const rs = mergedFilterKeys ? [...mergedFilterKeys, ...kkk] : [...kkk];
setMergedFilterKeys?.(rs);
const index = newData.findIndex(obj => obj[rowKey] === record[rowKey]);
newData.splice(index + 1, 0, ...newRows);
triggerChangeData?.(newData);
} else {
const newData = [...originData];
const parent = (0, _utils.findItemByKey)(newData, rowKey, record.parentId);
const newRows = Array.from({
length: n
}).map(() => defaultRowValue ? {
...defaultRowValue,
id: undefined,
rowId: (0, _utils.newGuid)(),
parentId: parent.rowId
} : {
id: undefined,
rowId: (0, _utils.newGuid)(),
parentId: parent.rowId
});
const kkk = (0, _utils.getAllRowKey)(newRows) ?? [];
const rs = mergedFilterKeys ? [...mergedFilterKeys, ...kkk] : [...kkk];
setMergedFilterKeys?.(rs);
// Cập nhật childData mới
const childData = parent?.children ? [...parent.children] : [];
const index = childData.findIndex(obj => obj[rowKey] === record[rowKey]);
childData.splice(index + 1, 0, ...newRows);
const newRowData = {
...parent,
children: childData
};
const newDataSource = (0, _utils.updateArrayByKey)(newData, newRowData, rowKey);
triggerChangeData?.(newDataSource);
}
}
}, [defaultValue, table, focusedCell?.rowId, originData, mergedFilterKeys, setMergedFilterKeys, triggerChangeData, rowKey]);
const handleInsertChild = _react.default.useCallback(item => {
const defaultRowValue = (0, _utils.getDefaultValue)(defaultValue);
const rowId = (0, _utils.newGuid)();
const record = table.getRowModel().rows.find(it => it.id === focusedCell?.rowId)?.original;
if (item.onClick) {
item.onClick({
toolbar: item
});
} else {
// const newData = [...dataSource]
const newData = [...originData];
let newElement;
if (!record?.children || record?.children && record.children.length === 0) {
newElement = {
...record,
children: [{
...defaultRowValue,
parentId: record?.rowId,
rowId
}]
};
} else {
newElement = {
...record,
children: [...record.children, {
...defaultRowValue,
parentId: record.rowId,
rowId
}]
};
}
const rs = mergedFilterKeys ? [...mergedFilterKeys, rowId] : [rowId];
setMergedFilterKeys?.(rs);
const newDataSource = (0, _utils.updateArrayByKey)(newData, newElement, rowKey);
triggerChangeData?.(newDataSource);
}
setTimeout(() => {
const row = table.getRowModel().rows.find(it => it.id === focusedCell?.rowId);
if (row) {
setExpanded(old => ({
...old,
[row.id]: true
}));
}
}, 10);
// const hasKey = mergedExpandedKeys.has(key)
// if (!hasKey) {
// const newExpandedKeys = [...mergedExpandedKeys, key]
// setInnerExpandedKeys(newExpandedKeys)
// }
}, [defaultValue, focusedCell?.rowId, mergedFilterKeys, originData, rowKey, setExpanded, setMergedFilterKeys, table, triggerChangeData]);
const handleDeleteRows = _react.default.useCallback(item => {
if (item.onClick) {
item.onClick({
toolbar: item
});
} else {
const filterData = (0, _utils.flattenArray)([...originData]);
const rs = filterData.filter(it => !rowsFocus.includes(it[rowKey]));
const newDaa = (0, _utils.unFlattenData)(rs);
if (commandSettings && commandSettings.confirmDialog) {
MySwal.fire({
title: t ? t('Confirm') : 'Confirm',
text: t ? t('Do you want to delete item?') : 'Do you want to delete item?',
// icon: 'warning',
allowOutsideClick: false,
showCancelButton: true,
confirmButtonText: t ? t('Delete') : 'Delete',
cancelButtonText: t ? t('Cancel') : 'Cancel',
customClass: {
confirmButton: 'be-button btn-primary',
cancelButton: 'be-button btn-danger ms-1'
},
buttonsStyling: false
}).then(async result => {
if (result.value) {
triggerChangeData?.([...newDaa]);
} else if (result.dismiss === MySwal.DismissReason.cancel) {}
});
} else {
// không hiện dialog
triggerChangeData?.([...newDaa]);
}
}
}, [commandSettings, originData, rowKey, rowsFocus, t, triggerChangeData]);
const handleDeleteAll = _react.default.useCallback(item => {
if (item.onClick) {
item.onClick({
toolbar: item
});
} else {
if (commandSettings && commandSettings.confirmDialog) {
MySwal.fire({
title: t ? t('Confirm') : 'Confirm',
text: t ? t('Do you want to delete item?') : 'Do you want to delete item?',
// icon: 'warning',
allowOutsideClick: false,
showCancelButton: true,
confirmButtonText: t ? t('Delete') : 'Delete',
cancelButtonText: t ? t('Cancel') : 'Cancel',
customClass: {
confirmButton: 'be-button btn-primary',
cancelButton: 'be-button btn-danger ms-1'
},
buttonsStyling: false
}).then(async result => {
if (result.value) {
triggerChangeData?.([]);
} else if (result.dismiss === MySwal.DismissReason.cancel) {}
});
} else {
triggerChangeData?.([]);
}
}
}, [commandSettings, t, triggerChangeData]);
const handleDeleteContent = () => {
if (startCell && endCell) {
const tmpData = (0, _utils.flattenArray)([...dataSource]);
const rs = tmpData.map((row, index) => {
if (!rangeState?.rowRange.includes(row.rowId)) {
return row;
}
const updatedRow = {
...row
};
for (const colId of rangeState.colRange) {
const column = table.getVisibleFlatColumns().find(it => it.id === colId)?.columnDef.meta;
const columnIndex = table.getVisibleFlatColumns().findIndex(it => it.id === colId);
if ((0, _utils.isEditable)(column, row)) {
let newValue = '';
if (column.type === 'number') {
newValue = 0;
}
if (column.type === 'boolean' || column.type === 'checkbox') {
newValue = false;
}
const editType = (0, _utils.getEditType)(column, row);
if (column.type === 'date' || column.type === 'datetime' || column.type === 'time' || column.type === 'month' || column.type === 'week' || column.type === 'year' || column.type === 'quarter' || editType === 'asyncSelect' || editType === 'select' || editType === 'treeSelect' || editType === 'selectTable') {
newValue = undefined;
}
updatedRow[colId] = newValue;
handleCellChange({
key: row[rowKey],
field: column.field ?? column.dataIndex,
record: updatedRow,
prevState: row[column.field],
newState: newValue,
option: '',
indexCol: columnIndex,
indexRow: index,
type: 'blur'
});
}
}
return updatedRow;
});
const newData = (0, _utils.unFlattenData)(rs);
triggerChangeData?.([...newData]);
}
};
const toolbarItemsBottom = _react.default.useMemo(() => {
if (!rowsFocus || rowsFocus.length === 0) {
return toolbarItems?.filter(it => it.position === 'Bottom' && it.visible !== false && it.key !== 'DUPLICATE' && it.key !== 'INSERT_BEFORE' && it.key !== 'INSERT_AFTER' && it.key !== 'DELETE_ROWS' && it.key !== 'INSERT_CHILDREN').map(item => {
if (item.key === 'ADD') {
return {
...item,
label: item.label ? t ? t(item.label) : item.label : t ? t('Add item') : 'Add item',
template: () => {
return /*#__PURE__*/_react.default.createElement(_react.Fragment, null, item.key === 'ADD' && /*#__PURE__*/_react.default.createElement("div", {
className: (0, _classnames.default)(`be-toolbar-item`, item?.className)
}, /*#__PURE__*/_react.default.createElement(_antd.Dropdown.Button, {
overlayClassName: 'be-popup-container',
trigger: ['click'],
style: {
color: '#28c76f',
borderColor: '#28c76f'
},
className: 'toolbar-button toolbar-dropdown-button',
menu: {
items: itemsAdd,
onClick: e => handleAddMulti(item, Number(e.key))
}
}, /*#__PURE__*/_react.default.createElement("span", {
style: {
color: '#28c76f'
},
onClick: () => handleAddMulti(item, 1)
}, item.label ? t ? t(item.label) : item.label : t ? t('Add item') : 'Add item'))));
}
};
}
if (item.key === 'DELETE') {
return {
...item,
label: item.label ? t ? t(item.label) : item.label : t ? t('Delete all item') : 'Delete all item',
template: () => {
return /*#__PURE__*/_react.default.createElement("div", {
className: (0, _classnames.default)(`be-toolbar-item`, item?.className)
}, /*#__PURE__*/_react.default.createElement(_antd.Button, {
style: {
color: '#eb4619',
borderColor: '#eb4619'
},
variant: 'outlined',
onClick: () => handleDeleteAll(item),
className: "d-flex toolbar-button"
}, item.label ? t ? t(item.label) : item.label : t ? t('Delete all item') : 'Delete all item'));
}
};
}
return {
...item
};
});
}
return toolbarItems?.filter(it => it.position === 'Bottom' && it.visible !== false).map(item => {
if (item.key === 'ADD') {
return {
...item,
label: item.label ? t ? t(item.label) : item.label : t ? t('Add item') : 'Add item',
template: () => {
return /*#__PURE__*/_react.default.createElement(_react.Fragment, null, item.key === 'ADD' && /*#__PURE__*/_react.default.createElement("div", {
className: (0, _classnames.default)(`be-toolbar-item`, item?.className)
}, /*#__PURE__*/_react.default.createElement(_antd.Dropdown.Button, {
title: "",
overlayClassName: 'be-popup-container',
style: {
color: '#28c76f',
borderColor: '#28c76f'
},
className: 'toolbar-button toolbar-dropdown-button',
menu: {
items: itemsAdd,
onClick: e => handleAddMulti(item, Number(e.key))
}
}, /*#__PURE__*/_react.default.createElement("span", {
style: {
color: '#28c76f'
},
onClick: () => handleAddMulti(item, 1)
}, item.label ? t ? t(item.label) : item.label : t ? t('Add item') : 'Add item'))));
}
};
}
if (item.key === 'DUPLICATE') {
return {
...item,
label: item.label ? t ? t(item.label) : item.label : t ? t('Duplicate') : 'Duplicate',
template: () => {
return /*#__PURE__*/_react.default.createElement(_react.Fragment, null, item.key === 'DUPLICATE' && item.visible !== false && rowsFocus.length > 0 && /*#__PURE__