Skip to content

Commit 1368267

Browse files
Copilothotlong
andcommitted
refactor: extract helper functions in Grid export handler
- Extract downloadFile() helper to reduce code duplication - Extract escapeCsvValue() helper for CSV escaping logic Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
1 parent cd6d2e0 commit 1368267

1 file changed

Lines changed: 19 additions & 19 deletions

File tree

packages/plugin-grid/src/ObjectGrid.tsx

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -520,6 +520,22 @@ export const ObjectGrid: React.FC<ObjectGridProps> = ({
520520
const prefix = exportConfig?.fileNamePrefix || schema.objectName || 'export';
521521
const exportData = maxRecords > 0 ? data.slice(0, maxRecords) : data;
522522

523+
const downloadFile = (blob: Blob, filename: string) => {
524+
const url = URL.createObjectURL(blob);
525+
const a = document.createElement('a');
526+
a.href = url;
527+
a.download = filename;
528+
a.click();
529+
URL.revokeObjectURL(url);
530+
};
531+
532+
const escapeCsvValue = (val: any): string => {
533+
const str = val == null ? '' : String(val);
534+
return str.includes(',') || str.includes('"') || str.includes('\n') || str.includes('\r')
535+
? `"${str.replace(/"/g, '""')}"`
536+
: str;
537+
};
538+
523539
if (format === 'csv') {
524540
const cols = generateColumns().filter((c: any) => c.accessorKey !== '_actions');
525541
const fields = cols.map((c: any) => c.accessorKey);
@@ -529,27 +545,11 @@ export const ObjectGrid: React.FC<ObjectGridProps> = ({
529545
rows.push(headers.join(','));
530546
}
531547
exportData.forEach(record => {
532-
rows.push(fields.map((f: string) => {
533-
const val = record[f];
534-
const str = val == null ? '' : String(val);
535-
return str.includes(',') || str.includes('"') || str.includes('\n') || str.includes('\r') ? `"${str.replace(/"/g, '""')}"` : str;
536-
}).join(','));
548+
rows.push(fields.map((f: string) => escapeCsvValue(record[f])).join(','));
537549
});
538-
const blob = new Blob([rows.join('\n')], { type: 'text/csv;charset=utf-8;' });
539-
const url = URL.createObjectURL(blob);
540-
const a = document.createElement('a');
541-
a.href = url;
542-
a.download = `${prefix}.csv`;
543-
a.click();
544-
URL.revokeObjectURL(url);
550+
downloadFile(new Blob([rows.join('\n')], { type: 'text/csv;charset=utf-8;' }), `${prefix}.csv`);
545551
} else if (format === 'json') {
546-
const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
547-
const url = URL.createObjectURL(blob);
548-
const a = document.createElement('a');
549-
a.href = url;
550-
a.download = `${prefix}.json`;
551-
a.click();
552-
URL.revokeObjectURL(url);
552+
downloadFile(new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' }), `${prefix}.json`);
553553
}
554554
setShowExport(false);
555555
}, [data, schema.exportOptions, schema.objectName, generateColumns]);

0 commit comments

Comments
 (0)