
























Render Mermaid diagrams including flowcharts, sequence diagrams, and more.
The @streamdown/mermaid plugin renders Mermaid diagrams including flowcharts, sequence diagrams, state diagrams, and more using text-based syntax. Each diagram includes interactive controls for fullscreen viewing, downloading, and copying.
Add the following @source directive to your globals.css or main CSS file:
@source "../node_modules/@streamdown/mermaid/dist/*.js";The path must be relative from your CSS file to the node_modules folder containing @streamdown/mermaid. In a monorepo, adjust the number of ../ segments to reach the root node_modules.
Add @streamdown/mermaid to your content array in tailwind.config.js:
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx,mdx}",
"./node_modules/@streamdown/mermaid/dist/*.js",
],
// ... rest of your config
};In a monorepo, adjust the path to reach the root node_modules:
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx,mdx}",
"../../node_modules/@streamdown/mermaid/dist/*.js",
],
// ... rest of your config
};import { mermaid } from '@streamdown/mermaid';
<Streamdown plugins={{ mermaid }}>
{markdown}
</Streamdown>Without the mermaid plugin, mermaid code blocks render as plain code instead of diagrams.
Create Mermaid diagrams using code blocks with the mermaid language identifier:
```mermaid
graph TD
A[Start] --> B{Decision}
B -->|Yes| C[Success]
B -->|No| D[Try Again]
D --> B
```Streamdown renders the diagram as an interactive SVG with controls.
Create flowcharts to visualize processes and workflows:
```mermaid
graph TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
C -->|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[Car]
```Node Shapes:
[text] - Rectangle(text) - Rounded rectangle{text} - Rhombus (decision)((text)) - Circle[[text]] - Subroutine shapeDirection:
graph TD - Top to bottomgraph LR - Left to rightgraph BT - Bottom to topgraph RL - Right to leftVisualize interactions between different actors or systems:
```mermaid
sequenceDiagram
participant User
participant Browser
participant Server
participant Database
User->>Browser: Enter URL
Browser->>Server: HTTP Request
Server->>Database: Query data
Database-->>Server: Return results
Server-->>Browser: HTTP Response
Browser-->>User: Display page
```Arrow Types:
-> - Solid line--> - Dotted line->> - Solid arrow-->> - Dotted arrowModel state machines and state transitions:
```mermaid
stateDiagram-v2
[*] --> Idle
Idle --> Loading: start
Loading --> Success: data received
Loading --> Error: failed
Success --> Idle: reset
Error --> Loading: retry
Success --> [*]
```Document object-oriented designs:
```mermaid
classDiagram
class User {
+String name
+String email
+login()
+logout()
}
class Post {
+String title
+String content
+Date createdAt
+publish()
}
User "1" --> "*" Post: creates
```Display proportional data:
```mermaid
pie title Project Time Distribution
"Development" : 45
"Testing" : 20
"Documentation" : 15
"Meetings" : 20
```Plan and track project timelines:
```mermaid
gantt
title Project Schedule
dateFormat YYYY-MM-DD
section Design
Wireframes :2024-01-01, 7d
Mockups :2024-01-08, 7d
section Development
Frontend :2024-01-15, 14d
Backend :2024-01-15, 14d
section Testing
QA Testing :2024-01-29, 7d
```Model database relationships:
```mermaid
erDiagram
USER ||--o{ POST : creates
USER {
int id PK
string email
string name
}
POST {
int id PK
int userId FK
string title
text content
}
POST ||--o{ COMMENT : has
COMMENT {
int id PK
int postId FK
string content
}
```Visualize Git workflows:
```mermaid
gitGraph
commit
commit
branch develop
checkout develop
commit
commit
checkout main
merge develop
commit
```The Mermaid plugin uses these defaults:
startOnLoad: false - Diagrams render on demandtheme: "default" - Mermaid's default themesecurityLevel: "strict" - Secure renderingfontFamily: "monospace" - Consistent code-like typographysuppressErrorRendering: true - Prevents partial renders on errorsCustomize the Mermaid theme using the mermaid.config prop:
import { Streamdown } from "streamdown";
import { mermaid } from "@streamdown/mermaid";
import type { MermaidConfig } from "@streamdown/mermaid";
export default function Page() {
return (
<Streamdown
plugins={{ mermaid }}
mermaid={{
config: {
theme: "dark",
themeVariables: {
primaryColor: "#ff6b6b",
primaryTextColor: "#fff",
primaryBorderColor: "#ff6b6b",
lineColor: "#f5f5f5",
secondaryColor: "#4ecdc4",
tertiaryColor: "#45b7d1",
},
},
}}
>
{markdown}
</Streamdown>
);
}Mermaid includes several built-in themes:
default - Classic Mermaid themedark - Dark mode optimizedforest - Green tonesneutral - Minimal stylingbase - Clean, modern styleExample:
<Streamdown
plugins={{ mermaid }}
mermaid={{ config: { theme: "forest" } }}
>
{markdown}
</Streamdown>Customize specific diagram types:
<Streamdown
plugins={{ mermaid }}
mermaid={{
config: {
theme: "base",
themeVariables: {
fontSize: "16px",
fontFamily: "Inter, sans-serif",
},
flowchart: {
nodeSpacing: 50,
rankSpacing: 50,
curve: "basis",
},
sequence: {
actorMargin: 50,
boxMargin: 10,
boxTextMargin: 5,
},
},
}}
>
{markdown}
</Streamdown>For advanced configuration, use createMermaidPlugin:
import { createMermaidPlugin } from '@streamdown/mermaid';
const mermaid = createMermaidPlugin({
config: {
theme: 'dark',
fontFamily: 'monospace',
},
});When Mermaid diagrams fail to render due to invalid syntax, you can provide a custom error component. This is useful for production environments where you want to control the user experience.
import { Streamdown } from "streamdown";
import { mermaid } from "@streamdown/mermaid";
import type { MermaidErrorComponentProps } from "streamdown";
const CustomMermaidError = ({
error,
chart,
retry,
}: MermaidErrorComponentProps) => (
<div className="rounded-lg border border-amber-200 bg-amber-50 p-4">
<div className="flex items-center gap-2">
<span className="text-xl">⚠️</span>
<p className="font-semibold text-amber-900">Couldn't render diagram</p>
</div>
<p className="mt-2 text-amber-700 text-sm">
There was an issue with the diagram syntax.
</p>
<button
onClick={retry}
className="mt-3 rounded bg-amber-600 px-4 py-2 text-white text-sm hover:bg-amber-700"
>
Try Again
</button>
</div>
);
export default function Page() {
return (
<Streamdown
plugins={{ mermaid }}
mermaid={{
errorComponent: CustomMermaidError,
}}
>
{markdown}
</Streamdown>
);
}The error component receives three props:
string) - The error message from Mermaidstring) - The original Mermaid diagram code() => void) - Function to retry rendering the diagramconst ErrorWithLogging = ({
error,
chart,
retry,
}: MermaidErrorComponentProps) => {
useEffect(() => {
// Log to your error tracking service
console.error("Mermaid rendering failed:", error);
// Could also send to Sentry, LogRocket, etc.
}, [error]);
return (
<div className="text-center p-4">
<p className="text-muted-foreground">Unable to display diagram</p>
<button onClick={retry} className="mt-2 text-primary text-sm underline">
Retry
</button>
</div>
);
};Each Mermaid diagram includes interactive controls:
Click the fullscreen button to view the diagram in an overlay with a dark background. This is useful for complex diagrams.
Download the diagram as an SVG file for use in presentations or documentation.
Copy the diagram to your clipboard for pasting into other applications.
You can customize which controls are shown:
<Streamdown
plugins={{ mermaid }}
controls={{
mermaid: {
fullscreen: true,
download: true,
copy: true,
panZoom: true, // Enable pan and zoom controls
},
}}
>
{markdown}
</Streamdown>Or disable specific controls:
<Streamdown
plugins={{ mermaid }}
controls={{
mermaid: {
fullscreen: true,
download: false, // Hide download button
copy: false, // Hide copy button
panZoom: false, // Hide pan/zoom controls
},
}}
>
{markdown}
</Streamdown>Or disable all Mermaid controls:
<Streamdown
plugins={{ mermaid }}
controls={{ mermaid: false }}
>
{markdown}
</Streamdown>When Mermaid diagrams are first streamed in, they appear as code blocks until the diagram syntax is complete. Streamdown's parser ensures the code block is properly formatted during streaming.
Mermaid diagrams are expensive to render. During streaming, you don't want to re-render the diagram on every chunk — that would be slow and cause flickering. Use the useIsCodeFenceIncomplete hook to wait until the code block is complete before rendering:
import { Streamdown, useIsCodeFenceIncomplete } from "streamdown";
import { mermaid } from "@streamdown/mermaid";
const MyMermaidBlock = ({ children }) => {
const isIncomplete = useIsCodeFenceIncomplete();
if (isIncomplete) {
return (
<div className="animate-pulse bg-muted h-48 rounded-lg flex items-center justify-center">
<span className="text-muted-foreground">Loading diagram...</span>
</div>
);
}
// Only render Mermaid once the code block is fully received
return <Mermaid chart={children} />;
};This shows a placeholder while the code block is streaming, then renders the Mermaid diagram only once the closing ``` is received — without waiting for the entire markdown stream to finish.
Use the isAnimating prop to disable interactive controls while content is streaming:
<Streamdown
plugins={{ mermaid }}
isAnimating={isStreaming}
>
{markdown}
</Streamdown>This prevents users from interacting with incomplete diagrams.
A --> B // Arrow
A --- B // Line
A -.-> B // Dotted arrow
A ==> B // Thick arrow
A -->|Label| B // Labeled arrowparticipant A as Alice
actor B as BobBreak complex diagrams into smaller, focused visualizations:
✅ Good: Multiple small diagrams
## User Authentication Flow
```mermaid
graph LR
A[Login] --> B{Valid?}
B -->|Yes| C[Dashboard]
B -->|No| D[Error]
```
## Data Fetching Flow
```mermaid
graph LR
A[Request] --> B[API]
B --> C[Database]
C --> B
B --> D[Response]
```
❌ Avoid: One massive diagram with everythingProvide descriptions for your diagrams:
Here's the authentication flow for our application:
```mermaid
sequenceDiagram
User->>App: Enter credentials
App->>Server: Authenticate
Server-->>App: Token
App-->>User: Success
```
The server validates credentials and returns a JWT token.Make your diagrams self-documenting:
✅ Good: Clear labels
```mermaid
graph TD
A[User clicks 'Submit'] --> B{Form valid?}
B -->|Yes| C[Send to server]
B -->|No| D[Show validation errors]
```
❌ Avoid: Cryptic labels
```mermaid
graph TD
A[Step 1] --> B{Check}
B -->|OK| C[Next]
B -->|Bad| D[Err]
```Select the diagram type that best represents your information:
```mermaidLarge diagrams may take time to render. Consider:
mermaid.config is properly passedThe Mermaid plugin implements the DiagramPlugin interface:
interface DiagramPlugin {
name: "mermaid";
type: "diagram";
language: string; // "mermaid"
getMermaid: (config?: MermaidConfig) => MermaidInstance;
}The language property indicates which code block language triggers diagram rendering.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。