Skip to content

Commit dd5876e

Browse files
fix(web): preserve Mermaid source when copying selected text (pingdotgg#16249)
Co-authored-by: Julius Marminge <[email protected]>
1 parent 9a05676 commit dd5876e

5 files changed

Lines changed: 179 additions & 6 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1128,7 +1128,7 @@ function MarkdownMermaidCodeBlock({
11281128
<MermaidDiagram source={code} theme={theme} onExpand={onExpand} />
11291129
</Suspense>
11301130
{searching ? (
1131-
<pre ref={sourceRevealRef} hidden>
1131+
<pre ref={sourceRevealRef} hidden aria-hidden>
11321132
{code}
11331133
</pre>
11341134
) : null}

‎apps/web/src/components/chat/MermaidDiagram.tsx‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import DOMPurify from "dompurify";
22
import type { Mermaid } from "mermaid";
33
import { use, useState } from "react";
44

5+
import { serializeCodeBlockToMarkdown } from "../../markdown-clipboard";
56
import { Button } from "../ui/button";
67

78
type MermaidRenderResult =
@@ -270,7 +271,11 @@ export function MermaidDiagram({
270271
}
271272

272273
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+
>
274279
<button
275280
type="button"
276281
aria-label="Expand diagram"

‎apps/web/src/components/chat/MessagesTimeline.browser.test.tsx‎

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,17 @@ import { RegistryProvider } from "@effect/atom-react";
22
import {
33
ApprovalRequestId,
44
CheckpointRef,
5+
ComposerContextId,
56
EnvironmentId,
67
MessageId,
78
RunId,
89
ThreadId,
910
} from "@t3tools/contracts";
11+
import {
12+
COMPOSER_CONTEXT_CLIPBOARD_MIME,
13+
decodeComposerContextClipboardHtml,
14+
decodeComposerContextFragment,
15+
} from "@t3tools/shared/composerContextClipboard";
1016
import type { LegendListRef } from "@legendapp/list/react";
1117
import { act, createRef, Profiler, useState, type ComponentProps, type ReactElement } from "react";
1218
import { createRoot, type Root } from "react-dom/client";
@@ -154,6 +160,7 @@ beforeEach(() => {
154160

155161
afterEach(async () => {
156162
for (const root of roots.splice(0)) await act(async () => root.unmount());
163+
window.getSelection()?.removeAllRanges();
157164
document.body.replaceChildren();
158165
vi.unstubAllGlobals();
159166
});
@@ -173,6 +180,22 @@ function renderTimeline(entries: ReadonlyArray<Entry>, props: Partial<TimelinePr
173180
);
174181
}
175182

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+
176199
function text() {
177200
return container.textContent ?? "";
178201
}
@@ -480,6 +503,121 @@ describe("MessagesTimeline work rows", () => {
480503
});
481504

482505
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+
483621
it("preserves XML-like tags and comparisons in user messages as text", async () => {
484622
const source = [
485623
'Without reading a file, do you have <global-agent-instructions scope="workspace">',

‎apps/web/src/components/chat/MessagesTimeline.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2211,7 +2211,10 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
22112211
for (let index = 0; index < selection.rangeCount; index += 1) {
22122212
const container = document.createElement("div");
22132213
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+
)) {
22152218
copiedMarkdown.push(element.getAttribute("data-markdown-copy") ?? "");
22162219
}
22172220
}

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

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,10 +68,14 @@ function resolveCodeBlockLanguage(pre: Element): string | null {
6868
return declared && declared !== "text" ? declared : null;
6969
}
7070

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$/, "");
7373
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));
7579
}
7680

7781
function serializeTableCell(cell: Element): string {
@@ -360,6 +364,14 @@ export function serializeTableElementToCsv(table: Element): string {
360364
return lines.join("\n");
361365
}
362366

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+
363375
function mathSourceElement(wrapper: Element): Element {
364376
const code = document.createElement("code");
365377
code.textContent = wrapper.getAttribute("data-markdown-copy")?.trim() ?? "";
@@ -370,6 +382,10 @@ function mathSourceElement(wrapper: Element): Element {
370382
}
371383

372384
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+
}
373389
for (const wrapper of container.querySelectorAll(MATH_SELECTOR)) {
374390
wrapper.replaceWith(mathSourceElement(wrapper));
375391
}
@@ -401,6 +417,17 @@ export function chatMarkdownClipboardPayload(
401417
const ancestor = range.commonAncestorContainer;
402418
const ancestorElement =
403419
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+
}
404431
// A range inside a formula would clone only KaTeX's glyphs, not the wrapper holding the TeX.
405432
const math = mathWrapperOf(ancestorElement);
406433
if (math) {

0 commit comments

Comments
 (0)