Repository navigation
fix(web): render Mermaid diagrams in Markdown #6191
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
adamblumoff
wants to merge
5
commits into
pingdotgg:main
from
adamblumoff:fix/render-mermaid-markdown
Closed
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
bff4d26
fix(web): render Mermaid diagrams in Markdown
adamblumoff 2dc2a6a
fix(web): harden Mermaid rendering
adamblumoff f678425
fix(web): refresh Mermaid code block integration
adamblumoff 38e6fa6
fix(web): secure Mermaid directives and fallbacks
adamblumoff cf50ae5
fix(web): preserve Mermaid source selections
adamblumoff File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; | ||
|
|
||
| const mermaid = vi.hoisted(() => ({ | ||
| initialize: vi.fn(), | ||
| render: vi.fn(), | ||
| })); | ||
|
|
||
| vi.mock("mermaid", () => ({ default: mermaid })); | ||
|
|
||
| import { renderMermaidDiagram } from "./MermaidDiagram"; | ||
| import { serializeMarkdownCodeFence } from "../markdown-clipboard"; | ||
|
|
||
| describe("renderMermaidDiagram", () => { | ||
| beforeEach(() => { | ||
| mermaid.initialize.mockReset(); | ||
| mermaid.render.mockReset(); | ||
| }); | ||
|
|
||
| it("renders with strict security and the selected theme", async () => { | ||
| mermaid.render.mockResolvedValue({ svg: "<svg />" }); | ||
|
|
||
| await renderMermaidDiagram("diagram-1", "flowchart LR\nA-->B", "dark"); | ||
|
|
||
| expect(mermaid.initialize).toHaveBeenCalledWith({ | ||
| startOnLoad: false, | ||
| securityLevel: "strict", | ||
| suppressErrorRendering: true, | ||
| secure: [ | ||
| "secure", | ||
| "securityLevel", | ||
| "startOnLoad", | ||
| "maxTextSize", | ||
| "suppressErrorRendering", | ||
| "maxEdges", | ||
| "themeCSS", | ||
| "fontFamily", | ||
| "altFontFamily", | ||
| ], | ||
| theme: "dark", | ||
| }); | ||
| expect(mermaid.render).toHaveBeenCalledWith("diagram-1", "flowchart LR\nA-->B"); | ||
| }); | ||
|
|
||
| it("continues rendering after an invalid diagram", async () => { | ||
| mermaid.render | ||
| .mockRejectedValueOnce(new Error("Invalid diagram")) | ||
| .mockResolvedValueOnce({ svg: "<svg />" }); | ||
|
|
||
| await expect(renderMermaidDiagram("diagram-1", "invalid", "light")).rejects.toThrow(); | ||
| await expect( | ||
| renderMermaidDiagram("diagram-2", "sequenceDiagram\nA->>B: Hi", "light"), | ||
| ).resolves.toEqual({ svg: "<svg />" }); | ||
| }); | ||
|
|
||
| it("skips queued work after its diagram unmounts", async () => { | ||
| let finishFirstRender!: (result: { svg: string }) => void; | ||
| mermaid.render.mockImplementationOnce( | ||
| () => | ||
| new Promise((resolve) => { | ||
| finishFirstRender = resolve; | ||
| }), | ||
| ); | ||
|
|
||
| const first = renderMermaidDiagram("diagram-1", "flowchart LR\nA-->B", "light"); | ||
| await vi.waitFor(() => expect(mermaid.render).toHaveBeenCalledTimes(1)); | ||
| const second = renderMermaidDiagram("diagram-2", "flowchart LR\nB-->C", "light", () => false); | ||
| finishFirstRender({ svg: "<svg />" }); | ||
|
|
||
| await first; | ||
| await expect(second).resolves.toBeNull(); | ||
| expect(mermaid.render).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it("chooses a fence longer than backtick runs in copied source", () => { | ||
| expect(serializeMarkdownCodeFence("flowchart LR\n%% ``` in a comment", "mermaid")).toBe( | ||
| "````mermaid\nflowchart LR\n%% ``` in a comment\n````\n\n", | ||
| ); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| import { useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from "react"; | ||
| import type { RenderResult } from "mermaid"; | ||
|
|
||
| import { serializeMarkdownCodeFence } from "../markdown-clipboard"; | ||
|
|
||
| type MermaidTheme = "light" | "dark"; | ||
|
|
||
| // Mermaid configuration is global, so initialization and rendering must stay paired. | ||
| let mermaidRenderQueue = Promise.resolve(); | ||
|
|
||
| export function renderMermaidDiagram( | ||
| id: string, | ||
| code: string, | ||
| theme: MermaidTheme, | ||
| isActive: () => boolean = () => true, | ||
| ) { | ||
| const render = async () => { | ||
| if (!isActive()) return null; | ||
| const { default: mermaid } = await import("mermaid"); | ||
| if (!isActive()) return null; | ||
| mermaid.initialize({ | ||
| startOnLoad: false, | ||
| securityLevel: "strict", | ||
| suppressErrorRendering: true, | ||
| secure: [ | ||
| "secure", | ||
| "securityLevel", | ||
| "startOnLoad", | ||
| "maxTextSize", | ||
| "suppressErrorRendering", | ||
| "maxEdges", | ||
| "themeCSS", | ||
| "fontFamily", | ||
| "altFontFamily", | ||
| ], | ||
| theme: theme === "dark" ? "dark" : "default", | ||
| }); | ||
| return mermaid.render(id, code); | ||
| }; | ||
|
|
||
| const result = mermaidRenderQueue.then(render, render); | ||
| mermaidRenderQueue = result.then( | ||
| () => undefined, | ||
| () => undefined, | ||
| ); | ||
| return result; | ||
| } | ||
|
|
||
| export function MermaidDiagram({ | ||
| code, | ||
| theme, | ||
| fallback, | ||
| }: { | ||
| code: string; | ||
| theme: MermaidTheme; | ||
| fallback: ReactNode; | ||
| }) { | ||
| const reactId = useId(); | ||
| const diagramId = `t3-mermaid-${reactId.replace(/[^a-zA-Z0-9_-]/g, "")}`; | ||
| const renderSequenceRef = useRef(0); | ||
| const diagramRef = useRef<HTMLDivElement>(null); | ||
| const [renderedDiagram, setRenderedDiagram] = useState<{ | ||
| code: string; | ||
| theme: MermaidTheme; | ||
| result: RenderResult; | ||
| } | null>(null); | ||
|
|
||
| useEffect(() => { | ||
| let active = true; | ||
| const renderId = `${diagramId}-${renderSequenceRef.current++}`; | ||
| void renderMermaidDiagram(renderId, code, theme, () => active).then( | ||
| (nextResult) => { | ||
| if (active && nextResult) setRenderedDiagram({ code, theme, result: nextResult }); | ||
| }, | ||
| () => undefined, | ||
| ); | ||
| return () => { | ||
| active = false; | ||
| }; | ||
| }, [code, diagramId, theme]); | ||
|
|
||
| useLayoutEffect(() => { | ||
| const svg = diagramRef.current?.querySelector("svg"); | ||
| const width = svg?.viewBox.baseVal.width ?? 0; | ||
| if (svg && Number.isFinite(width) && width > 0) { | ||
| svg.style.width = `${Math.ceil(width)}px`; | ||
| svg.style.maxWidth = "none"; | ||
| } | ||
| }); | ||
|
|
||
| const result = | ||
| renderedDiagram?.code === code && renderedDiagram.theme === theme | ||
| ? renderedDiagram.result | ||
| : null; | ||
| if (!result) return fallback; | ||
|
|
||
| return ( | ||
| <div | ||
| ref={diagramRef} | ||
| className="chat-markdown-mermaid" | ||
| data-markdown-copy={serializeMarkdownCodeFence(code, "mermaid")} | ||
|
adamblumoff marked this conversation as resolved.
|
||
| dangerouslySetInnerHTML={{ __html: result.svg }} | ||
| /> | ||
|
adamblumoff marked this conversation as resolved.
cursor[bot] marked this conversation as resolved.
|
||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.