Repository navigation
Expand file tree
/
Copy pathutils.tsx
More file actions
96 lines (80 loc) · 2.7 KB
/
Copy pathutils.tsx
File metadata and controls
96 lines (80 loc) · 2.7 KB
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
import type { Key } from 'react';
const { language } = navigator;
export const { compare } = new Intl.Collator(language, { numeric: true });
export const formatDate = new Intl.DateTimeFormat(language).format;
export const formatCurrency = new Intl.NumberFormat(language, {
style: 'currency',
currency: 'eur'
}).format;
export function showModalRef(dialog: HTMLDialogElement | null) {
dialog?.showModal();
}
export function getRowKey<K extends Key>(row: { readonly id: K }): K {
return row.id;
}
export function exportToCsv(gridEl: HTMLDivElement, fileName: string) {
// TODO: remove both toArray calls https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/join
const content = getGridContent(gridEl)
.map((row) => row.cells.map(serializeCellValue).toArray().join(','))
.toArray()
.join('\n');
downloadFile(fileName, new Blob([content], { type: 'text/csv;charset=utf-8;' }));
}
export async function exportToPdf(gridEl: HTMLDivElement, fileName: string) {
const [{ jsPDF }, { autoTable }] = await Promise.all([
import('jspdf'),
import('jspdf-autotable')
]);
const doc = new jsPDF({
orientation: 'l',
unit: 'px'
});
const head: string[][] = [];
const body: string[][] = [];
const foot: string[][] = [];
for (const row of getGridContent(gridEl)) {
const cells = row.cells.toArray();
if (row.type === 'body') {
body.push(cells);
} else if (row.type === 'head') {
head.push(cells);
} else {
foot.push(cells);
}
}
autoTable(doc, {
head,
body,
foot,
horizontalPageBreak: true,
styles: { cellPadding: 1.5, fontSize: 8, cellWidth: 'wrap' },
tableWidth: 'wrap'
});
doc.save(fileName);
}
function getGridContent(gridEl: HTMLDivElement) {
return Iterator.from(gridEl.children)
.filter((child) => child.matches('[role="row"]:not(.rdg-top-summary-row)'))
.map((row) => {
const cells = Iterator.from(row.children).map((cell) => cell.textContent);
if (row.classList.contains('rdg-header-row')) {
return { type: 'head', cells } as const;
}
if (row.classList.contains('rdg-bottom-summary-row')) {
return { type: 'foot', cells } as const;
}
return { type: 'body', cells } as const;
});
}
function serializeCellValue(value: string) {
const formattedValue = value.replaceAll('"', '""');
return formattedValue.includes(',') ? `"${formattedValue}"` : formattedValue;
}
function downloadFile(fileName: string, data: Blob) {
const downloadLink = document.createElement('a');
downloadLink.download = fileName;
const url = URL.createObjectURL(data);
downloadLink.href = url;
downloadLink.click();
URL.revokeObjectURL(url);
}