Repository navigation
feat(web): render mermaid diagrams in pull request bodies #13646
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
+1,012
−23
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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,44 @@ | ||
| import { useEffect, useState, type ReactNode } from "react"; | ||
|
|
||
| import { getCachedMermaidSvg, renderMermaidSvg, type MermaidTheme } from "~/lib/mermaid"; | ||
|
|
||
| /** | ||
| * Draws `code` as a mermaid diagram, the way GitHub does. Shows `children`, the highlighted | ||
| * source, when `code` is null, while the diagram renders, or when mermaid cannot parse it. | ||
| */ | ||
| export function MermaidDiagram({ | ||
| code, | ||
| theme, | ||
| children, | ||
| }: { | ||
| code: string | null; | ||
| theme: MermaidTheme; | ||
| children: ReactNode; | ||
| }) { | ||
| const key = `${theme}\n${code}`; | ||
| const [resolved, setResolved] = useState<{ key: string; svg: string | null } | null>(null); | ||
| // A cache hit draws on the first frame, so remounting a scrolled body does not flash. | ||
| const cached = code === null ? null : getCachedMermaidSvg(code, theme); | ||
| const svg = cached ?? (resolved?.key === key ? resolved.svg : null); | ||
|
|
||
| useEffect(() => { | ||
| if (code === null || cached != null) return; | ||
| let cancelled = false; | ||
| void renderMermaidSvg(code, theme).then( | ||
| (rendered) => !cancelled && setResolved({ key, svg: rendered }), | ||
| () => !cancelled && setResolved({ key, svg: null }), | ||
| ); | ||
| return () => { | ||
| cancelled = true; | ||
| }; | ||
| }, [cached, code, key, theme]); | ||
|
|
||
| if (svg === null) return children; | ||
| return ( | ||
| <div | ||
| className="chat-markdown-mermaid flex justify-center overflow-x-auto px-3 pt-1 pb-3" | ||
| // Mermaid runs its own DOMPurify pass at the `strict` security level set in lib/mermaid. | ||
| dangerouslySetInnerHTML={{ __html: svg }} | ||
| /> | ||
| ); | ||
| } | ||
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,67 @@ | ||
| import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; | ||
|
|
||
| const mocks = vi.hoisted(() => ({ | ||
| initialize: vi.fn(), | ||
| render: vi.fn(), | ||
| })); | ||
|
|
||
| vi.mock("mermaid", () => ({ | ||
| default: { initialize: mocks.initialize, render: mocks.render }, | ||
| })); | ||
|
|
||
| const { getCachedMermaidSvg, renderMermaidSvg } = await import("./mermaid"); | ||
|
|
||
| beforeEach(() => { | ||
| mocks.initialize.mockClear(); | ||
| mocks.render.mockClear(); | ||
| mocks.render.mockImplementation((_id: string, code: string) => | ||
| Promise.resolve({ svg: `<svg data-code="${code}" />` }), | ||
| ); | ||
| }); | ||
|
|
||
| describe("renderMermaidSvg", () => { | ||
| it("renders once and serves repeats from the cache", async () => { | ||
| const code = "graph TD; cached-->once;"; | ||
| expect(getCachedMermaidSvg(code, "dark")).toBeNull(); | ||
|
|
||
| const first = await renderMermaidSvg(code, "dark"); | ||
| const second = await renderMermaidSvg(code, "dark"); | ||
|
|
||
| expect(first).toBe(second); | ||
| expect(getCachedMermaidSvg(code, "dark")).toBe(first); | ||
| expect(mocks.render).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it("collapses concurrent renders of the same diagram", async () => { | ||
| const code = "graph TD; concurrent-->once;"; | ||
|
|
||
| const [first, second] = await Promise.all([ | ||
| renderMermaidSvg(code, "dark"), | ||
| renderMermaidSvg(code, "dark"), | ||
| ]); | ||
|
|
||
| expect(first).toBe(second); | ||
| expect(mocks.render).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it("caches per theme and reconfigures mermaid when the theme changes", async () => { | ||
| const code = "graph TD; themed-->twice;"; | ||
|
|
||
| const dark = await renderMermaidSvg(code, "dark"); | ||
| const light = await renderMermaidSvg(code, "light"); | ||
|
|
||
| expect(getCachedMermaidSvg(code, "dark")).toBe(dark); | ||
| expect(getCachedMermaidSvg(code, "light")).toBe(light); | ||
| expect(mocks.render).toHaveBeenCalledTimes(2); | ||
| expect(mocks.initialize.mock.calls.at(-1)?.[0]).toMatchObject({ theme: "default" }); | ||
| }); | ||
|
|
||
| it("keeps rendering after a diagram fails to parse", async () => { | ||
| mocks.render.mockRejectedValueOnce(new Error("Parse error on line 2")); | ||
|
|
||
| await expect(renderMermaidSvg("graph TD; broken", "light")).rejects.toThrow( | ||
| "Parse error on line 2", | ||
| ); | ||
| await expect(renderMermaidSvg("graph TD; ok-->after;", "light")).resolves.toContain("<svg"); | ||
| }); | ||
| }); |
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,51 @@ | ||
| import { LRUCache } from "./lruCache"; | ||
|
|
||
| export type MermaidTheme = "light" | "dark"; | ||
|
|
||
| // Scrolling a long body remounts every diagram in it, and mermaid's layout pass is the | ||
| // expensive part. Keyed by the source itself: a hash collision would draw the wrong diagram. | ||
| const renderedSvgCache = new LRUCache<string>(64, 8 * 1024 * 1024); | ||
|
|
||
| /** The SVG from an earlier render of this diagram in this theme, so remounts draw at once. */ | ||
| export function getCachedMermaidSvg(code: string, theme: MermaidTheme): string | null { | ||
| return renderedSvgCache.get(`${theme}\n${code}`); | ||
| } | ||
|
|
||
| // Mermaid's config and render target are module-global, so renders join one chain instead | ||
| // of trampling each other's theme. | ||
| let renderQueue: Promise<unknown> = Promise.resolve(); | ||
| let configuredTheme: MermaidTheme | null = null; | ||
| let renderCount = 0; | ||
|
|
||
| /** Renders on first use only: mermaid is far too large for the main bundle. */ | ||
| export function renderMermaidSvg(code: string, theme: MermaidTheme): Promise<string> { | ||
| const cached = getCachedMermaidSvg(code, theme); | ||
| if (cached != null) return Promise.resolve(cached); | ||
|
|
||
| const render = renderQueue.then(async () => { | ||
| // Copies of one diagram queue together; the first one through fills the cache. | ||
| const alreadyRendered = getCachedMermaidSvg(code, theme); | ||
| if (alreadyRendered != null) return alreadyRendered; | ||
|
|
||
| const { default: mermaid } = await import("mermaid"); | ||
| if (configuredTheme !== theme) { | ||
| mermaid.initialize({ | ||
| startOnLoad: false, | ||
| // Pull request bodies are attacker-controlled: keep DOMPurify on and click/script off. | ||
| securityLevel: "strict", | ||
| // Otherwise mermaid injects its own error graph next to the React fallback. | ||
| suppressErrorRendering: true, | ||
| theme: theme === "dark" ? "dark" : "default", | ||
| }); | ||
| configuredTheme = theme; | ||
| } | ||
| renderCount += 1; | ||
| const { svg } = await mermaid.render(`markdown-mermaid-${renderCount}`, code); | ||
| renderedSvgCache.set(`${theme}\n${code}`, svg, svg.length * 2); | ||
| return svg; | ||
| }); | ||
|
|
||
| // A failed diagram must not poison the queue for the next one. | ||
| renderQueue = render.catch(() => undefined); | ||
| return render; | ||
| } |
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.