Skip to content

Commit 956a896

Browse files
committed
feat(web): copy a chat table as HTML
The table copy menu offered Markdown and CSV, but pasting a table into a mail client, wiki, or HTML editor needed a real table, not a text grid. Added serializeTableElementToHtml, which emits plain <table> markup with the header/body split and column alignment and no app chrome or class names. The new Copy as HTML menu item writes it as text/plain and also as the text/html flavor through writeTextToClipboard, so rich-paste targets receive a table while plain editors receive the source. serializeTableElementToCsv now shares the row and cell helpers. Tests cover the HTML output and CSV quoting. Model: Claude Fable 5.1. Harness: Claude Code via T3 Code.
1 parent 9375c77 commit 956a896

3 files changed

Lines changed: 162 additions & 23 deletions

File tree

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

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ import { getClientSettings, useClientSettings } from "../hooks/useSettings";
141141
import {
142142
chatMarkdownClipboardPayload,
143143
serializeTableElementToCsv,
144+
serializeTableElementToHtml,
144145
serializeTableElementToMarkdown,
145146
} from "../markdown-clipboard";
146147
import { remarkNormalizeListItemIndentation } from "../markdown-list-indentation";
@@ -333,10 +334,18 @@ const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/;
333334
const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
334335
const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
335336

337+
type TableCopyFormat = "markdown" | "csv" | "html";
338+
339+
const TABLE_COPY_SERIALIZERS: Record<TableCopyFormat, (table: Element) => string> = {
340+
markdown: serializeTableElementToMarkdown,
341+
csv: serializeTableElementToCsv,
342+
html: serializeTableElementToHtml,
343+
};
344+
336345
interface MarkdownActionFailureContext {
337346
readonly operation: string;
338347
readonly target?: string;
339-
readonly format?: "markdown" | "csv";
348+
readonly format?: TableCopyFormat;
340349
readonly language?: string;
341350
readonly fenceTitle?: string;
342351
readonly copyTarget?: string;
@@ -726,18 +735,15 @@ function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) {
726735
setExpanded((value) => !value);
727736
}
728737

729-
const handleCopy = useCallback((format: "markdown" | "csv") => {
738+
const handleCopy = useCallback((format: TableCopyFormat) => {
730739
const table = containerRef.current?.querySelector("table");
731-
if (!table || typeof navigator === "undefined" || navigator.clipboard == null) {
732-
return;
733-
}
734-
const text =
735-
format === "markdown"
736-
? serializeTableElementToMarkdown(table)
737-
: serializeTableElementToCsv(table);
738-
void navigator.clipboard
739-
.writeText(text)
740-
.then(() => {
740+
if (!table) return;
741+
const text = TABLE_COPY_SERIALIZERS[format](table);
742+
// HTML also rides the rich flavor so mail clients and editors paste a real table.
743+
const extraFlavors = format === "html" ? { "text/html": text } : undefined;
744+
void writeTextToClipboard(text, "table", extraFlavors)
745+
.then((didCopy) => {
746+
if (!didCopy) return;
741747
if (copiedTimerRef.current != null) {
742748
clearTimeout(copiedTimerRef.current);
743749
}
@@ -816,6 +822,7 @@ function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) {
816822
<MenuPopup align="end">
817823
<MenuItem onClick={() => handleCopy("markdown")}>Copy as Markdown</MenuItem>
818824
<MenuItem onClick={() => handleCopy("csv")}>Copy as CSV</MenuItem>
825+
<MenuItem onClick={() => handleCopy("html")}>Copy as HTML</MenuItem>
819826
</MenuPopup>
820827
</Menu>
821828
</div>

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

Lines changed: 86 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
22

3-
import { serializeRenderedMarkdownFragment } from "./markdown-clipboard";
3+
import {
4+
serializeRenderedMarkdownFragment,
5+
serializeTableElementToCsv,
6+
serializeTableElementToHtml,
7+
} from "./markdown-clipboard";
48
import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
59
import {
610
collectAssistantCitations,
@@ -82,6 +86,37 @@ class FakeElement {
8286
};
8387
return search(this);
8488
}
89+
90+
/** Supports only the `:scope > a > b, :scope > c` paths the table serializers ask for. */
91+
querySelectorAll(selector: string): FakeElement[] {
92+
const found: FakeElement[] = [];
93+
for (const path of selector.split(",")) {
94+
const tags = path.trim().replace(":scope > ", "").split(" > ");
95+
let level: FakeElement[] = [this];
96+
for (const tag of tags) {
97+
level = level.flatMap((element) =>
98+
element.children.filter((child) => child.tagName === tag.toUpperCase()),
99+
);
100+
}
101+
found.push(...level);
102+
}
103+
return found;
104+
}
105+
}
106+
107+
function tableRow(tag: "TH" | "TD", cells: ReadonlyArray<string | FakeElement>): FakeElement {
108+
return new FakeElement("TR").append(
109+
...cells.map((cell) =>
110+
cell instanceof FakeElement ? cell : new FakeElement(tag).append(new FakeText(cell)),
111+
),
112+
);
113+
}
114+
115+
function renderedTable(header: ReadonlyArray<string>, body: ReadonlyArray<ReadonlyArray<string>>) {
116+
return new FakeElement("TABLE").append(
117+
new FakeElement("THEAD").append(tableRow("TH", header)),
118+
new FakeElement("TBODY").append(...body.map((cells) => tableRow("TD", cells))),
119+
);
85120
}
86121

87122
function asNode(element: FakeElement): Node {
@@ -278,3 +313,53 @@ describe("serializeRenderedMarkdownFragment", () => {
278313
);
279314
});
280315
});
316+
317+
describe("serializeTableElementToHtml", () => {
318+
it("emits a clean table with header, body, escaping, and alignment", () => {
319+
const amount = new FakeElement("TD", [], { align: "right" }).append(new FakeText("1,200"));
320+
const table = renderedTable(
321+
["Name", "Amount"],
322+
[
323+
["A & B <Ltd>", "3"],
324+
["Bob", "unused"],
325+
],
326+
);
327+
table.querySelector("tbody")!.children[1]!.childNodes[1] = amount;
328+
329+
expect(serializeTableElementToHtml(asNode(table) as Element)).toBe(
330+
[
331+
"<table>",
332+
" <thead>",
333+
" <tr><th>Name</th><th>Amount</th></tr>",
334+
" </thead>",
335+
" <tbody>",
336+
" <tr><td>A &amp; B &lt;Ltd&gt;</td><td>3</td></tr>",
337+
' <tr><td>Bob</td><td style="text-align:right">1,200</td></tr>',
338+
" </tbody>",
339+
"</table>",
340+
].join("\n"),
341+
);
342+
});
343+
344+
it("keeps the first row in the body when it is not a header", () => {
345+
const table = new FakeElement("TABLE").append(tableRow("TD", ["only", "cells"]));
346+
347+
expect(serializeTableElementToHtml(asNode(table) as Element)).toBe(
348+
"<table>\n <tbody>\n <tr><td>only</td><td>cells</td></tr>\n </tbody>\n</table>",
349+
);
350+
});
351+
352+
it("returns an empty string for a table without rows", () => {
353+
expect(serializeTableElementToHtml(asNode(new FakeElement("TABLE")) as Element)).toBe("");
354+
});
355+
});
356+
357+
describe("serializeTableElementToCsv", () => {
358+
it("quotes cells containing commas or quotes", () => {
359+
const table = renderedTable(["Name", "Note"], [['Say "hi"', "a, b"]]);
360+
361+
expect(serializeTableElementToCsv(asNode(table) as Element)).toBe(
362+
'Name,Note\n"Say ""hi""","a, b"',
363+
);
364+
});
365+
});

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

Lines changed: 57 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -344,21 +344,68 @@ export function serializeTableElementToMarkdown(table: Element): string {
344344
return serializeTable(table).trim();
345345
}
346346

347+
/** Rows of the table's own cells; nested tables and empty rows are skipped. */
348+
function tableRows(table: Element): Element[][] {
349+
const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
350+
return rows
351+
.map((row) =>
352+
[...row.children].filter((cell) => cell.tagName === "TH" || cell.tagName === "TD"),
353+
)
354+
.filter((cells) => cells.length > 0);
355+
}
356+
357+
function cellText(cell: Element): string {
358+
return (cell.textContent ?? "").replace(/\s+/g, " ").trim();
359+
}
360+
347361
function csvCell(value: string): string {
348-
const normalized = value.replace(/\s+/g, " ").trim();
349-
return /[",\n]/.test(normalized) ? `"${normalized.replaceAll('"', '""')}"` : normalized;
362+
return /[",\n]/.test(value) ? `"${value.replaceAll('"', '""')}"` : value;
350363
}
351364

352365
export function serializeTableElementToCsv(table: Element): string {
353-
const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
354-
const lines: string[] = [];
355-
for (const row of rows) {
356-
const cells = [...row.children].filter(
357-
(cell) => cell.tagName === "TH" || cell.tagName === "TD",
358-
);
359-
if (cells.length === 0) continue;
360-
lines.push(cells.map((cell) => csvCell(cell.textContent ?? "")).join(","));
366+
return tableRows(table)
367+
.map((cells) => cells.map((cell) => csvCell(cellText(cell))).join(","))
368+
.join("\n");
369+
}
370+
371+
function escapeHtml(value: string): string {
372+
return value
373+
.replaceAll("&", "&amp;")
374+
.replaceAll("<", "&lt;")
375+
.replaceAll(">", "&gt;")
376+
.replaceAll('"', "&quot;");
377+
}
378+
379+
function htmlTableCell(cell: Element, tag: "th" | "td"): string {
380+
const align = (cell as HTMLElement).style?.textAlign ?? cell.getAttribute("align") ?? "";
381+
const attributes = align === "center" || align === "right" ? ` style="text-align:${align}"` : "";
382+
return `<${tag}${attributes}>${escapeHtml(cellText(cell))}</${tag}>`;
383+
}
384+
385+
/**
386+
* Plain `<table>` markup keeping the header/body split and column alignment,
387+
* without the app's chrome or class names, so it pastes as a real table into
388+
* mail clients, wikis, and HTML editors.
389+
*/
390+
export function serializeTableElementToHtml(table: Element): string {
391+
const rows = tableRows(table);
392+
const firstRow = rows[0];
393+
if (!firstRow) return "";
394+
const hasHeader = firstRow.every((cell) => cell.tagName === "TH");
395+
const bodyRows = hasHeader ? rows.slice(1) : rows;
396+
const lines = ["<table>"];
397+
if (hasHeader) {
398+
const header = firstRow.map((cell) => htmlTableCell(cell, "th")).join("");
399+
lines.push(" <thead>", ` <tr>${header}</tr>`, " </thead>");
400+
}
401+
if (bodyRows.length > 0) {
402+
lines.push(" <tbody>");
403+
for (const cells of bodyRows) {
404+
lines.push(` <tr>${cells.map((cell) => htmlTableCell(cell, "td")).join("")}</tr>`);
405+
}
406+
lines.push(" </tbody>");
361407
}
408+
lines.push("</table>");
362409
return lines.join("\n");
363410
}
364411

0 commit comments

Comments
 (0)