Skip to content

Commit dc22264

Browse files
feat(web): copy chat tables as tab-separated text from the table menu
1 parent 61eb4af commit dc22264

3 files changed

Lines changed: 78 additions & 16 deletions

File tree

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ import { useTheme } from "../hooks/useTheme";
160160
import { getClientSettings, useClientSettings } from "../hooks/useSettings";
161161
import {
162162
chatMarkdownClipboardPayload,
163-
serializeTableElementToCsv,
163+
serializeTableElementToDelimited,
164164
serializeTableElementToMarkdown,
165165
} from "../markdown-clipboard";
166166
import {
@@ -356,10 +356,12 @@ const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/;
356356
const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
357357
const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
358358

359+
type TableCopyFormat = "markdown" | "tsv" | "csv";
360+
359361
interface MarkdownActionFailureContext {
360362
readonly operation: string;
361363
readonly target?: string;
362-
readonly format?: "markdown" | "csv";
364+
readonly format?: TableCopyFormat;
363365
readonly language?: string;
364366
readonly fenceTitle?: string;
365367
readonly copyTarget?: string;
@@ -589,15 +591,15 @@ function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) {
589591
setExpanded((value) => !value);
590592
}
591593

592-
const handleCopy = useCallback((format: "markdown" | "csv") => {
594+
const handleCopy = useCallback((format: TableCopyFormat) => {
593595
const table = containerRef.current?.querySelector("table");
594596
if (!table || typeof navigator === "undefined" || navigator.clipboard == null) {
595597
return;
596598
}
597599
const text =
598600
format === "markdown"
599601
? serializeTableElementToMarkdown(table)
600-
: serializeTableElementToCsv(table);
602+
: serializeTableElementToDelimited(table, format);
601603
void navigator.clipboard
602604
.writeText(text)
603605
.then(() => {
@@ -676,6 +678,7 @@ function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) {
676678
</Tooltip>
677679
<MenuPopup align="end">
678680
<MenuItem onClick={() => handleCopy("markdown")}>Copy as Markdown</MenuItem>
681+
<MenuItem onClick={() => handleCopy("tsv")}>Copy as TSV</MenuItem>
679682
<MenuItem onClick={() => handleCopy("csv")}>Copy as CSV</MenuItem>
680683
</MenuPopup>
681684
</Menu>
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// @vitest-environment jsdom
2+
3+
import { describe, expect, it } from "vite-plus/test";
4+
5+
import { serializeTableElementToDelimited } from "./markdown-clipboard";
6+
7+
function renderTable(html: string): HTMLTableElement {
8+
const container = document.createElement("div");
9+
container.innerHTML = html;
10+
return container.querySelector("table")!;
11+
}
12+
13+
describe("serializeTableElementToDelimited", () => {
14+
const table = renderTable(`
15+
<table>
16+
<thead><tr><th>Question</th><th>Owner, team</th></tr></thead>
17+
<tbody>
18+
<tr><td></td><td>Platform</td></tr>
19+
<tr><td>first<br>second\tthird</td><td></td></tr>
20+
<tr><td><img alt="Build badge" src="b.svg"></td><td>say "ok"</td></tr>
21+
</tbody>
22+
</table>`);
23+
24+
it("keeps every cell in its column as tab-separated rows", () => {
25+
expect(serializeTableElementToDelimited(table, "tsv")).toBe(
26+
'Question\tOwner, team\n\tPlatform\nfirst second third\t\nBuild badge\tsay "ok"',
27+
);
28+
});
29+
30+
it("quotes CSV cells that contain commas or quotes", () => {
31+
expect(serializeTableElementToDelimited(table, "csv")).toBe(
32+
'Question,"Owner, team"\n,Platform\nfirst second third,\nBuild badge,"say ""ok"""',
33+
);
34+
});
35+
});

‎apps/web/src/markdown-clipboard.ts‎

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -346,22 +346,46 @@ export function serializeTableElementToMarkdown(table: Element): string {
346346
return serializeTable(table).trim();
347347
}
348348

349-
function csvCell(value: string): string {
349+
/** Collapses a cell to one line so it cannot break the row or column grid. */
350+
function delimitedCell(value: string, format: "tsv" | "csv"): string {
350351
const normalized = value.replace(/\s+/g, " ").trim();
352+
if (format === "tsv") return normalized;
351353
return /[",\n]/.test(normalized) ? `"${normalized.replaceAll('"', '""')}"` : normalized;
352354
}
353355

354-
export function serializeTableElementToCsv(table: Element): string {
355-
const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
356-
const lines: string[] = [];
357-
for (const row of rows) {
358-
const cells = [...row.children].filter(
359-
(cell) => cell.tagName === "TH" || cell.tagName === "TD",
360-
);
361-
if (cells.length === 0) continue;
362-
lines.push(cells.map((cell) => csvCell(cell.textContent ?? "")).join(","));
363-
}
364-
return lines.join("\n");
356+
function delimitedRows(rows: ReadonlyArray<ReadonlyArray<string>>, format: "tsv" | "csv"): string {
357+
const separator = format === "tsv" ? "\t" : ",";
358+
return rows
359+
.map((cells) => cells.map((cell) => delimitedCell(cell, format)).join(separator))
360+
.join("\n");
361+
}
362+
363+
/**
364+
* Cell text with `<br>` kept as a word boundary and images as their alt text,
365+
* both of which `textContent` drops.
366+
*/
367+
function tableCellText(node: Node): string {
368+
if (node.nodeType === Node.TEXT_NODE) return node.textContent ?? "";
369+
if (node.nodeType !== Node.ELEMENT_NODE) return "";
370+
const element = node as Element;
371+
if (element.tagName === "BR") return " ";
372+
if (element.tagName === "IMG") return element.getAttribute("alt") ?? "";
373+
return [...node.childNodes].map(tableCellText).join("");
374+
}
375+
376+
/**
377+
* Tab-separated rows are what spreadsheets put on the clipboard, and what Slack
378+
* and spreadsheet apps turn back into a real table on paste.
379+
*/
380+
export function serializeTableElementToDelimited(table: Element, format: "tsv" | "csv"): string {
381+
const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")]
382+
.map((row) =>
383+
[...row.children]
384+
.filter((cell) => cell.tagName === "TH" || cell.tagName === "TD")
385+
.map(tableCellText),
386+
)
387+
.filter((cells) => cells.length > 0);
388+
return delimitedRows(rows, format);
365389
}
366390

367391
function sanitizedHtmlFrom(container: Element): string {

0 commit comments

Comments
 (0)