@ackplus/react-tanstack-data-table
Version:
A powerful React data table component built with MUI and TanStack Table
153 lines (152 loc) • 6.83 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.exportClientData = exportClientData;
exports.exportServerData = exportServerData;
const tslib_1 = require("tslib");
const XLSX = tslib_1.__importStar(require("xlsx"));
function exportClientData(table, options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const { format, filename, onProgress, onComplete, onError } = options;
try {
const selectedRows = table.getSelectedRows ? table.getSelectedRows() : [];
const hasSelectedRows = selectedRows.length > 0;
const rowsToExport = hasSelectedRows ? selectedRows : table.getFilteredRowModel().rows;
const exportData = rowsToExport.map((row, index) => {
onProgress === null || onProgress === void 0 ? void 0 : onProgress({
processedRows: index + 1,
totalRows: rowsToExport.length,
percentage: Math.round(((index + 1) / rowsToExport.length) * 100),
});
const rowData = {};
row.getVisibleCells().forEach(cell => {
const header = typeof cell.column.columnDef.header === 'string'
? cell.column.columnDef.header
: cell.column.id;
rowData[header] = cell.getValue() || '';
});
return rowData;
});
yield exportToFile(exportData, format, filename);
onComplete === null || onComplete === void 0 ? void 0 : onComplete({
success: true,
filename: `${filename}.${format === 'excel' ? 'xlsx' : 'csv'}`,
totalRows: exportData.length,
});
}
catch (error) {
console.error('Client export failed:', error);
onError === null || onError === void 0 ? void 0 : onError({
message: error instanceof Error ? error.message : 'Export failed',
code: 'CLIENT_EXPORT_ERROR',
});
}
});
}
function exportServerData(table, options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const { format, filename, fetchData, currentFilters, selection, onProgress, onComplete, onError } = options;
try {
onProgress === null || onProgress === void 0 ? void 0 : onProgress({
processedRows: 0,
totalRows: 0,
percentage: 0,
});
const { data } = yield fetchData(currentFilters, selection);
if (!data || !Array.isArray(data)) {
throw new Error('Invalid data received from server');
}
const visibleColumns = table.getVisibleLeafColumns().filter(col => col.getIsVisible());
const exportData = data.map((rowData, index) => {
onProgress === null || onProgress === void 0 ? void 0 : onProgress({
processedRows: index + 1,
totalRows: data.length,
percentage: Math.round(((index + 1) / data.length) * 100),
});
const exportRow = {};
visibleColumns.forEach(column => {
const columnId = column.id;
const header = typeof column.columnDef.header === 'string'
? column.columnDef.header
: columnId;
let value = rowData[columnId];
const columnDef = column.columnDef;
if (columnDef.accessorFn && typeof columnDef.accessorFn === 'function') {
value = columnDef.accessorFn(rowData);
}
if (value === null || value === undefined) {
value = '';
}
else if (typeof value === 'object') {
value = JSON.stringify(value);
}
else {
value = String(value);
}
exportRow[header] = value;
});
return exportRow;
});
yield exportToFile(exportData, format, filename);
onComplete === null || onComplete === void 0 ? void 0 : onComplete({
success: true,
filename: `${filename}.${format === 'excel' ? 'xlsx' : 'csv'}`,
totalRows: exportData.length,
});
}
catch (error) {
console.error('Server export failed:', error);
onError === null || onError === void 0 ? void 0 : onError({
message: error instanceof Error ? error.message : 'Export failed',
code: 'SERVER_EXPORT_ERROR',
});
}
});
}
function exportToFile(data, format, filename) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
if (data.length === 0) {
throw new Error('No data to export');
}
if (format === 'csv') {
const csv = convertToCSV(data);
downloadFile(csv, `${filename}.csv`, 'text/csv');
}
else {
const workbook = XLSX.utils.book_new();
const worksheet = XLSX.utils.json_to_sheet(data);
XLSX.utils.book_append_sheet(workbook, worksheet, 'Data');
const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
downloadFile(blob, `${filename}.xlsx`, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
}
});
}
function convertToCSV(data) {
if (data.length === 0)
return '';
const headers = Object.keys(data[0]);
const csvRows = [headers.join(',')];
for (const row of data) {
const values = headers.map(header => {
const value = row[header] || '';
if (typeof value === 'string' && (value.includes(',') || value.includes('"') || value.includes('\n'))) {
return `"${value.replace(/"/g, '""')}"`;
}
return value;
});
csvRows.push(values.join(','));
}
return csvRows.join('\n');
}
function downloadFile(content, filename, mimeType) {
const blob = content instanceof Blob ? content : new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}