Skip to content

Commit c1d6e0e

Browse files
committed
feat(web): render mermaid code blocks as diagrams
1 parent 8283b48 commit c1d6e0e

5 files changed

Lines changed: 1102 additions & 41 deletions

File tree

‎apps/web/package.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
"@tiptap/starter-kit": "^3.31.3",
4141
"class-variance-authority": "^0.7.1",
4242
"culori": "^4.0.2",
43+
"dompurify": "^3.4.16",
4344
"effect": "catalog:",
4445
"hast-util-to-html": "^9.0.5",
4546
"hast-util-to-jsx-runtime": "^2.3.6",
@@ -48,6 +49,7 @@
4849
"jsonc-parser": "3.3.1",
4950
"jszip": "3.10.1",
5051
"lucide-react": "^0.564.0",
52+
"mermaid": "^11.17.2",
5153
"react": "19.2.6",
5254
"react-dom": "19.2.6",
5355
"react-markdown": "^10.1.0",

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 135 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
import {
88
CheckIcon,
99
ChevronRightIcon,
10+
CodeIcon,
1011
CopyIcon,
1112
FileSpreadsheetIcon,
1213
FileTextIcon,
@@ -24,6 +25,7 @@ import {
2425
PresentationIcon,
2526
SparklesIcon,
2627
TriangleAlertIcon,
28+
WorkflowIcon,
2729
WrapTextIcon,
2830
type LucideIcon,
2931
} from "lucide-react";
@@ -141,6 +143,7 @@ import { GitHubIcon } from "./Icons";
141143
import { createIncrementalHighlightedDocument } from "../lib/incrementalHighlighting";
142144
import { HighlightedCodeLines } from "./chat/HighlightedCodeLines";
143145
import { RenderErrorBoundary } from "./RenderErrorBoundary";
146+
import { MermaidDiagram } from "./chat/MermaidDiagram";
144147
import { useTheme } from "../hooks/useTheme";
145148
import { getClientSettings, useClientSettings } from "../hooks/useSettings";
146149
import {
@@ -975,6 +978,8 @@ function MarkdownCodeBlock({
975978
theme,
976979
onRunShellCommand,
977980
isStreaming,
981+
leadingActions,
982+
canWrap = true,
978983
children,
979984
}: {
980985
code: string;
@@ -983,6 +988,8 @@ function MarkdownCodeBlock({
983988
theme: "light" | "dark";
984989
onRunShellCommand?: ((command: string) => void) | undefined;
985990
isStreaming: boolean;
991+
leadingActions?: ReactNode;
992+
canWrap?: boolean;
986993
children: ReactNode;
987994
}) {
988995
const [copied, setCopied] = useState(false);
@@ -1055,23 +1062,26 @@ function MarkdownCodeBlock({
10551062
/>
10561063
</span>
10571064
<span className="flex items-center gap-0.5" role="toolbar" aria-label="Code block actions">
1058-
<Tooltip>
1059-
<TooltipTrigger
1060-
render={
1061-
<Button
1062-
type="button"
1063-
variant={wrapped ? "secondary" : "ghost-muted"}
1064-
size="icon-xs"
1065-
aria-pressed={wrapped}
1066-
onClick={() => setWrapped((value) => !value)}
1067-
aria-label={wrapLabel}
1068-
/>
1069-
}
1070-
>
1071-
<WrapTextIcon className="size-3" />
1072-
</TooltipTrigger>
1073-
<TooltipPopup side="top">{wrapLabel}</TooltipPopup>
1074-
</Tooltip>
1065+
{leadingActions}
1066+
{canWrap ? (
1067+
<Tooltip>
1068+
<TooltipTrigger
1069+
render={
1070+
<Button
1071+
type="button"
1072+
variant={wrapped ? "secondary" : "ghost-muted"}
1073+
size="icon-xs"
1074+
aria-pressed={wrapped}
1075+
onClick={() => setWrapped((value) => !value)}
1076+
aria-label={wrapLabel}
1077+
/>
1078+
}
1079+
>
1080+
<WrapTextIcon className="size-3" />
1081+
</TooltipTrigger>
1082+
<TooltipPopup side="top">{wrapLabel}</TooltipPopup>
1083+
</Tooltip>
1084+
) : null}
10751085
{canRun ? (
10761086
<Tooltip>
10771087
<TooltipTrigger
@@ -1113,6 +1123,76 @@ function MarkdownCodeBlock({
11131123
);
11141124
}
11151125

1126+
/**
1127+
* Mermaid fences render as a diagram once the response settles; streaming and
1128+
* the code toggle keep the highlighted source.
1129+
*/
1130+
function MarkdownMermaidCodeBlock({
1131+
code,
1132+
fenceTitle,
1133+
theme,
1134+
isStreaming,
1135+
onExpand,
1136+
children,
1137+
}: {
1138+
code: string;
1139+
fenceTitle: string | null;
1140+
theme: "light" | "dark";
1141+
isStreaming: boolean;
1142+
onExpand: (imageUrl: string) => void;
1143+
children: ReactNode;
1144+
}) {
1145+
const [showCode, setShowCode] = useState(false);
1146+
const showDiagram = !showCode && !isStreaming && code.trim().length > 0;
1147+
const toggleLabel = showCode ? "Show diagram" : "Show code";
1148+
return (
1149+
<MarkdownCodeBlock
1150+
code={code}
1151+
language="mermaid"
1152+
fenceTitle={fenceTitle}
1153+
theme={theme}
1154+
isStreaming={isStreaming}
1155+
canWrap={!showDiagram}
1156+
leadingActions={
1157+
isStreaming ? null : (
1158+
<Tooltip>
1159+
<TooltipTrigger
1160+
render={
1161+
<Button
1162+
type="button"
1163+
variant="ghost-muted"
1164+
size="icon-xs"
1165+
onClick={() => setShowCode((value) => !value)}
1166+
aria-label={toggleLabel}
1167+
/>
1168+
}
1169+
>
1170+
{showCode ? <WorkflowIcon className="size-3" /> : <CodeIcon className="size-3" />}
1171+
</TooltipTrigger>
1172+
<TooltipPopup side="top">{toggleLabel}</TooltipPopup>
1173+
</Tooltip>
1174+
)
1175+
}
1176+
>
1177+
{showDiagram ? (
1178+
<RenderErrorBoundary resetKeys={[code, theme]} fallback={children}>
1179+
<Suspense
1180+
fallback={
1181+
<div className="flex min-h-36 items-center justify-center text-xs text-muted-foreground">
1182+
Rendering diagram
1183+
</div>
1184+
}
1185+
>
1186+
<MermaidDiagram source={code} theme={theme} onExpand={onExpand} />
1187+
</Suspense>
1188+
</RenderErrorBoundary>
1189+
) : (
1190+
children
1191+
)}
1192+
</MarkdownCodeBlock>
1193+
);
1194+
}
1195+
11161196
interface SuspenseShikiCodeBlockProps {
11171197
className: string | undefined;
11181198
code: string;
@@ -3300,7 +3380,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
33003380
return <MarkdownDetails open={detailsOpen}>{children}</MarkdownDetails>;
33013381
},
33023382
pre: function MarkdownPre({ node, children, ...props }) {
3303-
const { resolvedTheme, diffThemeName, isStreaming, onRunShellCommand, text } = use(
3383+
const { resolvedTheme, diffThemeName, expandMedia, isStreaming, onRunShellCommand, text } = use(
33043384
ChatMarkdownRendererContext,
33053385
);
33063386
const codeBlock = extractCodeBlock(children);
@@ -3310,6 +3390,42 @@ const CHAT_MARKDOWN_COMPONENTS = {
33103390

33113391
const language = extractFenceLanguage(codeBlock.className);
33123392
const fenceTitle = extractFenceTitle(extractPreCodeMeta(node));
3393+
const highlightedCode = (
3394+
<RenderErrorBoundary
3395+
resetKeys={[codeBlock.code, language, diffThemeName, isStreaming]}
3396+
fallback={<pre {...props}>{children}</pre>}
3397+
>
3398+
{/* Reserve the block's height but stay hidden until Shiki has colored
3399+
it, so plain text never flashes before the highlighted version. */}
3400+
<Suspense
3401+
fallback={
3402+
<pre {...props} className="invisible" aria-hidden>
3403+
{children}
3404+
</pre>
3405+
}
3406+
>
3407+
<SuspenseShikiCodeBlock
3408+
className={codeBlock.className}
3409+
code={codeBlock.code}
3410+
themeName={diffThemeName}
3411+
isStreaming={isStreaming}
3412+
/>
3413+
</Suspense>
3414+
</RenderErrorBoundary>
3415+
);
3416+
if (language === "mermaid") {
3417+
return (
3418+
<MarkdownMermaidCodeBlock
3419+
code={codeBlock.code}
3420+
fenceTitle={fenceTitle}
3421+
theme={resolvedTheme}
3422+
isStreaming={isStreaming}
3423+
onExpand={(src) => expandMedia({ images: [{ src, name: "Mermaid diagram" }], index: 0 })}
3424+
>
3425+
{highlightedCode}
3426+
</MarkdownMermaidCodeBlock>
3427+
);
3428+
}
33133429
return (
33143430
<MarkdownCodeBlock
33153431
code={codeBlock.code}
@@ -3323,27 +3439,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
33233439
}
33243440
isStreaming={isStreaming}
33253441
>
3326-
<RenderErrorBoundary
3327-
resetKeys={[codeBlock.code, language, diffThemeName, isStreaming]}
3328-
fallback={<pre {...props}>{children}</pre>}
3329-
>
3330-
{/* Reserve the block's height but stay hidden until Shiki has colored
3331-
it, so plain text never flashes before the highlighted version. */}
3332-
<Suspense
3333-
fallback={
3334-
<pre {...props} className="invisible" aria-hidden>
3335-
{children}
3336-
</pre>
3337-
}
3338-
>
3339-
<SuspenseShikiCodeBlock
3340-
className={codeBlock.className}
3341-
code={codeBlock.code}
3342-
themeName={diffThemeName}
3343-
isStreaming={isStreaming}
3344-
/>
3345-
</Suspense>
3346-
</RenderErrorBoundary>
3442+
{highlightedCode}
33473443
</MarkdownCodeBlock>
33483444
);
33493445
},
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
import DOMPurify from "dompurify";
2+
import type { Mermaid } from "mermaid";
3+
import { use } from "react";
4+
5+
import { fnv1a32 } from "../../lib/diffRendering";
6+
import { LRUCache } from "../../lib/lruCache";
7+
8+
type MermaidRenderResult =
9+
| { readonly status: "rendered"; readonly svg: string }
10+
| { readonly status: "error"; readonly message: string };
11+
12+
let mermaidModulePromise: Promise<Mermaid> | null = null;
13+
let renderQueue: Promise<unknown> = Promise.resolve();
14+
let nextDiagramId = 0;
15+
const renderCache = new LRUCache<Promise<MermaidRenderResult>>(64, 8 * 1024 * 1024);
16+
17+
// Mermaid is ~1MB, so it only loads once a diagram is actually shown.
18+
function loadMermaid(): Promise<Mermaid> {
19+
mermaidModulePromise ??= import("mermaid")
20+
.then((module) => module.default)
21+
.catch((error: unknown) => {
22+
mermaidModulePromise = null;
23+
throw error;
24+
});
25+
return mermaidModulePromise;
26+
}
27+
28+
// Diagrams can come from untrusted PR descriptions, so strip anything that can
29+
// navigate or run script on top of Mermaid's own strict sanitization.
30+
function sanitizeMermaidSvg(svg: string): string {
31+
return DOMPurify.sanitize(svg, {
32+
FORBID_ATTR: ["href", "xlink:href", "onerror", "onload", "onclick"],
33+
FORBID_TAGS: ["foreignObject", "script"],
34+
USE_PROFILES: { svg: true, svgFilters: true },
35+
});
36+
}
37+
38+
async function renderMermaid(
39+
source: string,
40+
theme: "light" | "dark",
41+
): Promise<MermaidRenderResult> {
42+
const id = `mermaid-diagram-${nextDiagramId++}`;
43+
try {
44+
const mermaid = await loadMermaid();
45+
// initialize() mutates global config, so renders run one at a time.
46+
mermaid.initialize({
47+
startOnLoad: false,
48+
securityLevel: "strict",
49+
suppressErrorRendering: true,
50+
htmlLabels: false,
51+
flowchart: { htmlLabels: false },
52+
theme: theme === "dark" ? "dark" : "default",
53+
fontFamily: getComputedStyle(document.body).fontFamily,
54+
});
55+
const { svg } = await mermaid.render(id, source);
56+
return { status: "rendered", svg: sanitizeMermaidSvg(svg) };
57+
} catch (error) {
58+
return {
59+
status: "error",
60+
message: error instanceof Error ? error.message : "The diagram could not be rendered.",
61+
};
62+
} finally {
63+
document.getElementById(`d${id}`)?.remove();
64+
}
65+
}
66+
67+
function mermaidRenderPromise(source: string, theme: "light" | "dark") {
68+
const key = `${fnv1a32(source).toString(36)}:${source.length}:${theme}`;
69+
const cached = renderCache.get(key);
70+
if (cached) return cached;
71+
const result = renderQueue.then(() => renderMermaid(source, theme));
72+
renderQueue = result;
73+
renderCache.set(key, result, source.length * 8);
74+
return result;
75+
}
76+
77+
/** Converts a rendered diagram into a standalone image URL with fixed size and background. */
78+
function mermaidSvgImageUrl(svg: string, background: string): string {
79+
const document = new DOMParser().parseFromString(svg, "image/svg+xml");
80+
const element = document.documentElement;
81+
const viewBox = element.getAttribute("viewBox")?.trim().split(/\s+/).map(Number);
82+
if (viewBox?.length === 4 && viewBox.every(Number.isFinite)) {
83+
element.setAttribute("width", String(viewBox[2]));
84+
element.setAttribute("height", String(viewBox[3]));
85+
}
86+
element.setAttribute("xmlns", "http://www.w3.org/2000/svg");
87+
element.style.maxWidth = "none";
88+
element.style.backgroundColor = background;
89+
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(element))}`;
90+
}
91+
92+
/** Suspends until the diagram renders; failures show the parser message above the source. */
93+
export function MermaidDiagram({
94+
source,
95+
theme,
96+
onExpand,
97+
}: {
98+
source: string;
99+
theme: "light" | "dark";
100+
onExpand: (imageUrl: string) => void;
101+
}) {
102+
const result = use(mermaidRenderPromise(source.trim(), theme));
103+
104+
if (result.status === "error") {
105+
return (
106+
<div className="px-3 pt-1 pb-3">
107+
<p className="m-0 text-xs text-destructive">Unable to render diagram: {result.message}</p>
108+
<pre className="mt-2 mb-0 overflow-auto font-mono text-xs whitespace-pre-wrap">
109+
{source}
110+
</pre>
111+
</div>
112+
);
113+
}
114+
115+
return (
116+
<div className="overflow-x-auto px-3 pt-2 pb-3">
117+
<button
118+
type="button"
119+
aria-label="Expand diagram"
120+
className="flex w-full cursor-zoom-in justify-center rounded-md focus-visible:outline-2 focus-visible:outline-ring [&_svg]:h-auto [&_svg]:max-w-full"
121+
onClick={() =>
122+
onExpand(mermaidSvgImageUrl(result.svg, getComputedStyle(document.body).backgroundColor))
123+
}
124+
dangerouslySetInnerHTML={{ __html: result.svg }}
125+
/>
126+
</div>
127+
);
128+
}

0 commit comments

Comments
 (0)