Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8709 fix(attachments): respect quoted fields when detecting CSV delimiters (#10062)

Jiahaod0c5eb1c5916
diff --git a/packages/views/editor/table-preview.test.tsx b/packages/views/editor/table-preview.test.tsx
index ace2675fa5..cee4b27268 100644
--- a/packages/views/editor/table-preview.test.tsx
+++ b/packages/views/editor/table-preview.test.tsx
@@ -92,6 +92,32 @@ describe("TablePreview", () => {
expect(title.closest("button")).toHaveClass("normal-case");
});
+ it("keeps quoted punctuation in CSV headers out of delimiter detection", () => {
+ renderWithI18n(
+ <TablePreview text={'"Priority; severity; impact",Owner\nhigh,Ada\n'} delimiter="," />,
+ );
+
+ expect(header("Priority; severity; impact")).toBeTruthy();
+ expect(header("Owner")).toBeTruthy();
+ expect(columnValues("c0")).toEqual(["high"]);
+ expect(columnValues("c1")).toEqual(["Ada"]);
+ expect(screen.getByText(/1 row/)).toHaveTextContent("1 row · 2 columns");
+ });
+
+ it("preserves literal quotes after a non-delimiter in CSV headers", () => {
+ renderWithI18n(
+ <TablePreview text={'5;" screen,Owner,Value\nlarge,Ada,10'} delimiter="," />,
+ );
+
+ expect(header('5;" screen')).toBeTruthy();
+ expect(header("Owner")).toBeTruthy();
+ expect(header("Value")).toBeTruthy();
+ expect(columnValues("c0")).toEqual(["large"]);
+ expect(columnValues("c1")).toEqual(["Ada"]);
+ expect(columnValues("c2")).toEqual(["10"]);
+ expect(screen.getByText(/1 row/)).toHaveTextContent("1 row · 3 columns");
+ });
+
it("says so when there are no rows", () => {
renderWithI18n(<TablePreview text={"only,a,header\n"} delimiter="," />);
expect(screen.getByText("No rows")).toBeTruthy();
diff --git a/packages/views/editor/utils/parse-delimited.test.ts b/packages/views/editor/utils/parse-delimited.test.ts
index 20f62845d3..f6a5f9934d 100644
--- a/packages/views/editor/utils/parse-delimited.test.ts
+++ b/packages/views/editor/utils/parse-delimited.test.ts
@@ -57,7 +57,7 @@ describe("parseDelimited", () => {
});
describe("sniffDelimiter", () => {
- it("picks whichever candidate splits the first line most", () => {
+ it("picks whichever candidate splits the first record most", () => {
expect(sniffDelimiter("a,b,c\n1,2,3")).toBe(",");
expect(sniffDelimiter("a;b;c\n1,5;2,5;3")).toBe(";");
expect(sniffDelimiter("a\tb\tc")).toBe("\t");
@@ -66,6 +66,99 @@ describe("sniffDelimiter", () => {
it("defaults to a comma for a single column", () => {
expect(sniffDelimiter("only\n1\n2")).toBe(",");
});
+
+ it.each([",", ";", "\t"] as const)(
+ "ignores other delimiters in quoted fields when detecting %j",
+ (delimiter) => {
+ const otherDelimiters = [",", ";", "\t"].filter((value) => value !== delimiter).join("");
+ const title = `Priority${otherDelimiters.repeat(3)}impact`;
+ const text = `id${delimiter}"${title}"${delimiter}Owner\n1${delimiter}high${delimiter}Ada`;
+ expect(sniffDelimiter(text)).toBe(delimiter);
+ expect(parseDelimited(text, sniffDelimiter(text))).toEqual([
+ ["id", title, "Owner"],
+ ["1", "high", "Ada"],
+ ]);
+ },
+ );
+
+ it.each(["\n", "\r\n", "\r"])(
+ "reads a quoted header across %j line breaks",
+ (newline) => {
+ const text = `"Priority;${newline}severity; impact",Owner${newline}high,Ada`;
+ expect(sniffDelimiter(text)).toBe(",");
+ expect(parseDelimited(text, sniffDelimiter(text))[0]).toEqual([
+ `Priority;${newline}severity; impact`,
+ "Owner",
+ ]);
+ },
+ );
+
+ it("keeps escaped quotes inside a quoted field", () => {
+ expect(sniffDelimiter('id;"said ""hi, there, friend""";Owner\n1;ok;Ada')).toBe(";");
+ });
+
+ it("recognizes a quoted first field after a byte order mark", () => {
+ expect(sniffDelimiter('\ufeff"Priority; severity; impact",Owner\nhigh,Ada')).toBe(",");
+ });
+
+ it("treats quotes within an unquoted field as text", () => {
+ expect(sniffDelimiter('5" screen;Owner\nlarge;Ada')).toBe(";");
+ });
+
+ it.each([
+ [",", ";"], [",", "\t"],
+ [";", ","], [";", "\t"],
+ ["\t", ","], ["\t", ";"],
+ ] as const)(
+ "detects %j with literal quotes after non-delimiter %j",
+ (delimiter, punctuation) => {
+ const title = `5${punctuation}" screen`;
+ const text = `${title}${delimiter}Owner${delimiter}Value\nlarge${delimiter}Ada${delimiter}10`;
+ expect(sniffDelimiter(text)).toBe(delimiter);
+ expect(parseDelimited(text, sniffDelimiter(text))).toEqual([
+ [title, "Owner", "Value"],
+ ["large", "Ada", "10"],
+ ]);
+ },
+ );
+
+ it.each([",", ";", "\t"] as const)(
+ "prefers well-formed %j quoting over more punctuation in a later field",
+ (delimiter) => {
+ const other = delimiter === "," ? ";" : ",";
+ const text = `id${delimiter}"a${other}b${other}c${other}d"${delimiter}Owner\n1${delimiter}ok${delimiter}Ada`;
+ expect(sniffDelimiter(text)).toBe(delimiter);
+ },
+ );
+
+ it("handles empty quoted fields and trailing empty fields", () => {
+ expect(sniffDelimiter('"";"";\n1;2;3')).toBe(";");
+ });
+
+ it("does not count delimiters inside a single quoted column", () => {
+ expect(sniffDelimiter('"a;b;c\nmore; text"\nvalue')).toBe(",");
+ });
+
+ it.each(["\n", "\r\n", "\r"])(
+ "stops at the first unquoted %j record ending",
+ (newline) => {
+ expect(sniffDelimiter(`a;b${newline}${"1,2,3,4\n".repeat(10_000)}`)).toBe(";");
+ },
+ );
+
+ it("handles a missing final newline", () => {
+ expect(sniffDelimiter('id;"a,b,c"')).toBe(";");
+ });
+
+ it("uses separator counts when all interpretations have malformed quotes", () => {
+ expect(sniffDelimiter('id;"a,b,c')).toBe(",");
+ });
+
+ it("keeps candidate precedence on ties and defaults for empty input", () => {
+ expect(sniffDelimiter("a,b;c\td")).toBe(",");
+ expect(sniffDelimiter("a;b\tc")).toBe(";");
+ expect(sniffDelimiter("")).toBe(",");
+ });
});
describe("toTable", () => {
diff --git a/packages/views/editor/utils/parse-delimited.ts b/packages/views/editor/utils/parse-delimited.ts
index 9e41b304e3..b108cacd3a 100644
--- a/packages/views/editor/utils/parse-delimited.ts
+++ b/packages/views/editor/utils/parse-delimited.ts
@@ -25,22 +25,83 @@ const CANDIDATES: readonly CellDelimiter[] = [",", ";", "\t"];
/**
* The delimiter a `.csv` file actually uses. Spreadsheets in locales with a
* decimal comma export `;`, and a mislabeled TSV is common. Read off the first
- * record: whichever candidate splits it most wins, a comma on ties.
+ * logical record under each candidate. Prefer well-formed quoting, then the
+ * most fields, with candidate order breaking ties. If every interpretation
+ * with separators has malformed quotes, keep the parser's lenient behavior.
+ * Track all candidates in one pass without allocating parsed fields.
*/
export function sniffDelimiter(text: string): CellDelimiter {
- let end = text.search(/\r|\n/);
- if (end < 0) end = text.length;
- const firstLine = text.slice(0, end);
+ const candidates = CANDIDATES.map((delimiter) => ({
+ delimiter,
+ count: 0,
+ quoted: false,
+ fieldStart: true,
+ afterQuote: false,
+ escapedQuote: false,
+ wellFormed: true,
+ done: false,
+ }));
+ let remaining = candidates.length;
+ for (let i = text.charCodeAt(0) === 0xfeff ? 1 : 0; i < text.length; i += 1) {
+ const char = text[i];
+ for (const candidate of candidates) {
+ if (candidate.done) continue;
+ if (candidate.quoted) {
+ if (candidate.escapedQuote) {
+ candidate.escapedQuote = false;
+ } else if (char === '"') {
+ if (text[i + 1] === '"') candidate.escapedQuote = true;
+ else {
+ candidate.quoted = false;
+ candidate.afterQuote = true;
+ }
+ }
+ continue;
+ }
+ if (char === candidate.delimiter) {
+ candidate.count += 1;
+ candidate.fieldStart = true;
+ candidate.afterQuote = false;
+ } else if (char === "\r" || char === "\n") {
+ candidate.done = true;
+ remaining -= 1;
+ } else if (char === '"' && candidate.fieldStart) {
+ candidate.quoted = true;
+ candidate.fieldStart = false;
+ } else {
+ if (char === '"' || candidate.afterQuote) candidate.wellFormed = false;
+ candidate.fieldStart = false;
+ }
+ }
+ if (remaining === 0) break;
+ if (candidates.every((candidate) => candidate.done || candidate.quoted)) {
+ // Only a quote can change any remaining interpretation. Skip the quoted
+ // content together, including a large body after an unterminated quote.
+ const nextQuote = text.indexOf('"', i + 1);
+ if (nextQuote < 0) break;
+ i = nextQuote - 1;
+ }
+ }
+
let best: CellDelimiter = ",";
let bestCount = 0;
- for (const candidate of CANDIDATES) {
- const count = firstLine.split(candidate).length - 1;
- if (count > bestCount) {
- best = candidate;
- bestCount = count;
+ let bestWellFormed: CellDelimiter = ",";
+ let bestWellFormedCount = 0;
+ for (const candidate of candidates) {
+ if (candidate.count > bestCount) {
+ best = candidate.delimiter;
+ bestCount = candidate.count;
+ }
+ if (
+ candidate.wellFormed &&
+ !candidate.quoted &&
+ candidate.count > bestWellFormedCount
+ ) {
+ bestWellFormed = candidate.delimiter;
+ bestWellFormedCount = candidate.count;
}
}
- return best;
+ return bestWellFormedCount > 0 ? bestWellFormed : best;
}
export function parseDelimited(text: string, delimiter: CellDelimiter): string[][] {