Skip to content

feat(preview): copy a Mermaid diagram as a PNG image - #1086

Merged
PathGao merged 1 commit into
masterfrom
feat/mermaid-copy-png
Nov 15, 2026
Merged

PathGao merged 1 commit into
masterfrom
feat/mermaid-copy-png

Conversation

@PathGao

@PathGao PathGao commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator

Mermaid diagrams in the preview could only be saved as SVG, which WeChat, Feishu, Word and PowerPoint don't paste. This adds a copy button in the diagram's top-right corner, the same one code blocks have, and a Copy Diagram As Image item in its context menu. Both put a PNG on the clipboard.

Mechanism

  • diagramToPngBase64 serializes the diagram's SVG, draws it onto a canvas at twice its viewBox size (longest side capped at 8192), and fills the preview's own background first. Mermaid leaves the background transparent, so a dark-theme diagram would otherwise paste as light text on white.
  • The PNG goes to a new clipboard_write_image command, which writes it through arboard the way clipboard_write_text does, including the X11 ownership hold from Copy doesn't work in the editor (paste works) #729. The webview's clipboard is not used.
  • Canvas export works because diagrams are drawn with htmlLabels: false, so there is no foreignObject to taint the canvas.
  • The button is added after every draw, because a theme change redraws the container's contents. It only appears when the caller passes onCopyDiagram, so exported HTML has none. It reuses .lang-label, so print already hides it. Its click stops propagation, so it doesn't also open the zoomed diagram.

Tests

preview.richContent.test.ts checks that a diagram keeps exactly one button through a theme redraw, that clicking it calls back without propagating, and that a render without the callback has no button. diagramImage.test.ts checks the 2× size and the cap.

Verification

  • npm run check, npm run lint, npm test (961 passed), npx vitest run (770 passed), vite build and check-startup-chunk, cargo fmt --check, cargo clippy -D warnings, cargo test --locked (249 passed), bindings regenerated.
  • In a macOS test build, the copied diagram pasted correctly.
  • Not run on Windows or Linux.

Closes #1085

A copy button in the diagram's top-right corner, like a code block's, and
a Copy Diagram As Image item in its context menu. The diagram is drawn at
twice its size on the preview's background and put on the clipboard through
arboard, the same path the text copy uses.
@PathGao
PathGao merged commit a353181 into master Nov 15, 2026
4 checks passed
@PathGao
PathGao deleted the feat/mermaid-copy-png branch November 16, 2026 06:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature Request: Copy Mermaid diagram as PNG image directly to clipboard

1 participant