-
Notifications
You must be signed in to change notification settings - Fork 853
feat(web): render Mermaid diagrams in chat messages #1789
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
Open
luzhongqiu
wants to merge
5
commits into
MoonshotAI:main
Choose a base branch
from
luzhongqiu:feat/web-mermaid
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
5c8414d
feat(web): render Mermaid diagrams in chat messages
a47c936
docs(web): add Mermaid render preview screenshot
ffdab68
docs(web): refine Mermaid fallback copy
537cda3
fix(web): sync Mermaid diagrams with global theme
94892d8
Merge branch 'main' into feat/web-mermaid
n-WN 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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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,159 @@ | ||
| "use client"; | ||
|
|
||
| import { useTheme } from "@/hooks/use-theme"; | ||
| import { cn } from "@/lib/utils"; | ||
| import { AlertTriangleIcon, Loader2Icon } from "lucide-react"; | ||
| import { type HTMLAttributes, useEffect, useId, useRef, useState } from "react"; | ||
|
|
||
| type MermaidDiagramProps = HTMLAttributes<HTMLDivElement> & { | ||
| code: string; | ||
| }; | ||
|
|
||
| type MermaidModule = typeof import("mermaid"); | ||
| type MermaidBindFunctions = (element: Element) => void; | ||
|
|
||
| let mermaidModulePromise: Promise<MermaidModule> | null = null; | ||
| let mermaidRenderNonce = 0; | ||
|
|
||
| const loadMermaidModule = async (): Promise<MermaidModule> => { | ||
| if (!mermaidModulePromise) { | ||
| mermaidModulePromise = import("mermaid"); | ||
| } | ||
| return mermaidModulePromise; | ||
| }; | ||
|
|
||
| const getErrorMessage = (error: unknown): string => { | ||
| if (error instanceof Error && error.message.trim().length > 0) { | ||
| return error.message; | ||
| } | ||
| return "Unable to render Mermaid diagram."; | ||
| }; | ||
|
|
||
| export function MermaidDiagram({ | ||
| code, | ||
| className, | ||
| ...props | ||
| }: MermaidDiagramProps) { | ||
| const { theme } = useTheme(); | ||
| const containerRef = useRef<HTMLDivElement>(null); | ||
| const bindFunctionsRef = useRef<MermaidBindFunctions | null>(null); | ||
| const renderId = useId().replaceAll(":", ""); | ||
| const [svg, setSvg] = useState(""); | ||
| const [error, setError] = useState<string | null>(null); | ||
|
|
||
| useEffect(() => { | ||
| let cancelled = false; | ||
| const source = code.trim(); | ||
|
|
||
| setSvg(""); | ||
| setError(null); | ||
| bindFunctionsRef.current = null; | ||
|
|
||
| if (!source) { | ||
| setError("Mermaid diagram is empty."); | ||
| return () => { | ||
| cancelled = true; | ||
| }; | ||
| } | ||
|
|
||
| const renderDiagram = async () => { | ||
| try { | ||
| const mermaid = (await loadMermaidModule()).default; | ||
|
|
||
| mermaid.initialize({ | ||
| startOnLoad: false, | ||
| securityLevel: "strict", | ||
| suppressErrorRendering: true, | ||
| theme: theme === "dark" ? "dark" : "default", | ||
| fontFamily: | ||
| "Inter Variable, Inter, -apple-system, BlinkMacSystemFont, sans-serif", | ||
| }); | ||
|
|
||
| const diagramId = `mermaid-${renderId}-${mermaidRenderNonce++}`; | ||
| const rendered = await mermaid.render(diagramId, source); | ||
|
|
||
| if (cancelled) { | ||
| return; | ||
| } | ||
|
|
||
| bindFunctionsRef.current = rendered.bindFunctions ?? null; | ||
| setSvg(rendered.svg); | ||
| setError(null); | ||
| } catch (renderError) { | ||
| if (cancelled) { | ||
| return; | ||
| } | ||
|
|
||
| bindFunctionsRef.current = null; | ||
| setSvg(""); | ||
| setError(getErrorMessage(renderError)); | ||
| } | ||
| }; | ||
|
|
||
| void renderDiagram(); | ||
|
|
||
| return () => { | ||
| cancelled = true; | ||
| }; | ||
| }, [code, renderId, theme]); | ||
|
|
||
| useEffect(() => { | ||
| if (!svg || !bindFunctionsRef.current || !containerRef.current) { | ||
| return; | ||
| } | ||
|
|
||
| bindFunctionsRef.current(containerRef.current); | ||
| bindFunctionsRef.current = null; | ||
| }, [svg]); | ||
|
|
||
| if (error) { | ||
| return ( | ||
| <div | ||
| className={cn( | ||
| "rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm", | ||
| className, | ||
| )} | ||
| {...props} | ||
| > | ||
| <div className="mb-3 flex items-start gap-2 text-destructive"> | ||
| <AlertTriangleIcon className="mt-0.5 size-4 shrink-0" /> | ||
| <div className="min-w-0"> | ||
| <div className="font-medium">Mermaid render failed</div> | ||
| <div className="mt-1 whitespace-pre-wrap break-words text-xs text-destructive/90"> | ||
| {error} | ||
| </div> | ||
| </div> | ||
| </div> | ||
| <pre className="overflow-x-auto rounded bg-card p-3 text-xs text-foreground"> | ||
| <code>{code}</code> | ||
| </pre> | ||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| if (!svg) { | ||
| return ( | ||
| <div | ||
| className={cn( | ||
| "flex min-h-32 items-center justify-center rounded-md border border-dashed border-border/80 bg-muted/20 px-4 py-10 text-sm text-muted-foreground", | ||
| className, | ||
| )} | ||
| {...props} | ||
| > | ||
| <Loader2Icon className="mr-2 size-4 animate-spin" /> | ||
| Rendering Mermaid diagram... | ||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| return ( | ||
| <div | ||
| ref={containerRef} | ||
| className={cn("px-3 py-4", className)} | ||
| data-mermaid-diagram="" | ||
| // biome-ignore lint/security/noDangerouslySetInnerHtml: Mermaid renders trusted SVG from local code blocks with strict security mode. | ||
| dangerouslySetInnerHTML={{ __html: svg }} | ||
| {...props} | ||
| /> | ||
| ); | ||
| } | ||
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.
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.