Open History to see the last commit
1export function filePreviewDelimiter(file: { name: string; mimeType?: string }): "," | "\t" | null {
2 const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase();
3 if (mime === "text/csv") return ",";
4 if (mime === "text/tab-separated-values") return "\t";
5 if (mime && mime !== "text/plain" && mime !== "application/octet-stream") return null;
6 if (/\.csv$/i.test(file.name)) return ",";
7 if (/\.tsv$/i.test(file.name)) return "\t";
8 return null;
9}
10
11export function parseDelimitedPreview(
12 text: string,
13 delimiter: "," | "\t",
14 limits: { maxRows: number; maxColumns: number; maxCellLength: number } = {
15 maxRows: 100,
16 maxColumns: 30,
17 maxCellLength: 2000,
18 },
19) {
20 const rows: string[][] = [];
21 let row: string[] = [];
22 let cell = "";
23 let quoted = false;
24 let truncated = false;
25 let rowStart = text.charCodeAt(0) === 0xfeff ? 1 : 0;
26 const endCell = () => {
27 if (cell.length > limits.maxCellLength) {
28 let end = limits.maxCellLength;
29 const before = cell.charCodeAt(end - 1);
30 const after = cell.charCodeAt(end);
31 if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) end--;
32 cell = cell.slice(0, end);
33 truncated = true;
34 }
35 if (row.length < limits.maxColumns) row.push(cell);
36 else truncated = true;
37 cell = "";
38 };
39 for (let index = rowStart; index < text.length; index++) {
40 const char = text[index];
41 if (char === '"') {
42 if (quoted && text[index + 1] === '"') {
43 if (cell.length <= limits.maxCellLength) cell += '"';
44 else truncated = true;
45 index++;
46 continue;
47 }
48 if (quoted || cell === "") {
49 quoted = !quoted;
50 continue;
51 }
52 }
53 if (!quoted && (char === delimiter || char === "\n" || char === "\r")) {
54 endCell();
55 if (char !== delimiter) {
56 rows.push(row);
57 row = [];
58 if (char === "\r" && text[index + 1] === "\n") index++;
59 rowStart = index + 1;
60 if (rows.length === limits.maxRows)
61 return { rows, truncated: truncated || index < text.length - 1 };
62 }
63 } else if (cell.length <= limits.maxCellLength) cell += char;
64 else truncated = true;
65 }
66 if (rowStart < text.length) {
67 endCell();
68 rows.push(row);
69 }
70 return { rows, truncated: truncated || quoted };
71}