mermaid — команда для Claude Code: диаграммы из текста
Команда строит диаграммы Mermaid (блок-схемы, sequence, state, class, ER, XY-графики) в SVG, HTML или ASCII для терминала.
MIT ★ 328 обновлён 2026-10-29
.claude/commands/mermaid.mdЧто делает mermaid
Команда рендерит шесть типов диаграмм через библиотеку [email protected]: flowchart, sequence, state (stateDiagram-v2), class, ER и XY-чарты. Вывод — SVG для React-компонента CoCo, standalone HTML с ESM-импортом из esm.sh, ASCII для терминала или строка SVG для бэкенда. В комплекте семь встроенных тем (tokyo-night, catppuccin-mocha, github-dark, nord, dracula и две светлые), проверки парсера и шаблоны вывода.
Парсер beautiful-mermaid не поддерживает journey, pie, gantt и gitgraph: их нужно заменить flowchart или XY-чартом. ID узлов — только буквы и цифры, метки с пробелами — в квадратных скобках с кавычками (A["Label"]). Для CoCo Platform диаграмма отображается компонентом <MermaidDiagram> автоматически, для standalone HTML нужен <script type="module"> с импортом renderMermaidSVGAsync.
Какие задачи решает
- построить блок-схему процесса или архитектуры системы
- нарисовать sequence-диаграмму взаимодействия сервисов
- сгенерировать ER-диаграмму базы данных из схемы
- создать state-диаграмму конечного автомата
- вывести XY-график для отчёта или дашборда
Примеры запросов агенту
- Нарисуй блок-схему процесса регистрации пользователя с проверкой email
- Построй sequence-диаграмму запроса между клиентом, API и базой
- Сделай ER-диаграмму для таблиц
users,ordersиproducts
Как установить mermaid
Вручную: положить файлы
.claude/commands/mermaid.mdВызов — /mermaid. Для всех проектов — ~/.claude/commands/
Вручную: положить файлы
~/.codex/prompts/mermaid.mdВызов — /prompts:mermaid. В Codex этот формат помечен устаревшим, замена — скиллы
Вручную: положить файлы
.github/prompts/mermaid.prompt.mdВручную: положить файлы
.gemini/commands/mermaid.tomlGemini хранит команды в TOML: текст запроса — в поле prompt
Вопросы о mermaid
Как установить mermaid в Claude Code?
Положи файл .claude/commands/mermaid.md в корень проекта — Claude Code подхватит команду автоматически.
Что делает команда mermaid?
Строит диаграммы Mermaid (flowchart, sequence, state, class, ER, XY) через [email protected] и выводит в SVG, HTML или ASCII.
Какие типы диаграмм поддерживает mermaid?
Команда работает с flowchart, stateDiagram-v2, sequence, class, ER и xychart-beta. Типы journey, pie, gantt и gitgraph парсер не понимает — их нужно заменить flowchart или XY-чартом.
Исходный текст
mermaid.md · MIT
--- description: "Use when the user asks for a diagram or chart: flowchart, sequence, state, class, ER, or XY chart, as SVG, HTML, or terminal ASCII. Builds beautiful-mermaid diagrams with themes, output templates, and parser-pitfall checks." allowed-tools: - Read - Write - Edit - Bash - Glob - Grep - Agent --- # /design-mermaid — Beautiful Mermaid Diagram Builder You are a Mermaid diagram specialist. You use the `beautiful-mermaid` library (not standard Mermaid v10) for ALL diagram rendering. **Package:** `[email protected]`, imported from `https://esm.sh/[email protected]` (the version pinned in every template below). Run `npm i [email protected]` to read the source locally when you need API details, parser capabilities, or edge-case syntax. ## Quick Reference | Diagram Type | Syntax Prefix | Example | |-------------|---------------|---------| | Flowchart | `graph TD` / `flowchart LR` | `graph TD; A --> B --> C` | | State | `stateDiagram-v2` | `stateDiagram-v2; [*] --> Idle` | | Sequence | `sequenceDiagram` | `sequenceDiagram; Alice->>Bob: Hello` | | Class | `classDiagram` | `classDiagram; Animal <\|-- Duck` | | ER | `erDiagram` | `erDiagram; USER \|\|--o{ ORDER : places` | | XY Chart | `xychart-beta` | `xychart-beta; bar [10, 20, 30]` | **Directions:** `TD` (top-down), `LR` (left-right), `BT` (bottom-top), `RL` (right-left) ## How to Use ### Step 1: Understand the request Ask clarifying questions if needed: - What entities/concepts should be in the diagram? - What type of diagram best represents the data? (flow, state machine, sequence, ER, class, chart) - Is this for the CoCo Platform UI, a standalone HTML file, or terminal output? ### Step 2: Build the diagram Write the mermaid source code. Follow these rules: **Syntax rules (beautiful-mermaid parser):** - Node IDs must be alphanumeric (no spaces, hyphens, or dots in IDs) - Use `["Label with spaces"]` for labels: `A["My Node"] --> B["Other Node"]` - Subgraphs: `subgraph Title; ... end` - Edge labels: `A -->|"label"| B` - Styling: `style A fill:#f00,color:#fff` - Link styling: `linkStyle 0 stroke:#ff0000,stroke-width:2px` - Line breaks in labels: `A["Line 1<br/>Line 2"]` **XY Chart syntax:** ``` xychart-beta title "Chart Title" x-axis [Cat1, Cat2, Cat3] y-axis "Label" 0 --> 100 bar [30, 50, 80] line [25, 45, 70] ``` - `horizontal` keyword after `xychart-beta` for horizontal orientation - Multiple `bar` and `line` declarations for multi-series ### Step 3: Render Choose output based on context: #### A) CoCo Platform (React component) If the diagram is for the CoCo Platform frontend, it renders automatically via the `<MermaidDiagram>` component. Just output the mermaid code in a fenced block: ```` ```mermaid graph TD A --> B ``` ```` The `RichContent` component detects and renders it with: - Theme: CSS variables from CoCo (auto dark/light) - Lazy-loaded elkjs (only when diagram present) - Copy source + fullscreen buttons - DOMPurify sanitized SVG #### B) Standalone HTML file For standalone documents or reports, use the ESM import pattern: ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' https://esm.sh; connect-src 'self' https://esm.sh; style-src 'self' 'unsafe-inline'; img-src 'self' data:;"> <title>Diagram</title> <style> body { font-family: Inter, system-ui, sans-serif; background: #1a1b26; color: #a9b1d6; max-width: 900px; margin: 40px auto; padding: 0 20px; } .diagram { background: #1a1b26; border-radius: 12px; padding: 16px; margin: 16px 0; } .diagram svg { max-width: 100%; height: auto; display: block; } </style> </head> <body> <div class="diagram" data-code="graph TD; A --> B"></div> <script type="module"> import { renderMermaidSVGAsync } from 'https://esm.sh/[email protected]' const theme = { bg: '#1a1b26', fg: '#a9b1d6', accent: '#7aa2f7', transparent: true } for (const el of document.querySelectorAll('[data-code]')) { try { el.innerHTML = await renderMermaidSVGAsync(el.dataset.code, theme) } catch (e) { el.innerHTML = `<pre style="color:#ff453a">${e.message}</pre>` } } </script> </body> </html> ``` **Available themes (built-in):** | Theme | bg | fg | accent | |-------|-----|-----|--------| | tokyo-night | #1a1b26 | #a9b1d6 | #7aa2f7 | | catppuccin-mocha | #1e1e2e | #cdd6f4 | #cba6f7 | | github-dark | #0d1117 | #e6edf3 | #4493f8 | | nord | #2e3440 | #d8dee9 | #88c0d0 | | dracula | #282a36 | #f8f8f2 | #bd93f9 | | zinc-light | #ffffff | #27272a | (derived) | | github-light | #ffffff | #1f2328 | #0969da | #### C) Terminal / ASCII output For CLI tools or terminal display: ```typescript import { renderMermaidASCII } from 'beautiful-mermaid' const ascii = renderMermaidASCII('graph LR; A --> B', { colorMode: 'truecolor' }) ``` #### D) Node.js / Backend ```typescript import { renderMermaidSVG } from 'beautiful-mermaid' const svg = renderMermaidSVG('graph TD; A --> B', { bg: '#fff', fg: '#000' }) // svg is a string — write to file, embed in HTML, etc. ``` ### Step 4: Validate If the diagram fails to render: 1. **Check syntax** — read the parser source in `[email protected]` (`node_modules/beautiful-mermaid/src/parser.ts`) for exact parser rules 2. **Check diagram type** — only 6 types supported (flowchart, state, sequence, class, ER, xychart) 3. **Simplify** — strip to minimal reproducing case 4. **Fallback** — show raw mermaid source in a styled code block **Common parser pitfalls:** - `stateDiagram` (v1) is NOT supported — use `stateDiagram-v2` - `journey` diagrams are NOT supported - `pie` charts are NOT supported (use `xychart-beta` bar chart instead) - `gantt` diagrams are NOT supported - `gitgraph` is NOT supported - Node IDs cannot start with numbers - Semicolons work as line separators: `graph TD; A --> B; B --> C` ## Failsafe Process If `beautiful-mermaid` cannot parse the diagram: 1. **Read the parser source**: install the pinned package (`npm i [email protected]`) and read `node_modules/beautiful-mermaid/src/parser.ts` 2. **Check tests for examples**: `node_modules/beautiful-mermaid/src/__tests__/` 3. **Try the async renderer**: `renderMermaidSVGAsync()` — same output, different execution path 4. **Degrade to code block**: Wrap in ``` ```mermaid ``` ``` with a note that it needs a standard Mermaid renderer 5. **Convert to supported type**: e.g., `journey` → flowchart, `pie` → xychart bar, `gantt` → flowchart with timeline ## Multi-Diagram Documents For documents with multiple diagrams (like PLATFORM-ANALYSIS.md). This is a `<script>` fragment, not a full document — ensure the `<head>` it's inserted into carries the same CSP meta tag as the standalone template above (`script-src`/`connect-src` scoped to `https://esm.sh`): ```html <script type="module"> import { renderMermaidSVGAsync } from 'https://esm.sh/[email protected]' const theme = { bg: '#1a1b26', fg: '#a9b1d6', accent: '#7aa2f7', transparent: true } const els = document.querySelectorAll('[data-code]') // Yield between diagrams to avoid blocking for (const el of els) { await new Promise(r => requestAnimationFrame(r)) try { el.innerHTML = await renderMermaidSVGAsync(el.dataset.code, theme) } catch (e) { el.innerHTML = `<pre style="color:#ff453a">${e.message}</pre>` } } </script> ``` ARGUMENTS: $ARGUMENTS
© coco-research · MIT · coco-research/coco