Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(data): preserve cell text when copying grid rows

Afloat5f2a504d1c84
diff --git a/src/components/data/DataGrid.test.ts b/src/components/data/DataGrid.test.ts
index a2e8ce4746..2cb3b7ceaf 100644
--- a/src/components/data/DataGrid.test.ts
+++ b/src/components/data/DataGrid.test.ts
@@ -67,6 +67,28 @@ describe("AG Grid component lifecycle", () => {
expect(handle.current!.visibleRows().rows.length).toBeLessThan(PAGE);
});
+ it.each([
+ { modifier: "ctrlKey", selected: false },
+ { modifier: "metaKey", selected: true },
+ ])("copies intact cell text with $modifier (selected: $selected)", async ({ modifier, selected }) => {
+ const rows = [["0001", "line one\r\nline two"], ["0002", 'a\t"quoted"']];
+ fixture.api.mockResolvedValue({ columns, rows, offset: 0, rowCount: rows.length });
+ const writeText = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue(undefined);
+ render("copy");
+ await vi.waitFor(() => expect(handle.current?.visibleRows().rows).toEqual(rows));
+ if (selected) {
+ const cell = host.querySelector<HTMLElement>('.ag-row[row-index="1"] .ag-cell')!;
+ flushSync(() => cell.click());
+ expect(host.querySelector('.ag-row[row-index="1"]')?.getAttribute("aria-selected")).toBe("true");
+ }
+ const viewport = host.querySelector('[data-testid="data-grid-viewport"]')!;
+ flushSync(() => viewport.dispatchEvent(new KeyboardEvent("keydown", { key: "c", [modifier]: true, bubbles: true, cancelable: true })));
+ await vi.waitFor(() => expect(writeText).toHaveBeenCalledTimes(1));
+ expect(writeText.mock.calls[0]![0]).toBe(selected
+ ? 'id\tdisplay.name\n0002\t"a\t""quoted"""'
+ : 'id\tdisplay.name\n0001\t"line one\r\nline two"\n0002\t"a\t""quoted"""');
+ });
+
it("filters a selected column, switches back to global search and clears", async () => {
render("filters");
await vi.waitFor(() => expect(fixture.api).toHaveBeenCalled());
diff --git a/src/components/data/data-format-roundtrip.test.ts b/src/components/data/data-format-roundtrip.test.ts
new file mode 100644
index 0000000000..d895a435b6
--- /dev/null
+++ b/src/components/data/data-format-roundtrip.test.ts
@@ -0,0 +1,45 @@
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { DuckDBInstance, type DuckDBConnection } from "@duckdb/node-api";
+import { afterAll, beforeAll, expect, it } from "vitest";
+import { cellText, tsv, type Cell } from "./data-format";
+
+let instance: DuckDBInstance;
+let connection: DuckDBConnection;
+let directory: string;
+beforeAll(async () => {
+ directory = mkdtempSync(join(tmpdir(), "omb-data-copy-"));
+ instance = await DuckDBInstance.create(":memory:");
+ connection = await instance.connect();
+});
+afterAll(() => {
+ connection?.closeSync();
+ instance?.closeSync();
+ if (directory) rmSync(directory, { recursive: true, force: true });
+});
+
+it.each([
+ {
+ name: "ordinary values",
+ columns: ["id", "value", "optional"],
+ rows: [["00012", 12.5, ""], ["9007199254740993", false, null]],
+ },
+ {
+ name: "tabs, quoted text and multiline cells",
+ columns: ["id", "notes\tand details", 'say "yes"', "optional"],
+ rows: [
+ ["00012", "line one\r\nline two\nline three\rline four", 'a\t"quoted"', ""],
+ ["9007199254740993", "trailing\t", '"quoted"', null],
+ ],
+ },
+])("round trips $name through DuckDB's tab-delimited reader", async ({ columns, rows }) => {
+ const file = join(directory, "clipboard.tsv");
+ writeFileSync(file, tsv(columns, rows as Cell[][]));
+ const names = columns.map((name) => `'${name.replace(/'/g, "''")}'`).join(", ");
+ const result = await connection.runAndReadAll(
+ `SELECT * FROM read_csv($1, delim='\t', header=true, all_varchar=true, force_not_null=[${names}])`, [file],
+ );
+ expect(result.columnNames()).toEqual(columns);
+ expect(result.getRowsJson()).toEqual(rows.map((row) => row.map(cellText)));
+});
diff --git a/src/components/data/data-format.test.ts b/src/components/data/data-format.test.ts
index f610725779..b9637156d5 100644
--- a/src/components/data/data-format.test.ts
+++ b/src/components/data/data-format.test.ts
@@ -33,10 +33,15 @@ describe("data helpers", () => {
});
it("copies as TSV and Markdown without breaking the shape", () => {
- expect(tsv(["a", "b"], [["x\ty", null], [1, true]])).toBe("a\tb\nx y\t\n1\ttrue");
+ expect(tsv(["a", "b"], [["x\ty", null], [1, true]])).toBe('a\tb\n"x\ty"\t\n1\ttrue');
expect(markdownTable(["a|b", "c"], [["x|y", "z\nw"]])).toBe("| a\\|b | c |\n| --- | --- |\n| x\\|y | z w |");
});
+ it("quotes TSV headers and cells without losing tabs, line endings or quotes", () => {
+ expect(tsv(['a\tb', 'say "yes"'], [['line one\r\nline two', '"quoted"'], ["", "plain"]]))
+ .toBe('"a\tb"\t"say ""yes"""\n"line one\r\nline two"\t"""quoted"""\n\tplain');
+ });
+
it("gives numbers narrow columns and text wide ones", () => {
expect(defaultColumnWidth({ name: "n", type: "BIGINT" })).toBe(110);
expect(defaultColumnWidth({ name: "description", type: "VARCHAR" })).toBe(180);
diff --git a/src/components/data/data-format.ts b/src/components/data/data-format.ts
index 2bc9f48a27..0e16327e53 100644
--- a/src/components/data/data-format.ts
+++ b/src/components/data/data-format.ts
@@ -40,8 +40,8 @@ export function rowObjects(columns: DataColumn[], rows: Cell[][]): Array<Record<
}
export function tsv(columns: string[], rows: Cell[][]): string {
- const clean = (text: string) => text.replace(/[\t\r\n]+/g, " ");
- return [columns.map(clean).join("\t"), ...rows.map((row) => row.map((cell) => clean(cellText(cell))).join("\t"))].join("\n");
+ const quote = (text: string) => /["\t\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
+ return [columns.map(quote).join("\t"), ...rows.map((row) => row.map((cell) => quote(cellText(cell))).join("\t"))].join("\n");
}
export function markdownTable(columns: string[], rows: Cell[][]): string {