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 22, 23:15 UTC
fix(web): preserve Mermaid source when copying selected text (#16249)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Nikita Maximilian Grimm committed
Oct 20, 2026 at 06:55 UTC
dd5876e157a57792f325d72aec710ffdf9914505
5 files changed
+179
-6
apps/web/src/components/ChatMarkdown.tsx
+1
-1
@@ -1128,7 +1128,7 @@ function MarkdownMermaidCodeBlock({
1128
<MermaidDiagram source={code} theme={theme} onExpand={onExpand} />
1129
</Suspense>
1130
{searching ? (
1131
- <pre ref={sourceRevealRef} hidden>
1131
+ <pre ref={sourceRevealRef} hidden aria-hidden>
1132
{code}
1133
</pre>
1134
) : null}
apps/web/src/components/chat/MermaidDiagram.tsx
+6
-1
@@ -2,6 +2,7 @@ import DOMPurify from "dompurify";
2
import type { Mermaid } from "mermaid";
3
import { use, useState } from "react";
4
5
+import { serializeCodeBlockToMarkdown } from "../../markdown-clipboard";
6
import { Button } from "../ui/button";
7
8
type MermaidRenderResult =
@@ -270,7 +271,11 @@ export function MermaidDiagram({
271
}
272
273
return (
273
- <div className="chat-markdown-mermaid overflow-x-auto">
274
+ <div
275
+ className="chat-markdown-mermaid overflow-x-auto"
276
+ data-markdown-mermaid=""
277
+ data-markdown-copy={serializeCodeBlockToMarkdown(source, "mermaid")}
278
+ >
279
<button
280
type="button"
281
aria-label="Expand diagram"
apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+138
@@ -2,11 +2,17 @@ import { RegistryProvider } from "@effect/atom-react";
2
import {
3
ApprovalRequestId,
4
CheckpointRef,
5
+ ComposerContextId,
6
EnvironmentId,
7
MessageId,
8
RunId,
9
ThreadId,
10
} from "@t3tools/contracts";
11
+import {
12
+ COMPOSER_CONTEXT_CLIPBOARD_MIME,
13
+ decodeComposerContextClipboardHtml,
14
+ decodeComposerContextFragment,
15
+} from "@t3tools/shared/composerContextClipboard";
16
import type { LegendListRef } from "@legendapp/list/react";
17
import { act, createRef, Profiler, useState, type ComponentProps, type ReactElement } from "react";
18
import { createRoot, type Root } from "react-dom/client";
@@ -154,6 +160,7 @@ beforeEach(() => {
160
161
afterEach(async () => {
162
for (const root of roots.splice(0)) await act(async () => root.unmount());
163
+ window.getSelection()?.removeAllRanges();
164
document.body.replaceChildren();
165
vi.unstubAllGlobals();
166
});
@@ -173,6 +180,22 @@ function renderTimeline(entries: ReadonlyArray<Entry>, props: Partial<TimelinePr
180
);
181
}
182
183
+async function copyRange(range: Range) {
184
+ const selection = window.getSelection()!;
185
+ selection.removeAllRanges();
186
+ selection.addRange(range);
187
+ const clipboardData = new DataTransfer();
188
+ const event = new ClipboardEvent("copy", { bubbles: true, cancelable: true, clipboardData });
189
+ const target = range.startContainer.parentElement!;
190
+ try {
191
+ await act(async () => target.dispatchEvent(event));
192
+ expect(event.defaultPrevented).toBe(true);
193
+ return clipboardData;
194
+ } finally {
195
+ selection.removeAllRanges();
196
+ }
197
+}
198
+
199
function text() {
200
return container.textContent ?? "";
201
}
@@ -480,6 +503,121 @@ describe("MessagesTimeline work rows", () => {
503
});
504
505
describe("MessagesTimeline messages", () => {
506
+ it.each([
507
+ { role: "assistant", selection: "across", findExpanded: false },
508
+ { role: "assistant", selection: "across", findExpanded: true },
509
+ { role: "user", selection: "across", findExpanded: false },
510
+ { role: "assistant", selection: "inside", findExpanded: false },
511
+ { role: "user", selection: "source", findExpanded: false },
512
+ ] as const)(
513
+ "copies Mermaid selection $selection in $role messages (find expanded: $findExpanded)",
514
+ async ({ role, selection, findExpanded }) => {
515
+ const code = "flowchart LR\n A[Select message] --> B[Copy Markdown]";
516
+ const source = `\`\`\`mermaid\n${code}\n\`\`\``;
517
+ await renderTimeline([message(`Before diagram.\n\n${source}\n\nAfter diagram.`, { role })], {
518
+ findExpanded,
519
+ });
520
+ const diagram = await vi.waitFor(
521
+ () => {
522
+ const svg = container.querySelector('[aria-label="Expand diagram"] svg');
523
+ expect(svg).not.toBeNull();
524
+ return svg!;
525
+ },
526
+ { timeout: 10_000 },
527
+ );
528
+ const range = document.createRange();
529
+ let expected = source;
530
+ if (selection === "across") {
531
+ const paragraphs = [...container.querySelectorAll("p")];
532
+ const before = paragraphs.find((p) => p.textContent === "Before diagram.")!.firstChild!;
533
+ const after = paragraphs.find((p) => p.textContent === "After diagram.")!.firstChild!;
534
+ range.setStart(before, 2);
535
+ range.setEnd(after, 5);
536
+ expected = `fore diagram.\n\n${source}\n\nAfter`;
537
+ } else if (selection === "inside") {
538
+ const label = [...diagram.querySelectorAll("p, text")].find(
539
+ (element) => element.textContent === "Select message",
540
+ )!;
541
+ const labelText = document.createTreeWalker(label, NodeFilter.SHOW_TEXT).nextNode()!;
542
+ range.setStart(labelText, 2);
543
+ range.setEnd(labelText, 5);
544
+ } else {
545
+ await click(button("Show code"));
546
+ const code = container.querySelector("pre code")!;
547
+ const firstToken = document.createTreeWalker(code, NodeFilter.SHOW_TEXT).nextNode()!;
548
+ range.setStart(firstToken, 0);
549
+ range.setEnd(firstToken, 9);
550
+ expected = "flowchart";
551
+ }
552
+
553
+ const clipboard = await copyRange(range);
554
+ expect.soft(clipboard.getData("text/plain")).toBe(expected);
555
+ if (selection !== "source") {
556
+ const html = new DOMParser().parseFromString(clipboard.getData("text/html"), "text/html");
557
+ html.querySelectorAll("[hidden]").forEach((element) => element.remove());
558
+ expect(html.body.textContent).toContain(code);
559
+ }
560
+ },
561
+ );
562
+
563
+ it("exports context records only after selecting the chip, not its link in Mermaid source", async () => {
564
+ const record = {
565
+ version: 1 as const,
566
+ kind: "image" as const,
567
+ contextId: ComposerContextId.make("image-1"),
568
+ label: "shot.png",
569
+ attachmentId: "attachment-1",
570
+ name: "shot.png",
571
+ mimeType: "image/png",
572
+ sizeBytes: 1,
573
+ };
574
+ const link = `[shot.png](t3-context://v1/image/${record.contextId})`;
575
+ const code = `flowchart LR\n A --> B\n%% ${link}`;
576
+ const source = `\`\`\`mermaid\n${code}\n\`\`\``;
577
+ await renderTimeline([
578
+ message(`Before\n\n${source}\n\nAfter\n\n${link}`, {
579
+ context: { version: 1, records: [record] },
580
+ attachments: [
581
+ {
582
+ type: "image",
583
+ id: record.attachmentId,
584
+ name: record.name,
585
+ mimeType: record.mimeType,
586
+ sizeBytes: record.sizeBytes,
587
+ },
588
+ ],
589
+ }),
590
+ ]);
591
+ await vi.waitFor(
592
+ () => expect(container.querySelector('[aria-label="Expand diagram"] svg')).not.toBeNull(),
593
+ { timeout: 10_000 },
594
+ );
595
+ const paragraphs = [...container.querySelectorAll("p")];
596
+ const before = paragraphs.find((p) => p.textContent === "Before")!.firstChild!;
597
+ const after = paragraphs.find((p) => p.textContent === "After")!.firstChild!;
598
+ const chip = button(/^Image attachment, shot\.png,/);
599
+ const range = document.createRange();
600
+ range.setStart(before, 0);
601
+ range.setEnd(after, 5);
602
+
603
+ const withoutChip = await copyRange(range);
604
+ expect(withoutChip.getData("text/plain")).toBe(`Before\n\n${source}\n\nAfter`);
605
+ expect(withoutChip.getData(COMPOSER_CONTEXT_CLIPBOARD_MIME)).toBe("");
606
+ expect(decodeComposerContextClipboardHtml(withoutChip.getData("text/html"))).toBeNull();
607
+
608
+ range.setEndAfter(chip);
609
+ const withChip = await copyRange(range);
610
+ expect(withChip.getData("text/plain")).toBe(`Before\n\n${source}\n\nAfter\n\n!${link}`);
611
+ expect(
612
+ decodeComposerContextFragment(withChip.getData(COMPOSER_CONTEXT_CLIPBOARD_MIME))?.records,
613
+ ).toEqual([record]);
614
+ expect(decodeComposerContextClipboardHtml(withChip.getData("text/html"))?.records).toEqual([
615
+ record,
616
+ ]);
617
+ const html = new DOMParser().parseFromString(withChip.getData("text/html"), "text/html");
618
+ expect(html.body.textContent).toContain(code);
619
+ });
620
+
621
it("preserves XML-like tags and comparisons in user messages as text", async () => {
622
const source = [
623
'Without reading a file, do you have <global-agent-instructions scope="workspace">',
apps/web/src/components/chat/MessagesTimeline.tsx
+4
-1
@@ -2211,7 +2211,10 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
2211
for (let index = 0; index < selection.rangeCount; index += 1) {
2212
const container = document.createElement("div");
2213
container.appendChild(selection.getRangeAt(index).cloneContents());
2214
- for (const element of container.querySelectorAll("[data-markdown-copy]")) {
2214
+ // Diagram source is copied text, not authority to export context records.
2215
+ for (const element of container.querySelectorAll(
2216
+ "[data-markdown-copy]:not([data-markdown-mermaid])",
2217
+ )) {
2218
copiedMarkdown.push(element.getAttribute("data-markdown-copy") ?? "");
2219
}
2220
}
apps/web/src/markdown-clipboard.ts
+30
-3
@@ -68,10 +68,14 @@ function resolveCodeBlockLanguage(pre: Element): string | null {
68
return declared && declared !== "text" ? declared : null;
69
}
70
71
-function serializeCodeBlock(pre: Element): string {
72
- const code = (pre.textContent ?? "").replace(/\n$/, "");
71
+export function serializeCodeBlockToMarkdown(source: string, language: string | null): string {
72
+ const code = source.replace(/\n$/, "");
73
const fence = codeFenceFor(code);
74
- return `${fence}${resolveCodeBlockLanguage(pre) ?? ""}\n${code}\n${fence}\n\n`;
74
+ return `${fence}${language ?? ""}\n${code}\n${fence}\n\n`;
75
+}
76
+
77
+function serializeCodeBlock(pre: Element): string {
78
+ return serializeCodeBlockToMarkdown(pre.textContent ?? "", resolveCodeBlockLanguage(pre));
79
}
80
81
function serializeTableCell(cell: Element): string {
@@ -360,6 +364,14 @@ export function serializeTableElementToCsv(table: Element): string {
364
return lines.join("\n");
365
}
366
367
+function mermaidSourceHtml(source: string) {
368
+ const pre = document.createElement("pre");
369
+ const code = document.createElement("code");
370
+ code.textContent = source.trim();
371
+ pre.appendChild(code);
372
+ return pre;
373
+}
374
+
375
function mathSourceElement(wrapper: Element): Element {
376
const code = document.createElement("code");
377
code.textContent = wrapper.getAttribute("data-markdown-copy")?.trim() ?? "";
@@ -370,6 +382,10 @@ function mathSourceElement(wrapper: Element): Element {
382
}
383
384
function sanitizedHtmlFrom(container: Element): string {
385
+ for (const diagram of container.querySelectorAll("[data-markdown-mermaid]")) {
386
+ const source = diagram.getAttribute("data-markdown-copy");
387
+ if (source !== null) diagram.replaceChildren(mermaidSourceHtml(source));
388
+ }
389
for (const wrapper of container.querySelectorAll(MATH_SELECTOR)) {
390
wrapper.replaceWith(mathSourceElement(wrapper));
391
}
@@ -401,6 +417,17 @@ export function chatMarkdownClipboardPayload(
417
const ancestor = range.commonAncestorContainer;
418
const ancestorElement =
419
ancestor.nodeType === Node.ELEMENT_NODE ? (ancestor as Element) : ancestor.parentElement;
420
+ const diagramSource = ancestorElement
421
+ ?.closest("[data-markdown-mermaid]")
422
+ ?.getAttribute("data-markdown-copy");
423
+ if (diagramSource != null) {
424
+ const text = diagramSource.trim();
425
+ if (!text) continue;
426
+ texts.push(text);
427
+ container.replaceChildren(mermaidSourceHtml(diagramSource));
428
+ htmls.push(sanitizedHtmlFrom(container));
429
+ continue;
430
+ }
431
// A range inside a formula would clone only KaTeX's glyphs, not the wrapper holding the TeX.
432
const math = mathWrapperOf(ancestorElement);
433
if (math) {