Skip to content
TypeScript

fix(web): preserve Mermaid source when copying selected text (#16249)

Nikita Maximilian Grimmdd5876e157a5
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index a377301d8d1..fbba770f5b6 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -1128,7 +1128,7 @@ function MarkdownMermaidCodeBlock({
<MermaidDiagram source={code} theme={theme} onExpand={onExpand} />
</Suspense>
{searching ? (
- <pre ref={sourceRevealRef} hidden>
+ <pre ref={sourceRevealRef} hidden aria-hidden>
{code}
</pre>
) : null}
diff --git a/apps/web/src/components/chat/MermaidDiagram.tsx b/apps/web/src/components/chat/MermaidDiagram.tsx
index 17f21805292..2599c00d04d 100644
--- a/apps/web/src/components/chat/MermaidDiagram.tsx
+++ b/apps/web/src/components/chat/MermaidDiagram.tsx
@@ -2,6 +2,7 @@ import DOMPurify from "dompurify";
import type { Mermaid } from "mermaid";
import { use, useState } from "react";
+import { serializeCodeBlockToMarkdown } from "../../markdown-clipboard";
import { Button } from "../ui/button";
type MermaidRenderResult =
@@ -270,7 +271,11 @@ export function MermaidDiagram({
}
return (
- <div className="chat-markdown-mermaid overflow-x-auto">
+ <div
+ className="chat-markdown-mermaid overflow-x-auto"
+ data-markdown-mermaid=""
+ data-markdown-copy={serializeCodeBlockToMarkdown(source, "mermaid")}
+ >
<button
type="button"
aria-label="Expand diagram"
diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
index df1a612c1c1..734169da537 100644
--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
@@ -2,11 +2,17 @@ import { RegistryProvider } from "@effect/atom-react";
import {
ApprovalRequestId,
CheckpointRef,
+ ComposerContextId,
EnvironmentId,
MessageId,
RunId,
ThreadId,
} from "@t3tools/contracts";
+import {
+ COMPOSER_CONTEXT_CLIPBOARD_MIME,
+ decodeComposerContextClipboardHtml,
+ decodeComposerContextFragment,
+} from "@t3tools/shared/composerContextClipboard";
import type { LegendListRef } from "@legendapp/list/react";
import { act, createRef, Profiler, useState, type ComponentProps, type ReactElement } from "react";
import { createRoot, type Root } from "react-dom/client";
@@ -154,6 +160,7 @@ beforeEach(() => {
afterEach(async () => {
for (const root of roots.splice(0)) await act(async () => root.unmount());
+ window.getSelection()?.removeAllRanges();
document.body.replaceChildren();
vi.unstubAllGlobals();
});
@@ -173,6 +180,22 @@ function renderTimeline(entries: ReadonlyArray<Entry>, props: Partial<TimelinePr
);
}
+async function copyRange(range: Range) {
+ const selection = window.getSelection()!;
+ selection.removeAllRanges();
+ selection.addRange(range);
+ const clipboardData = new DataTransfer();
+ const event = new ClipboardEvent("copy", { bubbles: true, cancelable: true, clipboardData });
+ const target = range.startContainer.parentElement!;
+ try {
+ await act(async () => target.dispatchEvent(event));
+ expect(event.defaultPrevented).toBe(true);
+ return clipboardData;
+ } finally {
+ selection.removeAllRanges();
+ }
+}
+
function text() {
return container.textContent ?? "";
}
@@ -480,6 +503,121 @@ describe("MessagesTimeline work rows", () => {
});
describe("MessagesTimeline messages", () => {
+ it.each([
+ { role: "assistant", selection: "across", findExpanded: false },
+ { role: "assistant", selection: "across", findExpanded: true },
+ { role: "user", selection: "across", findExpanded: false },
+ { role: "assistant", selection: "inside", findExpanded: false },
+ { role: "user", selection: "source", findExpanded: false },
+ ] as const)(
+ "copies Mermaid selection $selection in $role messages (find expanded: $findExpanded)",
+ async ({ role, selection, findExpanded }) => {
+ const code = "flowchart LR\n A[Select message] --> B[Copy Markdown]";
+ const source = `\`\`\`mermaid\n${code}\n\`\`\``;
+ await renderTimeline([message(`Before diagram.\n\n${source}\n\nAfter diagram.`, { role })], {
+ findExpanded,
+ });
+ const diagram = await vi.waitFor(
+ () => {
+ const svg = container.querySelector('[aria-label="Expand diagram"] svg');
+ expect(svg).not.toBeNull();
+ return svg!;
+ },
+ { timeout: 10_000 },
+ );
+ const range = document.createRange();
+ let expected = source;
+ if (selection === "across") {
+ const paragraphs = [...container.querySelectorAll("p")];
+ const before = paragraphs.find((p) => p.textContent === "Before diagram.")!.firstChild!;
+ const after = paragraphs.find((p) => p.textContent === "After diagram.")!.firstChild!;
+ range.setStart(before, 2);
+ range.setEnd(after, 5);
+ expected = `fore diagram.\n\n${source}\n\nAfter`;
+ } else if (selection === "inside") {
+ const label = [...diagram.querySelectorAll("p, text")].find(
+ (element) => element.textContent === "Select message",
+ )!;
+ const labelText = document.createTreeWalker(label, NodeFilter.SHOW_TEXT).nextNode()!;
+ range.setStart(labelText, 2);
+ range.setEnd(labelText, 5);
+ } else {
+ await click(button("Show code"));
+ const code = container.querySelector("pre code")!;
+ const firstToken = document.createTreeWalker(code, NodeFilter.SHOW_TEXT).nextNode()!;
+ range.setStart(firstToken, 0);
+ range.setEnd(firstToken, 9);
+ expected = "flowchart";
+ }
+
+ const clipboard = await copyRange(range);
+ expect.soft(clipboard.getData("text/plain")).toBe(expected);
+ if (selection !== "source") {
+ const html = new DOMParser().parseFromString(clipboard.getData("text/html"), "text/html");
+ html.querySelectorAll("[hidden]").forEach((element) => element.remove());
+ expect(html.body.textContent).toContain(code);
+ }
+ },
+ );
+
+ it("exports context records only after selecting the chip, not its link in Mermaid source", async () => {
+ const record = {
+ version: 1 as const,
+ kind: "image" as const,
+ contextId: ComposerContextId.make("image-1"),
+ label: "shot.png",
+ attachmentId: "attachment-1",
+ name: "shot.png",
+ mimeType: "image/png",
+ sizeBytes: 1,
+ };
+ const link = `[shot.png](t3-context://v1/image/${record.contextId})`;
+ const code = `flowchart LR\n A --> B\n%% ${link}`;
+ const source = `\`\`\`mermaid\n${code}\n\`\`\``;
+ await renderTimeline([
+ message(`Before\n\n${source}\n\nAfter\n\n${link}`, {
+ context: { version: 1, records: [record] },
+ attachments: [
+ {
+ type: "image",
+ id: record.attachmentId,
+ name: record.name,
+ mimeType: record.mimeType,
+ sizeBytes: record.sizeBytes,
+ },
+ ],
+ }),
+ ]);
+ await vi.waitFor(
+ () => expect(container.querySelector('[aria-label="Expand diagram"] svg')).not.toBeNull(),
+ { timeout: 10_000 },
+ );
+ const paragraphs = [...container.querySelectorAll("p")];
+ const before = paragraphs.find((p) => p.textContent === "Before")!.firstChild!;
+ const after = paragraphs.find((p) => p.textContent === "After")!.firstChild!;
+ const chip = button(/^Image attachment, shot\.png,/);
+ const range = document.createRange();
+ range.setStart(before, 0);
+ range.setEnd(after, 5);
+
+ const withoutChip = await copyRange(range);
+ expect(withoutChip.getData("text/plain")).toBe(`Before\n\n${source}\n\nAfter`);
+ expect(withoutChip.getData(COMPOSER_CONTEXT_CLIPBOARD_MIME)).toBe("");
+ expect(decodeComposerContextClipboardHtml(withoutChip.getData("text/html"))).toBeNull();
+
+ range.setEndAfter(chip);
+ const withChip = await copyRange(range);
+ expect(withChip.getData("text/plain")).toBe(`Before\n\n${source}\n\nAfter\n\n!${link}`);
+ expect(
+ decodeComposerContextFragment(withChip.getData(COMPOSER_CONTEXT_CLIPBOARD_MIME))?.records,
+ ).toEqual([record]);
+ expect(decodeComposerContextClipboardHtml(withChip.getData("text/html"))?.records).toEqual([
+ record,
+ ]);
+ const html = new DOMParser().parseFromString(withChip.getData("text/html"), "text/html");
+ expect(html.body.textContent).toContain(code);
+ });
+
it("preserves XML-like tags and comparisons in user messages as text", async () => {
const source = [
'Without reading a file, do you have <global-agent-instructions scope="workspace">',
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index 21054547847..6f62eecd27e 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -2211,7 +2211,10 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
for (let index = 0; index < selection.rangeCount; index += 1) {
const container = document.createElement("div");
container.appendChild(selection.getRangeAt(index).cloneContents());
- for (const element of container.querySelectorAll("[data-markdown-copy]")) {
+ // Diagram source is copied text, not authority to export context records.
+ for (const element of container.querySelectorAll(
+ "[data-markdown-copy]:not([data-markdown-mermaid])",
+ )) {
copiedMarkdown.push(element.getAttribute("data-markdown-copy") ?? "");
}
}
diff --git a/apps/web/src/markdown-clipboard.ts b/apps/web/src/markdown-clipboard.ts
index 698aaf2952c..ada4bca9a1c 100644
--- a/apps/web/src/markdown-clipboard.ts
+++ b/apps/web/src/markdown-clipboard.ts
@@ -68,10 +68,14 @@ function resolveCodeBlockLanguage(pre: Element): string | null {
return declared && declared !== "text" ? declared : null;
}
-function serializeCodeBlock(pre: Element): string {
- const code = (pre.textContent ?? "").replace(/\n$/, "");
+export function serializeCodeBlockToMarkdown(source: string, language: string | null): string {
+ const code = source.replace(/\n$/, "");
const fence = codeFenceFor(code);
- return `${fence}${resolveCodeBlockLanguage(pre) ?? ""}\n${code}\n${fence}\n\n`;
+ return `${fence}${language ?? ""}\n${code}\n${fence}\n\n`;
+}
+
+function serializeCodeBlock(pre: Element): string {
+ return serializeCodeBlockToMarkdown(pre.textContent ?? "", resolveCodeBlockLanguage(pre));
}
function serializeTableCell(cell: Element): string {
@@ -360,6 +364,14 @@ export function serializeTableElementToCsv(table: Element): string {
return lines.join("\n");
}
+function mermaidSourceHtml(source: string) {
+ const pre = document.createElement("pre");
+ const code = document.createElement("code");
+ code.textContent = source.trim();
+ pre.appendChild(code);
+ return pre;
+}
+
function mathSourceElement(wrapper: Element): Element {
const code = document.createElement("code");
code.textContent = wrapper.getAttribute("data-markdown-copy")?.trim() ?? "";
@@ -370,6 +382,10 @@ function mathSourceElement(wrapper: Element): Element {
}
function sanitizedHtmlFrom(container: Element): string {
+ for (const diagram of container.querySelectorAll("[data-markdown-mermaid]")) {
+ const source = diagram.getAttribute("data-markdown-copy");
+ if (source !== null) diagram.replaceChildren(mermaidSourceHtml(source));
+ }
for (const wrapper of container.querySelectorAll(MATH_SELECTOR)) {
wrapper.replaceWith(mathSourceElement(wrapper));
}
@@ -401,6 +417,17 @@ export function chatMarkdownClipboardPayload(
const ancestor = range.commonAncestorContainer;
const ancestorElement =
ancestor.nodeType === Node.ELEMENT_NODE ? (ancestor as Element) : ancestor.parentElement;
+ const diagramSource = ancestorElement
+ ?.closest("[data-markdown-mermaid]")
+ ?.getAttribute("data-markdown-copy");
+ if (diagramSource != null) {
+ const text = diagramSource.trim();
+ if (!text) continue;
+ texts.push(text);
+ container.replaceChildren(mermaidSourceHtml(diagramSource));
+ htmls.push(sanitizedHtmlFrom(container));
+ continue;
+ }
// A range inside a formula would clone only KaTeX's glyphs, not the wrapper holding the TeX.
const math = mathWrapperOf(ancestorElement);
if (math) {