-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathcsvSerializer.ts
213 lines (186 loc) · 6.14 KB
/
csvSerializer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import type { GridColumnGroup, GridCsvExportOptions, GridRowId } from '../../../../models';
import { GRID_CHECKBOX_SELECTION_COL_DEF } from '../../../../colDef';
import type { GridCellParams } from '../../../../models/params/gridCellParams';
import type { GridStateColDef } from '../../../../models/colDef/gridColDef';
import type { GridApiCommunity } from '../../../../models/api/gridApiCommunity';
import { warnOnce } from '../../../../internals/utils/warning';
function sanitizeCellValue(value: unknown, csvOptions: CSVOptions): string {
const valueStr = typeof value === 'string' ? value : `${value}`;
if (csvOptions.shouldAppendQuotes || csvOptions.escapeFormulas) {
const escapedValue = valueStr.replace(/"/g, '""');
if (csvOptions.escapeFormulas) {
// See https://owasp.org/www-community/attacks/CSV_Injection
if (['=', '+', '-', '@', '\t', '\r'].includes(escapedValue[0])) {
return `"'${escapedValue}"`;
}
}
// Make sure value containing delimiter or line break won't be split into multiple cells
if ([csvOptions.delimiter, '\n', '\r', '"'].some((delimiter) => valueStr.includes(delimiter))) {
return `"${escapedValue}"`;
}
return escapedValue;
}
return valueStr;
}
export const serializeCellValue = (
cellParams: GridCellParams,
options: {
csvOptions: CSVOptions;
ignoreValueFormatter: boolean;
},
) => {
const { csvOptions, ignoreValueFormatter } = options;
let value: any;
if (ignoreValueFormatter) {
const columnType = cellParams.colDef.type;
if (columnType === 'number') {
value = String(cellParams.value);
} else if (columnType === 'date' || columnType === 'dateTime') {
value = (cellParams.value as Date)?.toISOString();
} else if (typeof cellParams.value?.toString === 'function') {
value = cellParams.value.toString();
} else {
value = cellParams.value;
}
} else {
value = cellParams.formattedValue;
}
return sanitizeCellValue(value, csvOptions);
};
type CSVOptions = Required<
Pick<GridCsvExportOptions, 'delimiter' | 'shouldAppendQuotes' | 'escapeFormulas'>
>;
type CSVRowOptions = {
sanitizeCellValue?: (value: any, csvOptions: CSVOptions) => any;
csvOptions: CSVOptions;
};
class CSVRow {
options: CSVRowOptions;
rowString = '';
isEmpty = true;
constructor(options: CSVRowOptions) {
this.options = options;
}
addValue(value: string) {
if (!this.isEmpty) {
this.rowString += this.options.csvOptions.delimiter;
}
if (value === null || value === undefined) {
this.rowString += '';
} else if (typeof this.options.sanitizeCellValue === 'function') {
this.rowString += this.options.sanitizeCellValue(value, this.options.csvOptions);
} else {
this.rowString += value;
}
this.isEmpty = false;
}
getRowString() {
return this.rowString;
}
}
const serializeRow = ({
id,
columns,
getCellParams,
csvOptions,
ignoreValueFormatter,
}: {
id: GridRowId;
columns: GridStateColDef[];
getCellParams: (id: GridRowId, field: string) => GridCellParams;
csvOptions: CSVOptions;
ignoreValueFormatter: boolean;
}) => {
const row = new CSVRow({ csvOptions });
columns.forEach((column) => {
const cellParams = getCellParams(id, column.field);
if (process.env.NODE_ENV !== 'production') {
if (String(cellParams.formattedValue) === '[object Object]') {
warnOnce([
'MUI X: When the value of a field is an object or a `renderCell` is provided, the CSV export might not display the value correctly.',
'You can provide a `valueFormatter` with a string representation to be used.',
]);
}
}
row.addValue(
serializeCellValue(cellParams, {
ignoreValueFormatter,
csvOptions,
}),
);
});
return row.getRowString();
};
interface BuildCSVOptions {
columns: GridStateColDef[];
rowIds: GridRowId[];
csvOptions: Required<
Pick<
GridCsvExportOptions,
| 'delimiter'
| 'includeColumnGroupsHeaders'
| 'includeHeaders'
| 'shouldAppendQuotes'
| 'escapeFormulas'
>
>;
ignoreValueFormatter: boolean;
apiRef: React.MutableRefObject<GridApiCommunity>;
}
export function buildCSV(options: BuildCSVOptions): string {
const { columns, rowIds, csvOptions, ignoreValueFormatter, apiRef } = options;
const CSVBody = rowIds
.reduce<string>(
(acc, id) =>
`${acc}${serializeRow({
id,
columns,
getCellParams: apiRef.current.getCellParams,
ignoreValueFormatter,
csvOptions,
})}\r\n`,
'',
)
.trim();
if (!csvOptions.includeHeaders) {
return CSVBody;
}
const filteredColumns = columns.filter(
(column) => column.field !== GRID_CHECKBOX_SELECTION_COL_DEF.field,
);
const headerRows: CSVRow[] = [];
if (csvOptions.includeColumnGroupsHeaders) {
const columnGroupLookup = apiRef.current.getAllGroupDetails();
let maxColumnGroupsDepth = 0;
const columnGroupPathsLookup = filteredColumns.reduce<
Record<GridStateColDef['field'], GridColumnGroup['groupId'][]>
>((acc, column) => {
const columnGroupPath = apiRef.current.getColumnGroupPath(column.field);
acc[column.field] = columnGroupPath;
maxColumnGroupsDepth = Math.max(maxColumnGroupsDepth, columnGroupPath.length);
return acc;
}, {});
for (let i = 0; i < maxColumnGroupsDepth; i += 1) {
const headerGroupRow = new CSVRow({
csvOptions,
sanitizeCellValue,
});
headerRows.push(headerGroupRow);
filteredColumns.forEach((column) => {
const columnGroupId = (columnGroupPathsLookup[column.field] || [])[i];
const columnGroup = columnGroupLookup[columnGroupId];
headerGroupRow.addValue(columnGroup ? columnGroup.headerName || columnGroup.groupId : '');
});
}
}
const mainHeaderRow = new CSVRow({
csvOptions,
sanitizeCellValue,
});
filteredColumns.forEach((column) => {
mainHeaderRow.addValue(column.headerName || column.field);
});
headerRows.push(mainHeaderRow);
const CSVHead = `${headerRows.map((row) => row.getRowString()).join('\r\n')}\r\n`;
return `${CSVHead}${CSVBody}`.trim();
}