The best way to control Claude Code, Codex and more from any computer or phone
fix(web): copied Markdown tables keep formula pipes (#22875)
Nikita Maximilian Grimm committed
Oct 30, 2026 at 21:43 UTC
9ceb949a018fe4540b5fb67eea3d49f71ed47811
2 files changed
+147
-34
apps/web/src/markdown-clipboard.test.ts
+97
-1
@@ -1,11 +1,15 @@
1
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2
3
-import { serializeRenderedMarkdownFragment } from "./markdown-clipboard";
3
+import {
4
+ serializeRenderedMarkdownFragment,
5
+ serializeTableElementToMarkdown,
6
+} from "./markdown-clipboard";
7
import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
8
import {
9
collectAssistantCitations,
10
serializeAssistantCitation,
11
} from "@t3tools/shared/assistantCitations";
12
+import { markdownMathRanges, parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
13
14
const TEXT_NODE = 3;
15
const ELEMENT_NODE = 1;
@@ -95,6 +99,22 @@ class FakeElement {
99
};
100
return search(this);
101
}
102
+
103
+ /** Supports the `:scope > a > b` child paths the table serializer queries. */
104
+ querySelectorAll(selector: string): FakeElement[] {
105
+ return selector.split(", ").flatMap((part) =>
106
+ part
107
+ .replace(/^:scope > /, "")
108
+ .split(" > ")
109
+ .reduce<FakeElement[]>(
110
+ (level, tag) =>
111
+ level.flatMap((element) =>
112
+ element.children.filter((child) => child.tagName === tag.toUpperCase()),
113
+ ),
114
+ [this],
115
+ ),
116
+ );
117
+ }
118
}
119
120
function asNode(element: FakeElement): Node {
@@ -198,3 +218,79 @@ describe("serializeRenderedMarkdownFragment", () => {
218
);
219
});
220
});
221
+
222
+function renderedFormula(tex: string): FakeElement {
223
+ // MarkdownMath's wrapper; its children stand in for KaTeX's glyphs.
224
+ return new FakeElement("SPAN", [], {
225
+ "data-markdown-math": "inline",
226
+ "data-markdown-copy": `\\(${tex}\\)`,
227
+ }).append(new FakeText(tex));
228
+}
229
+
230
+function renderedTable(...rows: Array<Array<FakeElement | FakeText>>): FakeElement {
231
+ const row = (tag: string, cells: Array<FakeElement | FakeText>) =>
232
+ new FakeElement("TR").append(...cells.map((cell) => new FakeElement(tag).append(cell)));
233
+ const [head = [], ...body] = rows;
234
+ return new FakeElement("TABLE").append(
235
+ new FakeElement("THEAD").append(row("TH", head)),
236
+ new FakeElement("TBODY").append(...body.map((cells) => row("TD", cells))),
237
+ );
238
+}
239
+
240
+describe("copying rendered Markdown tables", () => {
241
+ beforeEach(() => {
242
+ vi.stubGlobal("Node", { TEXT_NODE, ELEMENT_NODE });
243
+ });
244
+
245
+ afterEach(() => {
246
+ vi.unstubAllGlobals();
247
+ });
248
+
249
+ it("keeps formula pipes as authored while escaping prose pipes", () => {
250
+ const table = renderedTable(
251
+ [new FakeText("Formula"), new FakeText("Note")],
252
+ [renderedFormula("|x|"), new FakeText("a | b")],
253
+ [renderedFormula("\\|x\\|"), new FakeElement("CODE").append(new FakeText("\\(c|d\\)"))],
254
+ [
255
+ new FakeElement("A", [], { href: "https://example.com/?q=a|b" }).append(
256
+ new FakeText("norm "),
257
+ renderedFormula("|y|"),
258
+ ),
259
+ new FakeText("e"),
260
+ ],
261
+ [
262
+ new FakeElement("UL").append(
263
+ new FakeElement("LI").append(renderedFormula("|z|"), new FakeText(" a | b")),
264
+ ),
265
+ new FakeElement("BLOCKQUOTE").append(new FakeElement("P").append(new FakeText("c | d"))),
266
+ ],
267
+ );
268
+ const markdown = serializeTableElementToMarkdown(table as unknown as Element);
269
+
270
+ const tree = parseMarkdownWithMath(markdown);
271
+ const parsed = tree.children[0];
272
+ if (parsed?.type !== "table") throw new Error("Expected a table");
273
+ expect(parsed.children.map((row) => row.children.length)).toEqual([2, 2, 2, 2, 2]);
274
+ expect(markdownMathRanges(markdown, tree).map((formula) => formula.tex)).toEqual([
275
+ "|x|",
276
+ "\\|x\\|",
277
+ "|y|",
278
+ "|z|",
279
+ ]);
280
+ expect(parsed.children[1]?.children[1]?.children).toMatchObject([
281
+ { type: "text", value: "a | b" },
282
+ ]);
283
+ expect(parsed.children[4]?.children[1]?.children).toMatchObject([
284
+ { type: "text", value: "> c | d" },
285
+ ]);
286
+ const [, , codeRow, linkRow] = parsed.children;
287
+ expect(codeRow?.children[1]?.children[0]).toMatchObject({
288
+ type: "inlineCode",
289
+ value: "\\(c|d\\)",
290
+ });
291
+ expect(linkRow?.children[0]?.children[0]).toMatchObject({
292
+ type: "link",
293
+ url: "https://example.com/?q=a|b",
294
+ });
295
+ });
296
+});
apps/web/src/markdown-clipboard.ts
+50
-33
@@ -76,7 +76,7 @@ function serializeCodeBlock(pre: Element): string {
76
}
77
78
function serializeTableCell(cell: Element): string {
79
- return serializeChildren(cell).replace(/\n+/g, " ").trim().replaceAll("|", "\\|");
79
+ return serializeChildren(cell, true).replace(/\n+/g, " ").trim();
80
}
81
82
function tableSeparatorFor(headerCells: Element[]): string {
@@ -108,14 +108,19 @@ function serializeTable(table: Element): string {
108
return `${lines.join("\n")}\n\n`;
109
}
110
111
-function serializeListItem(item: Element, ordered: boolean, index: number): string {
111
+function serializeListItem(
112
+ item: Element,
113
+ ordered: boolean,
114
+ index: number,
115
+ inTableCell: boolean,
116
+): string {
117
const checkbox = item.querySelector(
118
':scope > input[type="checkbox"], :scope > p > input[type="checkbox"]',
119
);
120
const task = checkbox ? `[${(checkbox as HTMLInputElement).checked ? "x" : " "}] ` : "";
121
const bullet = ordered ? `${index}. ` : "- ";
122
const marker = `${bullet}${task}`;
118
- let content = serializeChildren(item)
123
+ let content = serializeChildren(item, inTableCell)
124
.replace(/\n{3,}/g, "\n\n")
125
.trim();
126
if (!item.querySelector(":scope > p")) {
@@ -130,15 +135,15 @@ function serializeListItem(item: Element, ordered: boolean, index: number): stri
135
].join("\n");
136
}
137
133
-function serializeList(list: Element, ordered: boolean): string {
138
+function serializeList(list: Element, ordered: boolean, inTableCell: boolean): string {
139
const start = Number.parseInt(list.getAttribute("start") ?? "1", 10) || 1;
140
const items = [...list.children].filter((child) => child.tagName === "LI");
141
if (items.length === 0) return "";
137
- return `${items.map((item, index) => serializeListItem(item, ordered, start + index)).join("\n")}\n\n`;
142
+ return `${items.map((item, index) => serializeListItem(item, ordered, start + index, inTableCell)).join("\n")}\n\n`;
143
}
144
140
-function serializeBlockquote(quote: Element): string {
141
- const content = serializeChildren(quote)
145
+function serializeBlockquote(quote: Element, inTableCell: boolean): string {
146
+ const content = serializeChildren(quote, inTableCell)
147
.replace(/\n{3,}/g, "\n\n")
148
.trim();
149
if (!content) return "";
@@ -159,11 +164,11 @@ function serializeDetails(details: Element): string {
164
return `<details${open}>\n<summary>${summary}</summary>${content ? `\n\n${content}` : ""}\n</details>\n\n`;
165
}
166
162
-function serializeAnchor(anchor: Element): string {
167
+function serializeAnchor(anchor: Element, inTableCell: boolean): string {
168
const markdownCopy = anchor.getAttribute("data-markdown-copy");
164
- if (markdownCopy !== null) return markdownCopy;
165
- const content = serializeChildren(anchor);
166
- const href = anchor.getAttribute("href") ?? "";
169
+ if (markdownCopy !== null) return escapeTablePipes(markdownCopy, inTableCell);
170
+ const content = serializeChildren(anchor, inTableCell);
171
+ const href = escapeTablePipes(anchor.getAttribute("href") ?? "", inTableCell);
172
if (!/^https?:\/\//i.test(href)) return content;
173
const label = content.trim();
174
if (!label) return "";
@@ -171,32 +176,44 @@ function serializeAnchor(anchor: Element): string {
176
return `[${label}](${href})`;
177
}
178
174
-function serializeChildren(node: Node): string {
179
+/**
180
+ * GFM splits a table row at every unescaped pipe, but its math-aware parsing
181
+ * keeps a formula's pipes in the cell, so formula source is copied unescaped.
182
+ */
183
+function escapeTablePipes(text: string, inTableCell: boolean): string {
184
+ return inTableCell ? text.replaceAll("|", "\\|") : text;
185
+}
186
+
187
+function serializeChildren(node: Node, inTableCell = false): string {
188
let out = "";
189
for (const child of node.childNodes) {
177
- out += serializeNode(child);
190
+ out += serializeNode(child, inTableCell);
191
}
192
return out;
193
}
194
182
-function serializeNode(node: Node): string {
195
+function serializeNode(node: Node, inTableCell = false): string {
196
if (node.nodeType === Node.TEXT_NODE) {
197
const text = node.textContent ?? "";
198
if (text.includes("\n") && text.trim().length === 0) return "\n";
186
- return text;
199
+ return escapeTablePipes(text, inTableCell);
200
}
201
if (node.nodeType !== Node.ELEMENT_NODE) return "";
202
const element = node as Element;
203
if (element.hasAttribute("data-markdown-details")) {
191
- return serializeDetails(element);
204
+ return escapeTablePipes(serializeDetails(element), inTableCell);
205
}
206
const markdownCopy = element.getAttribute("data-markdown-copy");
194
- if (markdownCopy !== null) return markdownCopy;
207
+ if (markdownCopy !== null) {
208
+ return element.hasAttribute("data-markdown-math")
209
+ ? markdownCopy
210
+ : escapeTablePipes(markdownCopy, inTableCell);
211
+ }
212
if (isSkippedElement(element)) return "";
213
214
const headingLevel = /^H([1-6])$/.exec(element.tagName)?.[1];
215
if (headingLevel) {
199
- return `${"#".repeat(Number(headingLevel))} ${serializeChildren(element).trim()}\n\n`;
216
+ return `${"#".repeat(Number(headingLevel))} ${serializeChildren(element, inTableCell).trim()}\n\n`;
217
}
218
219
switch (element.tagName) {
@@ -205,45 +222,45 @@ function serializeNode(node: Node): string {
222
case "HR":
223
return "---\n\n";
224
case "P":
208
- return `${serializeChildren(element).trim()}\n\n`;
225
+ return `${serializeChildren(element, inTableCell).trim()}\n\n`;
226
case "PRE":
210
- return serializeCodeBlock(element);
227
+ return escapeTablePipes(serializeCodeBlock(element), inTableCell);
228
case "CODE": {
212
- const content = element.textContent ?? "";
229
+ const content = escapeTablePipes(element.textContent ?? "", inTableCell);
230
return isBlockCodeElement(element, content) ? content : wrapInlineCode(content);
231
}
232
case "STRONG":
233
case "B":
217
- return wrapInlineMarker(serializeChildren(element), "**");
234
+ return wrapInlineMarker(serializeChildren(element, inTableCell), "**");
235
case "EM":
236
case "I":
220
- return wrapInlineMarker(serializeChildren(element), "*");
237
+ return wrapInlineMarker(serializeChildren(element, inTableCell), "*");
238
case "DEL":
239
case "S":
223
- return wrapInlineMarker(serializeChildren(element), "~~");
240
+ return wrapInlineMarker(serializeChildren(element, inTableCell), "~~");
241
case "A":
225
- return serializeAnchor(element);
242
+ return serializeAnchor(element, inTableCell);
243
case "IMG": {
227
- const alt = element.getAttribute("alt") ?? "";
228
- const src = element.getAttribute("src") ?? "";
244
+ const alt = escapeTablePipes(element.getAttribute("alt") ?? "", inTableCell);
245
+ const src = escapeTablePipes(element.getAttribute("src") ?? "", inTableCell);
246
return alt && src ? `` : "";
247
}
248
case "UL":
232
- return serializeList(element, false);
249
+ return serializeList(element, false, inTableCell);
250
case "OL":
234
- return serializeList(element, true);
251
+ return serializeList(element, true, inTableCell);
252
case "BLOCKQUOTE":
236
- return serializeBlockquote(element);
253
+ return serializeBlockquote(element, inTableCell);
254
case "TABLE":
238
- return serializeTable(element);
255
+ return escapeTablePipes(serializeTable(element), inTableCell);
256
case "DIV":
257
case "SECTION":
258
case "ARTICLE": {
242
- const content = serializeChildren(element);
259
+ const content = serializeChildren(element, inTableCell);
260
return content && !content.endsWith("\n") ? `${content}\n` : content;
261
}
262
default:
246
- return serializeChildren(element);
263
+ return serializeChildren(element, inTableCell);
264
}
265
}
266