@devries-cameron20 / t3code Mirror · read-only / commits / 6f2ce81958
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 23:30 UTC

fix(web): copying commands with prose no longer adds code fences (#24433)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 11, 2026 at 11:53 UTC 6f2ce8195898c6207a86104c6919fb3efe26f0c0
2 files changed +88 -29
apps/web/src/markdown-clipboard.test.ts
+47 -5
@@ -1,6 +1,7 @@
1 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2
3 import {
4 + serializeCodeBlockToMarkdown,
5 serializeRenderedMarkdownFragment,
6 serializeTableElementToMarkdown,
7 } from "./markdown-clipboard";
@@ -209,13 +210,37 @@ describe("serializeRenderedMarkdownFragment", () => {
210 );
211 });
212
212 - it("keeps fences when a bare list item sits alongside the code block", () => {
213 + it("keeps a bare list item that sits alongside the code block", () => {
214 const container = new FakeElement("DIV").append(
215 new FakeElement("UL").append(new FakeElement("LI")),
216 renderedCodeBlock(["pnpm test"]),
217 );
218
218 - expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("-\n\n```\npnpm test\n```");
219 + expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("-\n\npnpm test");
220 + });
221 +
222 + it("copies a command and the prose after it as shown, without code fences", () => {
223 + const container = new FakeElement("DIV").append(
224 + renderedCodeBlock(["printf 'hello\\n'"]),
225 + new FakeElement("P").append(new FakeText("T")),
226 + );
227 +
228 + expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("printf 'hello\\n'\n\nT");
229 + });
230 +
231 + it("keeps a diagram's source exactly as written when copied with prose", () => {
232 + const source = 'flowchart TD\n A["first \n\n\nlast"]';
233 + const container = new FakeElement("DIV").append(
234 + new FakeElement("DIV", [], {
235 + "data-markdown-mermaid": "",
236 + "data-markdown-copy": serializeCodeBlockToMarkdown(source, "mermaid"),
237 + }),
238 + new FakeElement("P").append(new FakeText("After")),
239 + );
240 +
241 + expect(serializeRenderedMarkdownFragment(asNode(container))).toBe(
242 + `\`\`\`mermaid\n${source}\n\`\`\`\n\nAfter`,
243 + );
244 });
245
246 it("keeps blank lines inside a code block in a list item, quote, or longer fence", () => {
@@ -233,14 +258,14 @@ describe("serializeRenderedMarkdownFragment", () => {
258 );
259
260 expect(serializeRenderedMarkdownFragment(asNode(nestedFence))).toBe(
236 - "Example:\n\n````\n```js\na()\n\n\nb() \n```\n````",
261 + "Example:\n\n```js\na()\n\n\nb() \n```",
262 );
263
264 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(list)))).toBe(
240 - "1. Create it:\n ```\n import os\n\n\n def main():\n ```",
265 + "1. Create it:\n import os\n\n\n def main():",
266 );
267 expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(quote)))).toBe(
243 - "> Note:\n>\n> ```\n> import os\n>\n>\n> def main():\n> ```",
268 + "> Note:\n>\n> import os\n>\n>\n> def main():",
269 );
270 });
271
@@ -331,4 +356,21 @@ describe("copying rendered Markdown tables", () => {
356 url: "https://example.com/?q=a|b",
357 });
358 });
359 +
360 + it("copies code and diagrams in cells without markers or unescaped pipes", () => {
361 + const code = new FakeElement("PRE").append(
362 + new FakeElement("CODE").append(new FakeText("a b")),
363 + );
364 + const diagram = new FakeElement("DIV", [], {
365 + "data-markdown-mermaid": "",
366 + "data-markdown-copy": serializeCodeBlockToMarkdown("A -->|hi| B", "mermaid"),
367 + });
368 + expect(
369 + serializeTableElementToMarkdown(
370 + asNode(
371 + renderedTable([new FakeText("Command"), new FakeText("Diagram")], [code, diagram]),
372 + ) as Element,
373 + ),
374 + ).toBe("| Command | Diagram |\n| --- | --- |\n| a b | ```mermaid A -->\\|hi\\| B ``` |");
375 + });
376 });
apps/web/src/markdown-clipboard.ts
+41 -24
@@ -57,30 +57,32 @@ function codeFenceFor(code: string): string {
57 return "`".repeat(Math.max(3, longestRun + 1));
58 }
59
60 -function outsideCodeFences(markdown: string, tidy: (prose: string) => string): string {
61 - // A fence closes only at its own opening run, so split yields [prose, fence, run] triples.
62 - return markdown
63 - .split(/((`{3,})[\s\S]*?(?:\2|$))/)
64 - .map((part, index) => (index % 3 === 0 ? tidy(part) : index % 3 === 1 ? part : ""))
65 - .join("");
66 -}
67 -
68 -function resolveCodeBlockLanguage(pre: Element): string | null {
69 - const declared =
70 - pre.closest("[data-language]")?.getAttribute("data-language") ??
71 - /(?:^|\s)language-(\S+)/.exec(pre.querySelector("code")?.className ?? "")?.[1] ??
72 - null;
73 - return declared && declared !== "text" ? declared : null;
74 -}
75 -
60 export function serializeCodeBlockToMarkdown(source: string, language: string | null): string {
61 const code = source.replace(/\n$/, "");
62 const fence = codeFenceFor(code);
63 return `${fence}${language ?? ""}\n${code}\n${fence}\n\n`;
64 }
65
66 +// Brackets copied code so tidyMarkdown leaves its whitespace alone. Code is
67 +// copied as shown, without fences; DOM text from rendered markdown carries no NUL.
68 +const CODE_BOUNDARY = "\u0000";
69 +
70 +function verbatimBlock(code: string): string {
71 + return `${CODE_BOUNDARY}${code}${CODE_BOUNDARY}\n\n`;
72 +}
73 +
74 +// Odd parts are code and keep their markers, so outer passes still skip them.
75 +function outsideCode(markdown: string, tidy: (prose: string) => string): string {
76 + return markdown
77 + .split(CODE_BOUNDARY)
78 + .map((part, index) =>
79 + index % 2 === 1 ? `${CODE_BOUNDARY}${part}${CODE_BOUNDARY}` : tidy(part),
80 + )
81 + .join("");
82 +}
83 +
84 function serializeCodeBlock(pre: Element): string {
83 - return serializeCodeBlockToMarkdown(pre.textContent ?? "", resolveCodeBlockLanguage(pre));
85 + return verbatimBlock((pre.textContent ?? "").replace(/\n$/, ""));
86 }
87
88 function serializeTableCell(cell: Element): string {
@@ -128,11 +130,11 @@ function serializeListItem(
130 const task = checkbox ? `[${(checkbox as HTMLInputElement).checked ? "x" : " "}] ` : "";
131 const bullet = ordered ? `${index}. ` : "- ";
132 const marker = `${bullet}${task}`;
131 - let content = outsideCodeFences(serializeChildren(item, inTableCell), (prose) =>
133 + let content = outsideCode(serializeChildren(item, inTableCell), (prose) =>
134 prose.replace(/\n{3,}/g, "\n\n"),
135 ).trim();
136 if (!item.querySelector(":scope > p")) {
135 - content = outsideCodeFences(content, (prose) => prose.replace(/\n{2,}/g, "\n"));
137 + content = outsideCode(content, (prose) => prose.replace(/\n{2,}/g, "\n"));
138 }
139 // Continuations align after the bullet; task boxes belong to the item text.
140 const continuationIndent = " ".repeat(bullet.length);
@@ -158,7 +160,7 @@ function serializeList(list: Element, ordered: boolean, inTableCell: boolean): s
160 }
161
162 function serializeBlockquote(quote: Element, inTableCell: boolean): string {
161 - const content = outsideCodeFences(serializeChildren(quote, inTableCell), (prose) =>
163 + const content = outsideCode(serializeChildren(quote, inTableCell), (prose) =>
164 prose.replace(/\n{3,}/g, "\n\n"),
165 ).trim();
166 if (!content) return "";
@@ -220,6 +222,10 @@ function serializeNode(node: Node, inTableCell = false): string {
222 }
223 const markdownCopy = element.getAttribute("data-markdown-copy");
224 if (markdownCopy !== null) {
225 + // A diagram copies as its fenced source, which is code too.
226 + if (element.hasAttribute("data-markdown-mermaid")) {
227 + return verbatimBlock(escapeTablePipes(markdownCopy.trimEnd(), inTableCell));
228 + }
229 return element.hasAttribute("data-markdown-math")
230 ? markdownCopy
231 : escapeTablePipes(markdownCopy, inTableCell);
@@ -331,9 +337,19 @@ function soleCodeBlock(container: Node): Element | null {
337 }
338
339 function tidyMarkdown(markdown: string): string {
334 - return outsideCodeFences(markdown, (prose) =>
335 - prose.replace(/[ \t]+(?=\n)/g, "").replace(/\n{3,}/g, "\n\n"),
336 - ).trim();
340 + // Odd parts are code, kept verbatim, so a selection that starts or ends inside
341 + // code keeps that code's leading and trailing whitespace.
342 + const parts = markdown.split(CODE_BOUNDARY);
343 + const last = parts.length - 1;
344 + return parts
345 + .map((part, index) => {
346 + if (index % 2 === 1) return part;
347 + let prose = part.replace(/[ \t]+(?=\n)/g, "").replace(/\n{3,}/g, "\n\n");
348 + if (index === 0) prose = prose.trimStart();
349 + if (index === last) prose = prose.trimEnd();
350 + return prose;
351 + })
352 + .join("");
353 }
354
355 export function serializeRenderedMarkdownFragment(container: Node): string {
@@ -343,7 +359,8 @@ export function serializeRenderedMarkdownFragment(container: Node): string {
359 }
360
361 export function serializeTableElementToMarkdown(table: Element): string {
346 - return serializeTable(table).trim();
362 + // Raw HTML can put a pre in a cell; with no tidy pass here, drop its markers.
363 + return serializeTable(table).replaceAll(CODE_BOUNDARY, "").trim();
364 }
365
366 // The wrapper MarkdownMath puts on every formula it renders. The sanitizer drops