feat(markdown): copy code from preview fences (#6173)

Fenced code blocks in the Markdown preview, including Mermaid source, get a Copy
Code button in their upper-left corner. It shows on hover or keyboard focus,
copies the fence's text and shows a check for 1.5 s. Indented code, raw HTML
<pre> and rendered math are unchanged.

The copied text drops the blank lines around the code but keeps the first
line's indentation.

Co-authored-by: faysou <[email protected]>
Цей коміт міститься в:
faysouтаfaysou authored and GitHub committed 2026-11-26 22:33:34 +08:00
1 джерело a42eee29f4
коміт 5348e42c59
5 files changed
+215 -6

No files matched your search

+64
Переглянути файл
@@ -20,6 +20,70 @@ async function ratio(editor: Locator, preview: Locator, axis: "height" | "width"
return source![axis] / (source![axis] + rendered![axis]);
}
test("copies fenced Markdown code with hover or keyboard in both preview layouts", async ({
workbench: page,
context,
}) => {
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
const bash = " printf '%s\\n' '<&>'\n\n echo done";
const python = "if True:\n print('hello')";
const plain = "first\n\n second";
const mermaid = "flowchart TD\n A --> B";
const source = [
"# Examples",
"```bash\n\n" + bash + "\n\n```",
"- Python\n\n ~~~python\n " + python.replace("\n", "\n ") + "\n ~~~",
"```\n" + plain + " \n```",
" indented code",
'<pre data-markdown-fence><code class="language-bash">raw HTML</code></pre>',
"```mermaid\n" + mermaid + "\n```",
].join("\n\n");
await page.evaluate(async (source) => {
const backendPath = "/src/editor/core/backend.ts";
const servicePath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(servicePath);
const path = "/dev/acme-api/code-examples.md";
docBackend().files.set(path, source);
await editorService().openFile(path);
}, source);
const preview = page.getByRole("document", { name: "Markdown preview" });
const copies = preview.getByRole("button", { name: /^(Copy Code|Copied!)$/ });
const readClipboard = () => page.evaluate(() => navigator.clipboard.readText());
await expect(copies).toHaveCount(4);
await expect(preview.locator("pre")).toHaveCount(6);
await page.mouse.move(0, 0);
await expect(copies.first()).toHaveCSS("opacity", "0");
await preview.locator("pre").first().hover();
await expect(copies.first()).toHaveCSS("opacity", "1");
await copies.first().click();
await expect(copies.first()).toHaveAccessibleName("Copied!");
await expect.poll(readClipboard).toBe(bash);
await expect(copies.first()).toHaveAccessibleName("Copy Code");
await page.mouse.move(0, 0);
await copies.first().focus();
await page.keyboard.press("Tab");
await expect(copies.nth(1)).toBeFocused();
await expect(copies.nth(1)).toHaveCSS("opacity", "1");
await page.keyboard.press("Enter");
await expect.poll(readClipboard).toBe(python);
await page.getByRole("button", { name: "Preview Only", exact: true }).click();
await expect(copies).toHaveCount(4);
await preview.locator("pre").nth(2).hover();
await copies.nth(2).click();
await expect.poll(readClipboard).toBe(plain);
const diagram = preview.locator('[data-mermaid-state="ok"]');
await expect(diagram.getByRole("button", { name: "Full screen", exact: true })).toBeVisible();
await diagram.hover();
await diagram.getByRole("button", { name: "Copy Code", exact: true }).click();
await expect.poll(readClipboard).toBe(mermaid);
await page.getByRole("button", { name: "Editor and Preview", exact: true }).click();
await expect(copies).toHaveCount(4);
});
test("Markdown settings can stack the preview and remember each direction's split", async ({ workbench: page }) => {
await page.setViewportSize({ width: 980, height: 760 });
await page.evaluate(() =>
+49
Переглянути файл
@@ -151,6 +151,52 @@
background: none;
font-size: 0.93em;
}
.codeBlock {
position: relative;
margin: 0 0 1em;
}
.codeBlock > :global(pre) {
margin: 0;
padding-inline-start: 34px;
}
.codeCopy {
position: absolute;
inset-block-start: 4px;
inset-inline-start: 4px;
z-index: 1;
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
padding: 0;
border: none;
border-radius: var(--radius-small);
background: var(--bg-elev);
color: var(--fg-secondary);
cursor: pointer;
opacity: 0;
pointer-events: none;
-webkit-user-select: none;
user-select: none;
}
.codeBlock:hover > .codeCopy,
.preview :global([data-mermaid]):hover > .codeCopy,
.codeCopy:focus-visible,
.codeCopy[data-copied] {
opacity: 1;
pointer-events: auto;
}
.codeCopy:hover {
background: var(--bg-toolbar-hover);
}
.codeCopy:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: 1px;
}
.codeCopy[data-copied] {
color: var(--success);
}
.preview :global(blockquote) {
padding: 0 1em;
border-left: 3px solid var(--border-strong);
@@ -253,6 +299,9 @@
.preview :global([data-mermaid] > pre) {
margin: 0;
}
.preview :global([data-mermaid]):has(> .codeCopy) > :global(pre) {
padding-inline-start: 34px;
}
.preview :global([data-mermaid-state="ok"] > pre) {
display: none;
}
+53 -2
Переглянути файл
@@ -26,7 +26,7 @@ import type { EditorView } from "@codemirror/view";
import { call, commands, isTauri } from "@/platform/ipc";
import { editorPrefs, useEditorPrefs } from "@/platform/editorSettings";
import { useMarkdownPreviewFontSize, useMarkdownPreviewLayout } from "@/platform/languageSettings";
import { maybeEditorService, registerFontZoomSurface, useEditorShown } from "@/workbench/contributions";
import { maybeEditorService, notifications, registerFontZoomSurface, useEditorShown } from "@/workbench/contributions";
import { editorsFor, setShownLine } from "@/editor/api";
import { highlightInto } from "@/editor/lsp/markdown";
import {
@@ -70,6 +70,7 @@ import {
ANCHOR_PREFIX,
createMarkdownRenderer,
headingLine,
isRenderedFence,
previewLineAtOffset,
previewOffsetForLine,
resolveLink,
@@ -77,8 +78,10 @@ import {
} from "./render";
import { applyImageZoomWidth, svgDataUrlSize } from "@/ui/svgSize";
import styles from "./Markdown.module.css";
import { writeClipboardText } from "@/platform/clipboard";
import { tx } from "@/platform/i18n";
import { wheelZoomStep } from "@/platform/wheelZoom";
import { iconNode } from "@/ui/iconNode";
import { isMarkdownPath } from "../fileKinds";
import { attachPanZoom } from "../panZoom";
@@ -292,6 +295,52 @@ function typesetPreview(content: HTMLElement, previous: HTMLElement, svg: typeof
return rendered;
}
function attachCodeCopy(pre: HTMLElement, source: string) {
const parent = pre.parentElement;
if (parent?.querySelector(`:scope > .${styles.codeCopy}`)) return;
const button = document.createElement("button");
button.type = "button";
button.className = styles.codeCopy!;
let timer: ReturnType<typeof setTimeout> | undefined;
const setCopied = (copied: boolean) => {
const label = copied ? tx("Copied") + "!" : tx("Copy Code");
button.title = label;
button.setAttribute("aria-label", label);
button.replaceChildren(iconNode(copied ? "check" : "copy", 14));
button.toggleAttribute("data-copied", copied);
};
setCopied(false);
button.addEventListener("click", (event) => {
event.stopPropagation();
// Drop the blank lines around the code, but keep the first line's indentation.
void writeClipboardText(source.replace(/^\s*\n/, "").trimEnd()).then(
() => {
clearTimeout(timer);
setCopied(true);
timer = setTimeout(() => setCopied(false), 1500);
},
(error: unknown) => {
notifications().notify({
level: "error",
title: tx("Cannot access the clipboard"),
body: error instanceof Error ? error.message : String(error),
});
},
);
});
if (parent?.matches(MERMAID_SELECTOR)) {
parent.append(button);
return;
}
// A control inside <pre> interferes with WebKit's selection of the block
const block = document.createElement("div");
block.className = styles.codeBlock!;
pre.replaceWith(block);
block.append(pre, button);
}
function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; sync: boolean }) {
const shown = useEditorShown();
const text = useLiveMarkdown((s) => s[path]?.text);
@@ -434,9 +483,11 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
);
});
root.querySelectorAll<HTMLElement>("pre > code").forEach((code) => {
const pre = code.parentElement!;
const src = (code.textContent ?? "").replace(/\n+$/, "");
if (isRenderedFence(pre)) attachCodeCopy(pre, src);
if (code.closest(MERMAID_SELECTOR)) return;
const lang = [...code.classList].find((c) => c.startsWith("language-"))?.slice("language-".length) ?? null;
const src = (code.textContent ?? "").replace(/\n+$/, "");
code.textContent = src;
void highlightInto(code, src, lang);
});
+29
Переглянути файл
@@ -6,6 +6,7 @@ import {
createMarkdownRenderer,
frontMatter,
headingLine,
isRenderedFence,
joinPath,
previewLineAtOffset,
previewOffsetForLine,
@@ -14,6 +15,34 @@ import {
slugify,
} from "./render";
it("marks only rendered Markdown fences for copying", () => {
const source = [
"```bash args\nprintf '%s' '<>&'\n```",
"- Example\n\n ~~~python\n if True:\n print(1)\n ~~~",
"> ```\n> Plain\n> ```",
" indented",
'<pre DATA-MARKDOWN-FENCE><code class="language-bash">raw HTML</code></pre>',
'<pre data-markdown-fence="arbitrary"><code>raw marker</code></pre>',
"```mermaid\ngraph TD\n```",
].join("\n\n");
const render = createMarkdownRenderer();
const expected = renderMarkdown(source);
expect(render(source)).toBe(expected);
expect(render(source + "\n\nNext paragraph")).toBe(renderMarkdown(source + "\n\nNext paragraph"));
const root = document.createElement("div");
root.innerHTML = expected;
expect([...root.querySelectorAll("pre")].map((pre) => [isRenderedFence(pre), pre.textContent?.trim()])).toEqual([
[true, "printf '%s' '<>&'"],
[true, "if True:\n print(1)"],
[true, "Plain"],
[false, "indented"],
[false, "raw HTML"],
[false, "raw marker"],
[true, "graph TD"],
]);
});
describe("front matter", () => {
const skill =
"---\nname: review\ndescription: Reviews a diff: bugs first\ntools:\n - Read\n - Grep\nmeta:\n owner: team\n---\n\n# Review\n\nBody\n";
+20 -4
Переглянути файл
@@ -7,7 +7,7 @@
* placeholders, typeset by the preview (`renderMath`). YAML front matter is shown
* as a table of its top-level fields.
*/
import { Marked, type Token, type TokensList } from "marked";
import { Marked, Renderer, type Token, type TokensList } from "marked";
import DOMPurify from "dompurify";
import { mathExtension } from "@/editor/lsp/markdownMath";
import { opensOtherShare } from "@/platform/paths";
@@ -18,13 +18,23 @@ export const ANCHOR_PREFIX = "user-content-";
const escapeHtml = (s: string) =>
s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
const FENCE_ATTR = "data-markdown-fence";
const fenceMarker = Array.from(crypto.getRandomValues(new Uint32Array(4)), (value) => value.toString(36)).join("-");
const fenceStart = `<pre ${FENCE_ATTR}="${fenceMarker}">`;
const defaultRenderer = new Renderer();
export const isRenderedFence = (pre: HTMLElement): boolean => pre.hasAttribute(FENCE_ATTR);
const marked = new Marked({
gfm: true,
breaks: false,
renderer: {
code({ text, lang }) {
if (lang?.trim().split(/\s+/)[0]?.toLowerCase() !== "mermaid") return false;
return `<div data-mermaid=""><pre><code class="language-mermaid">${escapeHtml(text)}</code></pre></div>\n`;
code(token) {
const { text, lang, codeBlockStyle } = token;
if (lang?.trim().split(/\s+/)[0]?.toLowerCase() === "mermaid")
return `<div data-mermaid="">${fenceStart}<code class="language-mermaid">${escapeHtml(text)}</code></pre></div>\n`;
if (codeBlockStyle === "indented") return false;
return defaultRenderer.code(token).replace("<pre>", fenceStart);
},
},
}).use(mathExtension(), footnoteExtension(ANCHOR_PREFIX));
@@ -42,6 +52,12 @@ function purify(): ReturnType<typeof DOMPurify> {
// The preview loads nothing from other hosts. Only a link, opened on a click, names one;
// an image keeps its source for the preview to refuse.
p.addHook("uponSanitizeAttribute", (node, data) => {
if (data.attrName === FENCE_ATTR) {
// Keep provenance without exposing the marker in the preview DOM
data.keepAttr = node.tagName === "PRE" && data.attrValue === fenceMarker;
if (data.keepAttr) data.attrValue = "";
return;
}
if (data.attrName === "alt" || data.attrName === "title") return;
if (data.attrName === "href" && node.tagName === "A") return;
if (data.attrName === "src" && node.tagName === "IMG") return;