Open History to see the last commit
1/** A table preview is bounded independently of the source preview's byte limit. */
2export function filePreviewDelimiter(file: { name: string; mimeType?: string }): "," | "\t" | null {
3 const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase();
4 if (mime === "text/csv") return ",";
5 if (mime === "text/tab-separated-values") return "\t";
6 if (mime && mime !== "text/plain" && mime !== "application/octet-stream") return null;
7 if (/\.csv$/i.test(file.name)) return ",";
8 if (/\.tsv$/i.test(file.name)) return "\t";
9 return null;
10}
11
12/** Preserve quoted delimiters, escaped quotes and multiline cells; raw mode retains all text. */
13export function parseDelimitedPreview(text: string, delimiter: "," | "\t") {
14 const rows: string[][] = [];
15 let row: string[] = [];
16 let cell = "";
17 let quoted = false;
18 let truncated = false;
19 const endCell = () => {
20 if (row.length < 30) row.push(cell);
21 else truncated = true;
22 cell = "";
23 };
24 for (let index = text.charCodeAt(0) === 0xfeff ? 1 : 0; index < text.length; index++) {
25 const char = text[index];
26 if (char === '"') {
27 if (quoted && text[index + 1] === '"') {
28 if (cell.length < 2000) cell += '"';
29 else truncated = true;
30 index++;
31 continue;
32 }
33 if (quoted || cell === "") {
34 quoted = !quoted;
35 continue;
36 }
37 }
38 if (!quoted && (char === delimiter || char === "\n" || char === "\r")) {
39 endCell();
40 if (char !== delimiter) {
41 rows.push(row);
42 row = [];
43 if (char === "\r" && text[index + 1] === "\n") index++;
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 (cell.length || row.length) {
50 endCell();
51 rows.push(row);
52 }
53 return { rows, truncated: truncated || quoted };
54}