CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/components/data-grid/csv.tsx
Views: 687
1
/*
2
Component for viewing csv data.
3
*/
4
5
import { ReactNode, useMemo, useState } from "react";
6
import { Alert } from "antd";
7
import { parse } from "csv-parse/sync";
8
import { TableVirtuoso } from "react-virtuoso";
9
import { ColumnHeading } from "./headings";
10
import { rowBackground } from "@cocalc/util/misc";
11
12
function trim(x) {
13
if (x == null) return "";
14
let s = x.trim();
15
if (s[0] == '"') {
16
s = s.slice(1);
17
}
18
if (s.endsWith('"')) {
19
s = s.slice(0, -1);
20
}
21
return s;
22
}
23
24
interface Props {
25
value?: string;
26
overscan?: number;
27
errHint?: ReactNode;
28
}
29
30
export default function CSV({
31
overscan = 500,
32
value = "",
33
errHint = null,
34
}: Props) {
35
const [error, setError] = useState<string>("");
36
const data = useMemo(() => {
37
setError("");
38
try {
39
return parse(value, {
40
relax_quotes: true,
41
skip_empty_lines: true,
42
});
43
} catch (err) {
44
setError(`Unable to parse csv file: ${err}`);
45
return [];
46
}
47
}, [value]);
48
49
if (error) {
50
return (
51
<Alert
52
style={{ margin: "15px 0" }}
53
message={
54
<div>
55
{error}
56
<br />
57
{errHint}
58
</div>
59
}
60
type="error"
61
/>
62
);
63
}
64
65
return (
66
<TableVirtuoso
67
overscan={overscan}
68
style={{ height: "100%", overflow: "auto" }}
69
totalCount={Math.max(0, data.length - 1)}
70
fixedHeaderContent={() => (
71
<tr>
72
{data[0]?.map((field) => (
73
<ColumnHeading key={field} title={trim(field)} width={200} />
74
))}
75
</tr>
76
)}
77
itemContent={(index) => {
78
const style = {
79
border: "1px solid #eee",
80
padding: "0 5px",
81
height: "30px",
82
background: rowBackground({ index }),
83
};
84
return (
85
<>
86
{data[index + 1]?.map((val, k) => (
87
<td style={style} key={k}>
88
{val}
89
</td>
90
))}
91
</>
92
);
93
}}
94
/>
95
);
96
}
97
98