Skip to content

Agent skill that turns natural language, code, Terraform/K8s, SQL, OpenAPI, AsyncAPI, Protobuf and GraphQL sources into editable, tested draw.io architecture diagrams: incremental sync, multi-view projection, drift diff, CI architecture tests, whiteboard derasterize, interactive HTML/PPTX/Mermaid exports.

feat: drawio2mermaid.py — convert a .drawio to Mermaid flowchart (v1.26.0) (#74)

Agents365.aid5f1f6d33997
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c7ed5d9..7f4403b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,20 @@ All notable changes to **drawio-skill** are documented here. The format is based
on [Keep a Changelog](https://keepachangelog.com/), and the project follows
semantic-ish versioning (the `version:` field in `skills/drawio-skill/SKILL.md`).
+## [1.26.0] — 2026-07-04
+### Added
+- **Diagram → Mermaid** (`scripts/drawio2mermaid.py`) — convert a `.drawio` into
+ a Mermaid `flowchart` you can paste into Markdown and have GitHub / GitLab /
+ docs render natively (diagrams-as-code). Containers become `subgraph`s, edge
+ labels are kept, and a few shapes map to Mermaid node forms (cylinder →
+ database `[( )]`, rhombus → decision `{ }`). `--fenced` wraps each graph in a
+ ```` ```mermaid ```` block; multi-page files emit one flowchart per page.
+ - `drawio2mermaid.py diagram.drawio` (to stdout) or `--fenced -o out.md`.
+ - Structural conversion only — styling/colours/vendor icons don't survive
+ (Mermaid has no equivalent); keep the `.drawio` for a faithful diagram.
+ - Output validated against the Mermaid renderer + a draw.io round-trip.
+ SKILL.md router + READMEs updated. Suite now 63.
+
## [1.25.0] — 2026-07-03
### Added
- **Animated data-flow SVG** (`scripts/svgflow.py`) — export a `.drawio` to SVG
diff --git a/README.md b/README.md
index 1aead29..67926a2 100644
--- a/README.md
+++ b/README.md
@@ -185,6 +185,9 @@ python3 scripts/drawio2pptx.py c4.drawio -o c4.pptx # needs: pip install pytho
# Animated data-flow SVG — edges "flow" (marching ants); renders on GitHub
python3 scripts/svgflow.py architecture.drawio -o flow.svg
+# Reverse: .drawio → Mermaid flowchart (diagrams-as-code GitHub renders)
+python3 scripts/drawio2mermaid.py architecture.drawio --fenced -o arch.md
+
# any extractor → auto-layout → editable .drawio
python3 scripts/autolayout.py graph.json -o diagram.drawio
```
@@ -197,6 +200,7 @@ python3 scripts/autolayout.py graph.json -o diagram.drawio
| **Diagram → Markdown** | `explain.py` reverses a `.drawio` into a structured description — components by tier, relations, per-page for C4 — for dropping an architecture summary into a README or PR |
| **Diagram → PowerPoint** | `drawio2pptx.py` turns a multi-page diagram into a 16:9 deck (one page per slide, page name as title) — a C4 model becomes a ready-to-present slideshow |
| **Animated data-flow** | `svgflow.py` makes a diagram's edges *flow* (marching-ants animation along each arrow) — a self-contained looping SVG that renders on GitHub, in docs, or as a slide background |
+| **Diagram → Mermaid** | `drawio2mermaid.py` converts a `.drawio` into a Mermaid `flowchart` (containers → subgraphs, edge labels kept) — paste it into Markdown as diagrams-as-code that GitHub renders natively |
| **Sequence engine** | `seqlayout.py` computes lifeline / activation-bar / arrow geometry from a message list — no Graphviz, no hand placement |
| **Auto-layout** | Graphviz places nodes and routes orthogonal edges *around* them — removes the manual-coordinate ceiling for large graphs. `--tune` tries both directions and keeps the more readable one |
| **Transitive reduction** | drops edges implied by a longer path, turning a dense hairball into a traceable graph (asyncio: 149 → 46 edges) |
diff --git a/README_CN.md b/README_CN.md
index 8bdcbce..15121a0 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -183,6 +183,9 @@ python3 scripts/drawio2pptx.py c4.drawio -o c4.pptx # 需要: pip install pyth
# 数据流动画 SVG —— 让边「流动」起来(marching ants);GitHub 可直接渲染
python3 scripts/svgflow.py architecture.drawio -o flow.svg
+# 反向:.drawio → Mermaid 流程图(GitHub 原生渲染的 diagrams-as-code)
+python3 scripts/drawio2mermaid.py architecture.drawio --fenced -o arch.md
+
# 任一提取器 → 自动布局 → 可编辑的 .drawio
python3 scripts/autolayout.py graph.json -o diagram.drawio
```
@@ -195,6 +198,7 @@ python3 scripts/autolayout.py graph.json -o diagram.drawio
| **图 → Markdown** | `explain.py` 把一张 `.drawio` 反向描述成结构化文档 —— 按层级列出组件、关系、C4 多页分节 —— 方便把架构摘要塞进 README 或 PR |
| **图 → PowerPoint** | `drawio2pptx.py` 把多页图变成 16:9 幻灯片(每页一张、页名当标题)—— C4 模型一键变成可演示的 slideshow |
| **数据流动画** | `svgflow.py` 让图里的边「流动」起来(沿箭头方向的 marching-ants 动画)—— 自包含循环 SVG,可在 GitHub、文档或幻灯片背景里直接播放 |
+| **图 → Mermaid** | `drawio2mermaid.py` 把 `.drawio` 转成 Mermaid `flowchart`(容器变 subgraph、保留边标签)—— 粘进 Markdown 就是 GitHub 原生渲染的 diagrams-as-code |
| **时序图引擎** | `seqlayout.py` 从消息列表直接算出 lifeline / 激活条 / 箭头几何 —— 不需要 Graphviz,不需要手摆 |
| **自动布局** | Graphviz 自动布点,正交连线**绕开**节点 —— 大图不再需要手动摆坐标。`--tune` 双向各排一次取更可读的 |
| **传递约简** | 删掉被更长路径蕴含的边,把密集的"毛线团"变成可读图(asyncio:149 → 46 条边) |
diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.md
index 40be323..c657780 100644
--- a/skills/drawio-skill/SKILL.md
+++ b/skills/drawio-skill/SKILL.md
@@ -1,6 +1,6 @@
---
name: drawio-skill
-version: 1.25.0
+version: 1.26.0
description: Use when the user requests diagrams, flowcharts, architecture diagrams, ER diagrams, UML / sequence / class diagrams, network topology, cloud architecture from Terraform or Kubernetes manifests, ML/DL model figures (Transformer/CNN/LSTM), mind maps, or any visualization. Also use proactively when explaining systems with 3+ components, complex data flows, or relationships that benefit from visual representation. Best suited when the diagram needs custom styling, rich shape vocabulary, swimlanes, or exportable images (PNG/SVG/PDF/JPG). Generates .drawio XML and exports locally via the native draw.io desktop CLI.
license: MIT
homepage: https://github.com/Agents365-ai/drawio-skill
@@ -54,6 +54,7 @@ When the workflow references one of these, read it on demand — none of them ne
| `scripts/explain.py` | The user wants to **describe / document / summarize an existing `.drawio` in words** (reverse of generating one) — `explain.py diagram.drawio` emits structured Markdown: components grouped by container/tier, relations (`A —label→ B`), per-page sections for multi-page/C4. Good for a README/PR summary or a text-only read-out |
| `scripts/drawio2pptx.py` | The user wants a **PowerPoint deck / slides from a diagram** — `drawio2pptx.py diagram.drawio -o deck.pptx` puts each page on its own 16:9 slide (page name as title), so a multi-page **C4 model** becomes a ready-to-present deck. Needs `python-pptx` (`pip install python-pptx`) + the draw.io CLI |
| `scripts/svgflow.py` | The user wants an **animated / "flowing" diagram** (data-flow, moving edges) — `svgflow.py diagram.drawio -o flow.svg` exports to SVG and makes every edge a marching-ants animation (dashes travel along the arrows). Self-contained looping `.svg` that renders on GitHub / any browser; `--speed` / `--dash` / `--reverse` |
+| `scripts/drawio2mermaid.py` | The user wants to **convert a `.drawio` into Mermaid text** (diagrams-as-code for a Markdown file that GitHub renders) — `drawio2mermaid.py diagram.drawio` emits a `flowchart` (containers → `subgraph`s, edge labels kept, cylinder/rhombus shapes mapped); `--fenced` wraps in ```mermaid, multi-page → one graph per page. Structural only (styling/icons don't survive) |
| `scripts/sqlerd.py` | The user wants an **ER diagram from SQL DDL** — parses `CREATE TABLE` statements into per-table nodes (columns with PK/FK markers) and crow's-foot FK edges for autolayout |
| `scripts/seqlayout.py` | The user wants a **sequence diagram** — describe participants + messages as JSON and the script computes all lifeline/activation/arrow geometry deterministically (no hand-placed coordinates, no Graphviz needed) |
| `scripts/c4.py` | The user wants a **C4 model** (System Context / Container / Component) — levels JSON in, one multi-page `.drawio` out with official C4 shapes/colors and **click-to-drill-down** links between levels |
diff --git a/skills/drawio-skill/scripts/drawio2mermaid.py b/skills/drawio-skill/scripts/drawio2mermaid.py
new file mode 100644
index 0000000..cd582af
--- /dev/null
+++ b/skills/drawio-skill/scripts/drawio2mermaid.py
@@ -0,0 +1,153 @@
+#!/usr/bin/env python3
+"""Convert a .drawio into Mermaid flowchart text (diagrams-as-code).
+
+The other reverse tool, `explain.py`, turns a diagram into prose; this turns it
+into a **Mermaid `flowchart`** you can paste into a Markdown file and have
+GitHub / GitLab / docs render natively — handy when you want the diagram to live
+as maintainable text next to the code. Containers become `subgraph`s, edge
+labels are kept, and a few shapes map to Mermaid node forms (cylinder → database
+`[( )]`, rhombus → decision `{ }`, else `[ ]`).
+
+ python3 drawio2mermaid.py architecture.drawio # Mermaid to stdout
+ python3 drawio2mermaid.py c4.drawio --fenced -o out.md # ```mermaid fenced
+
+Multi-page files emit one flowchart per page. This is a structural conversion —
+styling, colours and vendor icons do not survive (Mermaid has no equivalent);
+for a faithful, richly-styled diagram keep the `.drawio`.
+
+Usage: python3 drawio2mermaid.py <file.drawio> [-o out] [--direction TD|LR] [--fenced]
+"""
+import argparse
+import html
+import re
+import sys
+import xml.etree.ElementTree as ET
+
+
+def clean(text):
+ """Strip the HTML draw.io stores in labels; keep line breaks as <br/>."""
+ if not text:
+ return ""
+ text = re.sub(r"<br\s*/?>", "\n", text, flags=re.I)
+ text = re.sub(r"<[^>]+>", "", text)
+ text = html.unescape(text)
+ return re.sub(r"[ \t]+", " ", text).strip()
+
+
+def esc(label):
+ """Mermaid-safe quoted label: escape quotes, newlines -> <br/>."""
+ label = label.replace('"', "&quot;").replace("\n", "<br/>")
+ return label or " "
+
+
+def node_form(safe_id, label, style):
+ """Mermaid node declaration, shape chosen from the draw.io style."""
+ lbl = f'"{esc(label)}"'
+ if "shape=cylinder" in style or "shape=datastore" in style:
+ return f"{safe_id}[({lbl})]" # database
+ if "rhombus" in style:
+ return f"{safe_id}{{{lbl}}}" # decision
+ if "ellipse" in style or "shape=cloud" in style:
+ return f"{safe_id}(({lbl}))" # circle-ish
+ return f"{safe_id}[{lbl}]" # default box
+
+
+def cells_of(page):
+ """(cell, id, label) for a page, unwrapping UserObject/object wrappers."""
+ model = page.find("mxGraphModel")
+ root = model.find("root") if model is not None else None
+ if root is None:
+ return None
+ out = []
+ for child in root:
+ if child.tag == "mxCell":
+ out.append((child, child.get("id"), clean(child.get("value"))))
+ elif child.tag in ("UserObject", "object"):
+ inner = child.find("mxCell")
+ if inner is not None:
+ inner.set("id", child.get("id", ""))
+ out.append((inner, child.get("id"),
+ clean(child.get("label") or child.get("value"))))
+ return out
+
+
+def page_to_mermaid(page, direction):
+ cells = cells_of(page)
+ if cells is None:
+ return "%% (compressed page — skipped)"
+ label = {cid: lbl for _, cid, lbl in cells}
+ style = {cid: (c.get("style") or "") for c, cid, _ in cells}
+ parents = {c.get("parent") for c, _, _ in cells if c.get("parent")}
+
+ verts = [(c, cid) for c, cid, _ in cells if c.get("vertex") == "1"]
+ containers = {cid for c, cid in verts if cid in parents}
+ leaves = [(c, cid) for c, cid in verts
+ if cid not in containers and "edgeLabel" not in style.get(cid, "")]
+
+ sid = {cid: f"n{i}" for i, (_, cid) in enumerate(leaves)} # mermaid-safe ids
+ lines = [f"flowchart {direction}"]
+
+ # Nodes, grouped into subgraphs by their container.
+ by_container = {}
+ for c, cid in leaves:
+ parent = c.get("parent")
+ key = parent if parent in containers else None
+ by_container.setdefault(key, []).append(cid)
+
+ def emit_node(cid, indent):
+ lines.append(indent + node_form(sid[cid], label.get(cid) or cid, style.get(cid, "")))
+
+ for cid in by_container.get(None, []):
+ emit_node(cid, " ")
+ for cont, members in by_container.items():
+ if cont is None:
+ continue
+ lines.append(f' subgraph {sid.get(cont, "g_" + cont)}["{esc(label.get(cont) or "")}"]')
+ for cid in members:
+ emit_node(cid, " ")
+ lines.append(" end")
+
+ # Edges (only between leaves we emitted).
+ for c, _, _ in cells:
+ if c.get("edge") != "1":
+ continue
+ s, t = c.get("source"), c.get("target")
+ if s in sid and t in sid:
+ lbl = clean(c.get("value"))
+ arrow = f'-->|"{esc(lbl)}"|' if lbl else "-->"
+ lines.append(f" {sid[s]} {arrow} {sid[t]}")
+ return "\n".join(lines)
+
+
+def main():
+ ap = argparse.ArgumentParser(description="Convert a .drawio to Mermaid flowchart text.")
+ ap.add_argument("file")
+ ap.add_argument("-o", "--output", help="output path (default: stdout)")
+ ap.add_argument("--direction", default="TD", choices=["TD", "LR", "TB", "RL", "BT"])
+ ap.add_argument("--fenced", action="store_true", help="wrap each graph in a ```mermaid fence")
+ args = ap.parse_args()
+ try:
+ root = ET.parse(args.file).getroot()
+ except (ET.ParseError, OSError) as exc:
+ sys.exit(f"error: cannot parse {args.file}: {exc}")
+ pages = root.findall("diagram") or [root]
+
+ blocks = []
+ for i, page in enumerate(pages, 1):
+ graph = page_to_mermaid(page, args.direction)
+ name = page.get("name")
+ if len(pages) > 1 and name:
+ graph = f"%% Page {i}: {name}\n{graph}"
+ blocks.append(f"```mermaid\n{graph}\n```" if args.fenced else graph)
+
+ text = ("\n\n".join(blocks)).rstrip() + "\n"
+ if args.output:
+ with open(args.output, "w", encoding="utf-8") as f:
+ f.write(text)
+ sys.stderr.write(f"wrote {args.output} ({len(pages)} page{'s' if len(pages) != 1 else ''})\n")
+ else:
+ sys.stdout.write(text)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index d3650e2..8eb755e 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -848,6 +848,41 @@ class TestImportersCli(unittest.TestCase):
out, _ = sf.animate(self.FLOW_SVG, 2, "8 2", reverse=True)
self.assertIn("stroke-dashoffset:10", out) # +(8+2), toward source
+ def test_drawio2mermaid_flowchart(self):
+ # Reuses EXPLAIN_PAGE: container "Tier" with A/B, cylinder DB, edge a->c "reads".
+ doc = ('<mxfile><diagram name="P1"><mxGraphModel><root>'
+ + self.EXPLAIN_PAGE + "</root></mxGraphModel></diagram></mxfile>")
+ with tempfile.TemporaryDirectory() as d:
+ path = os.path.join(d, "arch.drawio")
+ self._write(path, doc)
+ mmd = run("drawio2mermaid.py", path, "--direction", "TD").stdout
+ self.assertTrue(mmd.startswith("flowchart TD"))
+ self.assertIn("subgraph", mmd)
+ self.assertIn('["Tier"]', mmd) # container -> subgraph title
+ self.assertIn('["A"]', mmd)
+ self.assertIn('[("DB")]', mmd) # cylinder -> database shape
+ self.assertIn('-->|"reads"|', mmd) # labeled edge
+
+ def test_drawio2mermaid_multipage_fenced(self):
+ doc = ('<mxfile>'
+ '<diagram name="P1"><mxGraphModel><root>'
+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'
+ '<mxCell id="x" value="Solo" vertex="1" parent="1" style="rounded=1;">'
+ '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'
+ '</root></mxGraphModel></diagram>'
+ '<diagram name="P2"><mxGraphModel><root>'
+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'
+ '<mxCell id="y" value="Two" vertex="1" parent="1" style="rounded=1;">'
+ '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'
+ '</root></mxGraphModel></diagram></mxfile>')
+ with tempfile.TemporaryDirectory() as d:
+ path = os.path.join(d, "multi.drawio")
+ self._write(path, doc)
+ mmd = run("drawio2mermaid.py", path, "--fenced").stdout
+ self.assertEqual(mmd.count("```mermaid"), 2) # one fence per page
+ self.assertIn("%% Page 2: P2", mmd)
+ self.assertIn('["Solo"]', mmd)
+
SQL = ("CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255));\n"
"CREATE TABLE orders (\n"
" id INT,\n"