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(text: string, delimiter: "," | "\t") {
12 const rows: string[][] = [];
13 let row: string[] = [];
14 let cell = "";
15 let quoted = false;
16 let truncated = false;
17 let rowStart = text.charCodeAt(0) === 0xfeff ? 1 : 0;
18 const endCell = () => {
19 if (row.length < 30) row.push(cell);
20 else truncated = true;
21 cell = "";
22 };
23 for (let index = rowStart; index < text.length; index++) {
24 const char = text[index];
25 if (char === '"') {
26 if (quoted && text[index + 1] === '"') {
27 if (cell.length < 2000) cell += '"';
28 else truncated = true;
29 index++;
30 continue;
31 }
32 if (quoted || cell === "") {
33 quoted = !quoted;
34 continue;
35 }
36 }
37 if (!quoted && (char === delimiter || char === "\n" || char === "\r")) {
38 endCell();
39 if (char !== delimiter) {
40 rows.push(row);
41 row = [];
42 if (char === "\r" && text[index + 1] === "\n") index++;
43 rowStart = index + 1;
44 if (rows.length === 100) return { rows, truncated: truncated || index < text.length - 1 };
45 }
46 } else if (cell.length < 2000) cell += char;
47 else truncated = true;
48 }
49 if (rowStart < text.length) {
50 endCell();
51 rows.push(row);
52 }
53 return { rows, truncated: truncated || quoted };
54}