feat(web): render mermaid code blocks as diagrams (#15067)
Co-authored-by: maria-rcks <[email protected]>
This commit is contained in:
1 parent
429c625a85
commit
5e35272fda
5 files changed
+1215
-49
No files matched your search
@@ -40,6 +40,7 @@
|
||||
"@tiptap/starter-kit": "^3.31.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"culori": "^4.0.2",
|
||||
"dompurify": "^3.4.16",
|
||||
"effect": "catalog:",
|
||||
"hast-util-to-html": "^9.0.5",
|
||||
"hast-util-to-jsx-runtime": "^2.3.6",
|
||||
@@ -48,6 +49,7 @@
|
||||
"jsonc-parser": "3.3.1",
|
||||
"jszip": "3.10.1",
|
||||
"lucide-react": "^0.564.0",
|
||||
"mermaid": "^11.17.2",
|
||||
"react": "19.2.6",
|
||||
"react-dom": "19.2.6",
|
||||
"react-markdown": "^10.1.0",
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
import {
|
||||
CheckIcon,
|
||||
ChevronRightIcon,
|
||||
CodeIcon,
|
||||
CopyIcon,
|
||||
FileSpreadsheetIcon,
|
||||
FileTextIcon,
|
||||
@@ -24,6 +25,7 @@ import {
|
||||
PresentationIcon,
|
||||
SparklesIcon,
|
||||
TriangleAlertIcon,
|
||||
WorkflowIcon,
|
||||
WrapTextIcon,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
@@ -141,6 +143,7 @@ import { GitHubIcon } from "./Icons";
|
||||
import { createIncrementalHighlightedDocument } from "../lib/incrementalHighlighting";
|
||||
import { HighlightedCodeLines } from "./chat/HighlightedCodeLines";
|
||||
import { RenderErrorBoundary } from "./RenderErrorBoundary";
|
||||
import { MermaidDiagram } from "./chat/MermaidDiagram";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { getClientSettings, useClientSettings } from "../hooks/useSettings";
|
||||
import {
|
||||
@@ -975,6 +978,9 @@ function MarkdownCodeBlock({
|
||||
theme,
|
||||
onRunShellCommand,
|
||||
isStreaming,
|
||||
leadingActions,
|
||||
canWrap = true,
|
||||
diagram = false,
|
||||
children,
|
||||
}: {
|
||||
code: string;
|
||||
@@ -983,6 +989,10 @@ function MarkdownCodeBlock({
|
||||
theme: "light" | "dark";
|
||||
onRunShellCommand?: ((command: string) => void) | undefined;
|
||||
isStreaming: boolean;
|
||||
leadingActions?: ReactNode;
|
||||
canWrap?: boolean;
|
||||
/** Renders content instead of code, with actions below it like tables. */
|
||||
diagram?: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
@@ -1040,6 +1050,37 @@ function MarkdownCodeBlock({
|
||||
[],
|
||||
);
|
||||
|
||||
const copyButton = (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost-muted"
|
||||
size="icon-xs"
|
||||
onClick={handleCopy}
|
||||
aria-label={copyLabel}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{copyLabel}</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
if (diagram) {
|
||||
return (
|
||||
<div className="my-[0.65rem]" data-language={language}>
|
||||
{children}
|
||||
<div className="mt-0.5 flex items-center justify-between select-none">
|
||||
{leadingActions}
|
||||
{copyButton}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="chat-markdown-codeblock my-[0.65rem] overflow-hidden rounded-lg border border-border/70 bg-secondary leading-snug dark:border-transparent dark:bg-input/32"
|
||||
@@ -1055,23 +1096,26 @@ function MarkdownCodeBlock({
|
||||
/>
|
||||
</span>
|
||||
<span className="flex items-center gap-0.5" role="toolbar" aria-label="Code block actions">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
variant={wrapped ? "secondary" : "ghost-muted"}
|
||||
size="icon-xs"
|
||||
aria-pressed={wrapped}
|
||||
onClick={() => setWrapped((value) => !value)}
|
||||
aria-label={wrapLabel}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<WrapTextIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{wrapLabel}</TooltipPopup>
|
||||
</Tooltip>
|
||||
{leadingActions}
|
||||
{canWrap ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
variant={wrapped ? "secondary" : "ghost-muted"}
|
||||
size="icon-xs"
|
||||
aria-pressed={wrapped}
|
||||
onClick={() => setWrapped((value) => !value)}
|
||||
aria-label={wrapLabel}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<WrapTextIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{wrapLabel}</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{canRun ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
@@ -1090,6 +1134,47 @@ function MarkdownCodeBlock({
|
||||
<TooltipPopup side="top">Run in terminal</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{copyButton}
|
||||
</span>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mermaid fences render as a diagram once the response settles; streaming and
|
||||
* the code toggle keep the highlighted source.
|
||||
*/
|
||||
function MarkdownMermaidCodeBlock({
|
||||
code,
|
||||
fenceTitle,
|
||||
theme,
|
||||
isStreaming,
|
||||
onExpand,
|
||||
children,
|
||||
}: {
|
||||
code: string;
|
||||
fenceTitle: string | null;
|
||||
theme: "light" | "dark";
|
||||
isStreaming: boolean;
|
||||
onExpand: (imageUrl: string) => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const [showCode, setShowCode] = useState(false);
|
||||
const showDiagram = !showCode && !isStreaming && code.trim().length > 0;
|
||||
const toggleLabel = showCode ? "Show diagram" : "Show code";
|
||||
return (
|
||||
<MarkdownCodeBlock
|
||||
code={code}
|
||||
language="mermaid"
|
||||
fenceTitle={fenceTitle}
|
||||
theme={theme}
|
||||
isStreaming={isStreaming}
|
||||
canWrap={!showDiagram}
|
||||
diagram={showDiagram}
|
||||
leadingActions={
|
||||
isStreaming ? null : (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
@@ -1097,19 +1182,34 @@ function MarkdownCodeBlock({
|
||||
type="button"
|
||||
variant="ghost-muted"
|
||||
size="icon-xs"
|
||||
onClick={handleCopy}
|
||||
aria-label={copyLabel}
|
||||
onClick={() => setShowCode((value) => !value)}
|
||||
aria-label={toggleLabel}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
|
||||
{showCode ? <WorkflowIcon className="size-3" /> : <CodeIcon className="size-3" />}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{copyLabel}</TooltipPopup>
|
||||
<TooltipPopup side="top">{toggleLabel}</TooltipPopup>
|
||||
</Tooltip>
|
||||
</span>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
>
|
||||
{showDiagram ? (
|
||||
<RenderErrorBoundary resetKeys={[code, theme]} fallback={children}>
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="flex min-h-36 items-center justify-center text-xs text-muted-foreground">
|
||||
Rendering diagram
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<MermaidDiagram source={code} theme={theme} onExpand={onExpand} />
|
||||
</Suspense>
|
||||
</RenderErrorBoundary>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</MarkdownCodeBlock>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3300,7 +3400,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
|
||||
return <MarkdownDetails open={detailsOpen}>{children}</MarkdownDetails>;
|
||||
},
|
||||
pre: function MarkdownPre({ node, children, ...props }) {
|
||||
const { resolvedTheme, diffThemeName, isStreaming, onRunShellCommand, text } = use(
|
||||
const { resolvedTheme, diffThemeName, expandMedia, isStreaming, onRunShellCommand, text } = use(
|
||||
ChatMarkdownRendererContext,
|
||||
);
|
||||
const codeBlock = extractCodeBlock(children);
|
||||
@@ -3310,6 +3410,42 @@ const CHAT_MARKDOWN_COMPONENTS = {
|
||||
|
||||
const language = extractFenceLanguage(codeBlock.className);
|
||||
const fenceTitle = extractFenceTitle(extractPreCodeMeta(node));
|
||||
const highlightedCode = (
|
||||
<RenderErrorBoundary
|
||||
resetKeys={[codeBlock.code, language, diffThemeName, isStreaming]}
|
||||
fallback={<pre {...props}>{children}</pre>}
|
||||
>
|
||||
{/* Reserve the block's height but stay hidden until Shiki has colored
|
||||
it, so plain text never flashes before the highlighted version. */}
|
||||
<Suspense
|
||||
fallback={
|
||||
<pre {...props} className="invisible" aria-hidden>
|
||||
{children}
|
||||
</pre>
|
||||
}
|
||||
>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={diffThemeName}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
</Suspense>
|
||||
</RenderErrorBoundary>
|
||||
);
|
||||
if (language === "mermaid") {
|
||||
return (
|
||||
<MarkdownMermaidCodeBlock
|
||||
code={codeBlock.code}
|
||||
fenceTitle={fenceTitle}
|
||||
theme={resolvedTheme}
|
||||
isStreaming={isStreaming}
|
||||
onExpand={(src) => expandMedia({ images: [{ src, name: "Mermaid diagram" }], index: 0 })}
|
||||
>
|
||||
{highlightedCode}
|
||||
</MarkdownMermaidCodeBlock>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<MarkdownCodeBlock
|
||||
code={codeBlock.code}
|
||||
@@ -3323,27 +3459,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
|
||||
}
|
||||
isStreaming={isStreaming}
|
||||
>
|
||||
<RenderErrorBoundary
|
||||
resetKeys={[codeBlock.code, language, diffThemeName, isStreaming]}
|
||||
fallback={<pre {...props}>{children}</pre>}
|
||||
>
|
||||
{/* Reserve the block's height but stay hidden until Shiki has colored
|
||||
it, so plain text never flashes before the highlighted version. */}
|
||||
<Suspense
|
||||
fallback={
|
||||
<pre {...props} className="invisible" aria-hidden>
|
||||
{children}
|
||||
</pre>
|
||||
}
|
||||
>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={diffThemeName}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
</Suspense>
|
||||
</RenderErrorBoundary>
|
||||
{highlightedCode}
|
||||
</MarkdownCodeBlock>
|
||||
);
|
||||
},
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import DOMPurify from "dompurify";
|
||||
import type { Mermaid } from "mermaid";
|
||||
import { use, useState } from "react";
|
||||
|
||||
import { Button } from "../ui/button";
|
||||
|
||||
type MermaidRenderResult =
|
||||
| { readonly status: "rendered"; readonly svg: string }
|
||||
| { readonly status: "error"; readonly message: string; readonly retryable: boolean };
|
||||
|
||||
let mermaidModulePromise: Promise<Mermaid> | null = null;
|
||||
let renderQueue: Promise<unknown> = Promise.resolve();
|
||||
let nextDiagramId = 0;
|
||||
const MAX_CACHED_RENDERS = 64;
|
||||
// Keyed by the full source so distinct diagrams never share an entry. Pending
|
||||
// renders are never evicted, because use() must get the same promise on retry.
|
||||
const renderCache = new Map<string, Promise<MermaidRenderResult>>();
|
||||
const settledRenders = new WeakSet<Promise<MermaidRenderResult>>();
|
||||
|
||||
// Mermaid is ~1MB, so it only loads once a diagram is actually shown.
|
||||
function loadMermaid(): Promise<Mermaid> {
|
||||
mermaidModulePromise ??= import("mermaid")
|
||||
.then((module) => module.default)
|
||||
.catch((error: unknown) => {
|
||||
mermaidModulePromise = null;
|
||||
throw error;
|
||||
});
|
||||
return mermaidModulePromise;
|
||||
}
|
||||
|
||||
const REMOTE_CSS_URL = /url\(\s*(?!['"]?#)[^)]*\)/gi;
|
||||
let purifier: ReturnType<typeof DOMPurify> | null = null;
|
||||
|
||||
// Diagrams can come from untrusted PR descriptions, so strip anything that can
|
||||
// navigate, run script, or fetch remote content on top of Mermaid's own strict
|
||||
// sanitization. CSS keeps only local url(#id) references; label text is untouched.
|
||||
function sanitizeMermaidSvg(svg: string): string {
|
||||
if (!purifier) {
|
||||
purifier = DOMPurify(window);
|
||||
purifier.addHook("uponSanitizeElement", (node, data) => {
|
||||
if (data.tagName === "style" && node.textContent) {
|
||||
node.textContent = node.textContent.replace(REMOTE_CSS_URL, "none");
|
||||
}
|
||||
});
|
||||
purifier.addHook("uponSanitizeAttribute", (_node, data) => {
|
||||
if (data.attrName === "style")
|
||||
data.attrValue = data.attrValue.replace(REMOTE_CSS_URL, "none");
|
||||
});
|
||||
}
|
||||
return purifier.sanitize(svg, {
|
||||
ADD_TAGS: ["foreignObject"],
|
||||
HTML_INTEGRATION_POINTS: { foreignobject: true },
|
||||
FORBID_ATTR: ["href", "xlink:href", "src", "srcset"],
|
||||
FORBID_TAGS: ["a", "img", "image", "script"],
|
||||
USE_PROFILES: { svg: true, svgFilters: true, html: true },
|
||||
});
|
||||
}
|
||||
|
||||
// Mermaid also lazy-loads diagram chunks inside render(); losing the network
|
||||
// there is worth a retry, unlike a syntax error.
|
||||
const CHUNK_LOAD_ERROR = /dynamically imported module|importing a module script|failed to fetch/i;
|
||||
|
||||
async function renderMermaid(
|
||||
source: string,
|
||||
theme: "light" | "dark",
|
||||
): Promise<MermaidRenderResult> {
|
||||
const id = `mermaid-diagram-${nextDiagramId++}`;
|
||||
let mermaid: Mermaid;
|
||||
try {
|
||||
mermaid = await loadMermaid();
|
||||
} catch {
|
||||
return { status: "error", message: "Mermaid failed to load.", retryable: true };
|
||||
}
|
||||
try {
|
||||
// initialize() mutates global config, so renders run one at a time.
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
securityLevel: "strict",
|
||||
suppressErrorRendering: true,
|
||||
// HTML labels and theme CSS are mounted while Mermaid lays the diagram
|
||||
// out, before sanitizing, so diagram directives must not set them.
|
||||
secure: [
|
||||
"secure",
|
||||
"securityLevel",
|
||||
"startOnLoad",
|
||||
"maxTextSize",
|
||||
"suppressErrorRendering",
|
||||
"maxEdges",
|
||||
"htmlLabels",
|
||||
"themeCSS",
|
||||
],
|
||||
htmlLabels: false,
|
||||
flowchart: { htmlLabels: false },
|
||||
theme: theme === "dark" ? "dark" : "default",
|
||||
fontFamily: getComputedStyle(document.body).fontFamily,
|
||||
});
|
||||
const { svg } = await mermaid.render(id, source);
|
||||
return { status: "rendered", svg: sanitizeMermaidSvg(svg) };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "The diagram could not be rendered.";
|
||||
return { status: "error", message, retryable: CHUNK_LOAD_ERROR.test(message) };
|
||||
} finally {
|
||||
document.getElementById(`d${id}`)?.remove();
|
||||
}
|
||||
}
|
||||
|
||||
function evictSettledRenders() {
|
||||
for (const [key, result] of renderCache) {
|
||||
if (renderCache.size <= MAX_CACHED_RENDERS) return;
|
||||
if (settledRenders.has(result)) renderCache.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
function mermaidRenderKey(source: string, theme: "light" | "dark") {
|
||||
return `${theme}\n${source}`;
|
||||
}
|
||||
|
||||
function mermaidRenderPromise(source: string, theme: "light" | "dark") {
|
||||
const key = mermaidRenderKey(source, theme);
|
||||
const cached = renderCache.get(key);
|
||||
if (cached) {
|
||||
renderCache.delete(key);
|
||||
renderCache.set(key, cached);
|
||||
return cached;
|
||||
}
|
||||
const result = renderQueue.then(() => renderMermaid(source, theme));
|
||||
renderQueue = result;
|
||||
void result.then(() => {
|
||||
settledRenders.add(result);
|
||||
evictSettledRenders();
|
||||
});
|
||||
renderCache.set(key, result);
|
||||
evictSettledRenders();
|
||||
return result;
|
||||
}
|
||||
|
||||
let expandedImageUrl: string | null = null;
|
||||
|
||||
/**
|
||||
* Converts a rendered diagram into a standalone image with fixed size and background.
|
||||
* A blob URL, unlike a data URL, passes the desktop connect-src policy that media
|
||||
* save and copy actions fetch through. Only one diagram is expanded at a time, so
|
||||
* the previous URL is released.
|
||||
*/
|
||||
function mermaidImageUrl(svg: string): string {
|
||||
const svgDocument = new DOMParser().parseFromString(svg, "image/svg+xml");
|
||||
const element = svgDocument.documentElement;
|
||||
const viewBox = element.getAttribute("viewBox")?.trim().split(/\s+/).map(Number);
|
||||
if (viewBox?.length === 4 && viewBox.every(Number.isFinite)) {
|
||||
element.setAttribute("width", String(viewBox[2]));
|
||||
element.setAttribute("height", String(viewBox[3]));
|
||||
}
|
||||
element.setAttribute("xmlns", "http://www.w3.org/2000/svg");
|
||||
element.style.maxWidth = "none";
|
||||
element.style.backgroundColor = getComputedStyle(document.body).backgroundColor;
|
||||
if (expandedImageUrl) URL.revokeObjectURL(expandedImageUrl);
|
||||
expandedImageUrl = URL.createObjectURL(
|
||||
new Blob([new XMLSerializer().serializeToString(element)], { type: "image/svg+xml" }),
|
||||
);
|
||||
return expandedImageUrl;
|
||||
}
|
||||
|
||||
/** Suspends until the diagram renders; failures show the parser message above the source. */
|
||||
export function MermaidDiagram({
|
||||
source,
|
||||
theme,
|
||||
onExpand,
|
||||
}: {
|
||||
source: string;
|
||||
theme: "light" | "dark";
|
||||
onExpand: (imageUrl: string) => void;
|
||||
}) {
|
||||
const [, setAttempt] = useState(0);
|
||||
const result = use(mermaidRenderPromise(source.trim(), theme));
|
||||
|
||||
if (result.status === "error") {
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<p className="m-0 text-xs text-destructive">Unable to render diagram: {result.message}</p>
|
||||
{result.retryable ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
onClick={() => {
|
||||
renderCache.delete(mermaidRenderKey(source.trim(), theme));
|
||||
setAttempt((attempt) => attempt + 1);
|
||||
}}
|
||||
>
|
||||
Retry
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<pre className="mt-2 mb-0 overflow-auto font-mono text-xs whitespace-pre-wrap">
|
||||
{source}
|
||||
</pre>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="overflow-x-auto">
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Expand diagram"
|
||||
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"
|
||||
onClick={() => onExpand(mermaidImageUrl(result.svg))}
|
||||
dangerouslySetInnerHTML={{ __html: result.svg }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Generated
+810
-2
File diff suppressed because it is too large.
Load diff
@@ -599,6 +599,33 @@
|
||||
"licenseId": "MIT",
|
||||
"copyrights": ["Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"license": "MIT",
|
||||
"name": "fastdom",
|
||||
"sourceUrl": "https://github.com/wilsonpage/fastdom",
|
||||
"generatedNotice": {
|
||||
"licenseId": "MIT",
|
||||
"copyrights": ["Copyright (c) 2016 Wilson Page"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"license": "MIT",
|
||||
"name": "strictdom",
|
||||
"sourceUrl": "https://github.com/wilsonpage/strictdom",
|
||||
"generatedNotice": {
|
||||
"licenseId": "MIT",
|
||||
"copyrights": ["Copyright (c) 2013 Wilson Page"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"license": "MIT",
|
||||
"name": "khroma",
|
||||
"sourceUrl": "https://github.com/fabiospampinato/khroma",
|
||||
"generatedNotice": {
|
||||
"licenseId": "MIT",
|
||||
"copyrights": ["Copyright (c) 2019-present Fabio Spampinato, Andrew Maney"]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user