"""mermaid_to_drawio.py — convert a Mermaid flowchart/classDiagram into a
real, editable draw.io (.drawio / diagrams.net) file.
Where this came from (P18-T16, composed — not ported): like
`dependency-diagram` before it, there's no Mermaid-to-drawio conversion
mechanism in PinkyAI's own engine to port from. Scoped after a web search
turned up exactly the problem this exists to sidestep: draw.io's own
built-in Mermaid importer is real but documented-flaky for flowcharts and
UML class diagrams specifically (the jgraph/drawio issue tracker: import
failures, silent fallback to a flattened image instead of real shapes, a
50,000-character ceiling, a pinned Mermaid version lagging upstream
syntax). This script never goes through that importer — it parses
Mermaid source directly and writes a real `<mxGraphModel>` document
(drawio's actual native file format), so the result opens as a genuinely
editable diagram every time.
See README.md for the full provenance note, usage examples, and the
"Honest scope" section (this converts `flowchart`/`graph` and
`classDiagram` only — every other Mermaid diagram kind gets a clear,
named error, not a silent misparse).
"""
from __future__ import annotations
import argparse
import html
import json
import re
import sys
from collections import deque
from dataclasses import dataclass, field
from pathlib import Path
class MermaidParseError(ValueError):
"""Raised for Mermaid source this script can't (or deliberately won't)
convert — an unsupported diagram type, or a line that doesn't match
any recognized statement shape. Always a plain, specific message;
never a silent best-effort guess."""
_KNOWN_UNSUPPORTED_TYPES = (
"sequencediagram",
"statediagram-v2",
"statediagram",
"erdiagram",
"gantt",
"pie",
"journey",
"gitgraph",
"mindmap",
"timeline",
"requirementdiagram",
"quadrantchart",
"sankey-beta",
"block-beta",
"xychart-beta",
"c4context",
)
def sniff_diagram_type(text: str) -> str:
"""Returns "flowchart", "classDiagram", or the (lowercased) Mermaid
keyword of an unsupported/unrecognized diagram type, read off the
first real (non-blank, non `%%`-comment) line."""
for raw_line in text.splitlines():
line = raw_line.strip()
if not line or line.startswith("%%"):
continue
first_word = re.split(r"[\s{]", line, maxsplit=1)[0].lower()
if first_word in ("graph", "flowchart"):
return "flowchart"
if first_word == "classdiagram":
return "classDiagram"
if first_word in _KNOWN_UNSUPPORTED_TYPES:
return first_word
return first_word or "unknown"
return "empty"
SHAPE_DELIMS: list[tuple[str, str, str]] = [
("([", "])", "stadium"),
("[[", "]]", "subroutine"),
("[(", ")]", "cylinder"),
("((", "))", "circle"),
("{{", "}}", "hexagon"),
("[/", "/]", "rect"),
("[\\", "\\]", "rect"),
("[/", "\\]", "rect"),
("[\\", "/]", "rect"),
("[", "]", "rect"),
("(", ")", "round"),
("{", "}", "diamond"),
]
_NODE_ID_RE = re.compile(r"^[A-Za-z0-9_\-]+")
_HEADER_RE = re.compile(r"^(graph|flowchart)\b\s*(TD|TB|LR|RL|BT)?", re.IGNORECASE)
@dataclass
class FlowNode:
id: str
label: str
shape: str = "rect"
has_explicit_shape: bool = False
subgraph: str | None = None
fill: str | None = None
stroke: str | None = None
@dataclass
class FlowEdge:
source: str
target: str
label: str | None = None
line_style: str = "solid"
start_arrow: bool = False
end_arrow: bool = True
@dataclass
class Subgraph:
id: str
title: str
parent: str | None = None
node_ids: list[str] = field(default_factory=list)
child_ids: list[str] = field(default_factory=list)
x: float = 0.0
y: float = 0.0
width: float = 0.0
height: float = 0.0
@dataclass
class Flowchart:
direction: str = "TD"
nodes: dict[str, FlowNode] = field(default_factory=dict)
node_order: list[str] = field(default_factory=list)
edges: list[FlowEdge] = field(default_factory=list)
subgraphs: dict[str, Subgraph] = field(default_factory=dict)
subgraph_order: list[str] = field(default_factory=list)
root_subgraph_ids: list[str] = field(default_factory=list)
def _mask_literal_spans(line: str) -> str:
"""Returns `line` with the interior of any `[...]`/`(...)`/`{...}`/
`"..."` span replaced by `x` placeholders (same length; delimiters and
everything outside a span untouched). Protects edge-operator and
node-id scanning from misfiring on a dash/pipe/ampersand that's really
just part of a label's text (`A["a-b & c"]` must not look like an
edge or a fan-out)."""
out = list(line)
depth = 0
i = 0
n = len(line)
while i < n:
ch = line[i]
if ch == '"' and depth == 0:
j = line.find('"', i + 1)
if j == -1:
break
for k in range(i + 1, j):
out[k] = "x"
i = j + 1
continue
if ch in "([{":
depth += 1
i += 1
continue
if ch in ")]}":
if depth > 0:
depth -= 1
i += 1
continue
if depth > 0:
out[i] = "x"
i += 1
return "".join(out)
_EDGE_RE = re.compile(
r"(?P<lhead><)?"
r"(?P<run1>[-.=]{2,})"
r"(?:(?P<mid>[^-.=<>]+?)(?P<run2>[-.=]{2,}))?"
r"(?P<rhead>>)?"
r"(?:\|(?P<plabel>[^|]*)\|)?"
)
def _classify_edge_run(run1: str, run2: str | None) -> str:
combined = run1 + (run2 or "")
if "." in combined:
return "dashed"
if "=" in combined:
return "thick"
return "solid"
def _strip_quotes(text: str) -> str:
text = text.strip()
if len(text) >= 2 and text[0] == text[-1] and text[0] in "\"'":
return text[1:-1]
return text
def _unescape_label(text: str) -> str:
text = _strip_quotes(text)
text = re.sub(r"<br\s*/?>", "\n", text, flags=re.IGNORECASE)
return text.strip()
def parse_node_ref(token: str) -> tuple[str, str | None, str | None]:
"""Parses one node-reference token (e.g. `A[Load Data]`, `B{Valid?}`,
or a bare `C`) into `(id, label_or_None, shape_or_None)`. `label`/
`shape` are `None` when the token is a bare reference with no shape
declared at this mention."""
token = token.strip()
m = _NODE_ID_RE.match(token)
if not m:
raise MermaidParseError(f"couldn't find a node id in {token!r}")
node_id = m.group(0)
rest = token[len(node_id):].strip()
if not rest:
return node_id, None, None
for open_delim, close_delim, shape in SHAPE_DELIMS:
if rest.startswith(open_delim) and rest.endswith(close_delim) and len(rest) >= len(open_delim) + len(close_delim):
inner = rest[len(open_delim): len(rest) - len(close_delim)]
return node_id, _unescape_label(inner), shape
return node_id, None, None
def _register_node(chart: Flowchart, node_id: str, label: str | None, shape: str | None, subgraph_id: str | None) -> None:
existing = chart.nodes.get(node_id)
if existing is None:
chart.nodes[node_id] = FlowNode(
id=node_id,
label=label if label is not None else node_id,
shape=shape or "rect",
has_explicit_shape=shape is not None,
subgraph=subgraph_id,
)
chart.node_order.append(node_id)
return
if shape is not None and not existing.has_explicit_shape:
existing.label = label if label is not None else existing.label
existing.shape = shape
existing.has_explicit_shape = True
if existing.subgraph is None and subgraph_id is not None:
existing.subgraph = subgraph_id
_COLOR_PROP_RE = re.compile(r"(fill|stroke)\s*:\s*(#[0-9a-fA-F]{3,8}|[A-Za-z]+)")
def _parse_style_props(props: str) -> tuple[str | None, str | None]:
fill = stroke = None
for prop, value in _COLOR_PROP_RE.findall(props):
if prop == "fill":
fill = value
elif prop == "stroke":
stroke = value
return fill, stroke
def parse_flowchart(text: str) -> Flowchart:
chart = Flowchart()
header_consumed = False
class_defs: dict[str, tuple[str | None, str | None]] = {}
class_assignments: dict[str, str] = {}
direct_styles: dict[str, tuple[str | None, str | None]] = {}
subgraph_stack: list[str] = []
anon_subgraph_counter = 0
for raw_line in text.splitlines():
line = raw_line.strip()
if not line or line.startswith("%%"):
continue
if not header_consumed:
m = _HEADER_RE.match(line)
if not m:
raise MermaidParseError(f"expected a `graph`/`flowchart` header line, got {line!r}")
chart.direction = (m.group(2) or "TD").upper()
header_consumed = True
continue
if line == "end":
if not subgraph_stack:
raise MermaidParseError("unmatched `end` (no open `subgraph` to close)")
subgraph_stack.pop()
continue
if line.startswith("subgraph"):
rest = line[len("subgraph"):].strip()
anon_subgraph_counter += 1
if not rest:
sub_id = f"subgraph{anon_subgraph_counter}"
title = sub_id
elif rest.startswith('"'):
sub_id = f"subgraph{anon_subgraph_counter}"
title = _strip_quotes(rest)
else:
sid, label, _shape = parse_node_ref(rest)
if label is not None:
sub_id, title = sid, label
else:
sub_id = title = sid
parent = subgraph_stack[-1] if subgraph_stack else None
chart.subgraphs[sub_id] = Subgraph(id=sub_id, title=title, parent=parent)
chart.subgraph_order.append(sub_id)
if parent:
chart.subgraphs[parent].child_ids.append(sub_id)
else:
chart.root_subgraph_ids.append(sub_id)
subgraph_stack.append(sub_id)
continue
if line.startswith("direction "):
continue
if line.startswith("classDef "):
m2 = re.match(r"classDef\s+(\S+)\s+(.*)$", line)
if m2:
class_defs[m2.group(1)] = _parse_style_props(m2.group(2))
continue
if line.startswith("style "):
m2 = re.match(r"style\s+(\S+)\s+(.*)$", line)
if m2:
direct_styles[m2.group(1)] = _parse_style_props(m2.group(2))
continue
if line.startswith("class ") and not line.startswith("classDef"):
m2 = re.match(r"class\s+([^\s]+)\s+(\S+)\s*;?$", line)
if m2:
for nid in m2.group(1).split(","):
class_assignments[nid.strip()] = m2.group(2)
continue
if line.startswith(("click ", "linkStyle ")):
continue
_parse_flow_statement(chart, line, subgraph_stack[-1] if subgraph_stack else None)
if subgraph_stack:
raise MermaidParseError(f"unclosed subgraph(s): {', '.join(subgraph_stack)} (missing `end`)")
for node_id, node in chart.nodes.items():
fill = stroke = None
class_name = class_assignments.get(node_id)
if class_name and class_name in class_defs:
fill, stroke = class_defs[class_name]
if node_id in direct_styles:
direct_fill, direct_stroke = direct_styles[node_id]
fill = direct_fill or fill
stroke = direct_stroke or stroke
node.fill, node.stroke = fill, stroke
return chart
def _split_masked(original: str, masked: str, sep: str) -> list[str]:
"""Splits `original` at positions where `masked` has an unmasked
`sep` character (i.e. one that's really a top-level separator, not
text inside a label)."""
parts: list[str] = []
start = 0
for i, ch in enumerate(masked):
if ch == sep:
parts.append(original[start:i])
start = i + 1
parts.append(original[start:])
return parts
def _parse_flow_statement(chart: Flowchart, line: str, subgraph_id: str | None) -> None:
masked = _mask_literal_spans(line)
matches = list(_EDGE_RE.finditer(masked))
def register_segment(orig_seg: str, masked_seg: str) -> list[str]:
ids: list[str] = []
for token in _split_masked(orig_seg, masked_seg, "&"):
token = token.strip()
if not token:
continue
node_id, label, shape = parse_node_ref(token)
_register_node(chart, node_id, label, shape, subgraph_id)
ids.append(node_id)
return ids
if not matches:
register_segment(line, masked)
return
node_lists: list[list[str]] = []
cursor = 0
for m in matches:
node_lists.append(register_segment(line[cursor: m.start()], masked[cursor: m.start()]))
cursor = m.end()
node_lists.append(register_segment(line[cursor:], masked[cursor:]))
for i, m in enumerate(matches):
left_ids = node_lists[i]
right_ids = node_lists[i + 1]
line_style = _classify_edge_run(m.group("run1"), m.group("run2"))
raw_label = m.group("plabel")
if raw_label is None:
raw_label = m.group("mid")
label = raw_label.strip() if raw_label else None
for lid in left_ids:
for rid in right_ids:
chart.edges.append(
FlowEdge(
source=lid,
target=rid,
label=label,
line_style=line_style,
start_arrow=bool(m.group("lhead")),
end_arrow=bool(m.group("rhead")),
)
)
RANK_GAP = 90
ORDER_GAP = 40
CHAR_WIDTH = 7.2
MIN_NODE_WIDTH = 70
MAX_NODE_WIDTH = 260
NODE_HEIGHT_LINE = 20
MIN_NODE_HEIGHT = 40
SUBGRAPH_PAD = 24
SUBGRAPH_TOP_PAD = 40
def _node_size(node: FlowNode) -> tuple[float, float]:
lines = node.label.split("\n") or [""]
longest = max((len(ln) for ln in lines), default=0)
width = min(MAX_NODE_WIDTH, max(MIN_NODE_WIDTH, int(longest * CHAR_WIDTH) + 30))
height = max(MIN_NODE_HEIGHT, NODE_HEIGHT_LINE * len(lines) + 20)
if node.shape == "circle":
side = max(width, height)
width = height = side
return float(width), float(height)
def compute_ranks(node_order: list[str], edges: list[FlowEdge]) -> dict[str, int]:
"""Longest-path-from-sources layering via Kahn's algorithm. A node
that's part of a cycle (never reaches in-degree 0 through the normal
walk) is pushed to one extra rank past everything already placed —
a simple, honest cycle-breaking rule, not a real feedback-arc-set
minimization; see README.md's Honest scope."""
adj: dict[str, list[str]] = {n: [] for n in node_order}
indeg: dict[str, int] = {n: 0 for n in node_order}
for e in edges:
if e.source in adj and e.target in indeg:
adj[e.source].append(e.target)
indeg[e.target] += 1
rank: dict[str, int] = {n: 0 for n in node_order}
work = dict(indeg)
queue: deque[str] = deque(n for n in node_order if work[n] == 0)
seen = set(queue)
while queue:
u = queue.popleft()
for v in adj[u]:
rank[v] = max(rank[v], rank[u] + 1)
work[v] -= 1
if work[v] <= 0 and v not in seen:
seen.add(v)
queue.append(v)
remaining = [n for n in node_order if n not in seen]
if remaining:
base = (max(rank.values()) + 1) if rank else 0
for n in remaining:
rank[n] = base
return rank
def layout_flowchart(chart: Flowchart) -> None:
"""Assigns real (x, y, width, height) geometry to every node (as
dynamic `_layout_*` attributes — draw.io has no on-load layout
engine, so this script's own layered layout is the only one that
runs) and computes each subgraph's bounding box."""
if not chart.node_order:
return
ranks = compute_ranks(chart.node_order, chart.edges)
subgraph_group_index: dict[str | None, int] = {None: -1}
for i, sid in enumerate(chart.subgraph_order):
subgraph_group_index[sid] = i
by_rank: dict[int, list[str]] = {}
for nid in chart.node_order:
by_rank.setdefault(ranks[nid], []).append(nid)
for rank_nodes in by_rank.values():
rank_nodes.sort(key=lambda nid: (subgraph_group_index.get(chart.nodes[nid].subgraph), chart.node_order.index(nid)))
sizes = {nid: _node_size(chart.nodes[nid]) for nid in chart.node_order}
horizontal = chart.direction in ("LR", "RL")
primary_offset = 0.0
for r in sorted(by_rank):
rank_nodes = by_rank[r]
band_primary_size = max((sizes[n][1] if horizontal else sizes[n][0]) for n in rank_nodes)
secondary_offset = 0.0
for nid in rank_nodes:
w, h = sizes[nid]
node = chart.nodes[nid]
if horizontal:
x, y = primary_offset, secondary_offset
secondary_offset += h + ORDER_GAP
else:
x, y = secondary_offset, primary_offset
secondary_offset += w + ORDER_GAP
node._layout_w, node._layout_h = w, h
node._layout_x, node._layout_y = x, y
primary_offset += band_primary_size + RANK_GAP
if chart.direction == "BT":
total_h = primary_offset
for nid in chart.node_order:
node = chart.nodes[nid]
node._layout_y = total_h - node._layout_y - node._layout_h
elif chart.direction == "RL":
total_w = primary_offset
for nid in chart.node_order:
node = chart.nodes[nid]
node._layout_x = total_w - node._layout_x - node._layout_w
_compute_subgraph_bboxes(chart)
def _compute_subgraph_bboxes(chart: Flowchart) -> None:
for nid in chart.node_order:
node = chart.nodes[nid]
if node.subgraph:
chart.subgraphs[node.subgraph].node_ids.append(nid)
def bbox_of(sid: str) -> tuple[float, float, float, float]:
xs0: list[float] = []
ys0: list[float] = []
xs1: list[float] = []
ys1: list[float] = []
sub = chart.subgraphs[sid]
for nid in sub.node_ids:
node = chart.nodes[nid]
xs0.append(node._layout_x)
ys0.append(node._layout_y)
xs1.append(node._layout_x + node._layout_w)
ys1.append(node._layout_y + node._layout_h)
for cid in sub.child_ids:
cx, cy, cw, ch = bbox_of(cid)
xs0.append(cx)
ys0.append(cy)
xs1.append(cx + cw)
ys1.append(cy + ch)
if not xs0:
xs0 = ys0 = xs1 = ys1 = [0.0]
x0, y0 = min(xs0) - SUBGRAPH_PAD, min(ys0) - SUBGRAPH_TOP_PAD
x1, y1 = max(xs1) + SUBGRAPH_PAD, max(ys1) + SUBGRAPH_PAD
sub.x, sub.y, sub.width, sub.height = x0, y0, x1 - x0, y1 - y0
return sub.x, sub.y, sub.width, sub.height
for sid in chart.root_subgraph_ids:
bbox_of(sid)
_SHAPE_STYLE = {
"rect": "rounded=0;whiteSpace=wrap;html=1;",
"round": "rounded=1;arcSize=20;whiteSpace=wrap;html=1;",
"stadium": "rounded=1;arcSize=50;whiteSpace=wrap;html=1;",
"subroutine": "shape=process;whiteSpace=wrap;html=1;",
"cylinder": "shape=cylinder3;whiteSpace=wrap;html=1;boundedLbl=1;",
"circle": "ellipse;whiteSpace=wrap;html=1;",
"diamond": "rhombus;whiteSpace=wrap;html=1;",
"hexagon": "shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;",
}
def _xml_escape_attr(text: str) -> str:
return html.escape(text, quote=True)
def _label_html(label: str) -> str:
escaped = _xml_escape_attr(label)
return escaped.replace("\n", "<br>")
def _edge_style(edge: FlowEdge) -> str:
parts = ["edgeStyle=orthogonalEdgeStyle", "rounded=0", "html=1"]
parts.append("startArrow=classic;startFill=1" if edge.start_arrow else "startArrow=none")
parts.append("endArrow=classic;endFill=1" if edge.end_arrow else "endArrow=none")
if edge.line_style == "dashed":
parts.append("dashed=1")
elif edge.line_style == "thick":
parts.append("strokeWidth=3")
return ";".join(parts) + ";"
def render_flowchart_xml(chart: Flowchart) -> str:
cells: list[str] = ['<mxCell id="0" />', '<mxCell id="1" parent="0" />']
def sub_cell_id(sid: str) -> str:
return f"sub-{sid}"
def node_cell_id(nid: str) -> str:
return f"node-{nid}"
def emit_subgraph(sid: str) -> None:
sub = chart.subgraphs[sid]
parent_cell = sub_cell_id(sub.parent) if sub.parent else "1"
origin_x, origin_y = (chart.subgraphs[sub.parent].x, chart.subgraphs[sub.parent].y) if sub.parent else (0.0, 0.0)
style = (
"rounded=0;whiteSpace=wrap;html=1;fillColor=none;strokeColor=#8a8a8a;"
"verticalAlign=top;align=left;spacingLeft=8;spacingTop=6;fontStyle=1;dashed=1;"
"container=1;collapsible=0;"
)
cells.append(
f'<mxCell id="{sub_cell_id(sid)}" value="{_xml_escape_attr(sub.title)}" style="{style}" '
f'vertex="1" parent="{parent_cell}">'
f'<mxGeometry x="{sub.x - origin_x:.1f}" y="{sub.y - origin_y:.1f}" '
f'width="{sub.width:.1f}" height="{sub.height:.1f}" as="geometry" /></mxCell>'
)
for cid in sub.child_ids:
emit_subgraph(cid)
for sid in chart.root_subgraph_ids:
emit_subgraph(sid)
for nid in chart.node_order:
node = chart.nodes[nid]
origin_x, origin_y = (chart.subgraphs[node.subgraph].x, chart.subgraphs[node.subgraph].y) if node.subgraph else (0.0, 0.0)
parent_cell = sub_cell_id(node.subgraph) if node.subgraph else "1"
style = _SHAPE_STYLE.get(node.shape, _SHAPE_STYLE["rect"])
if node.fill:
style += f"fillColor={node.fill};"
if node.stroke:
style += f"strokeColor={node.stroke};"
x, y = node._layout_x - origin_x, node._layout_y - origin_y
cells.append(
f'<mxCell id="{node_cell_id(nid)}" value="{_label_html(node.label)}" style="{style}" '
f'vertex="1" parent="{parent_cell}">'
f'<mxGeometry x="{x:.1f}" y="{y:.1f}" width="{node._layout_w:.1f}" height="{node._layout_h:.1f}" as="geometry" /></mxCell>'
)
for i, edge in enumerate(chart.edges):
if edge.source not in chart.nodes or edge.target not in chart.nodes:
continue
label_attr = _label_html(edge.label) if edge.label else ""
cells.append(
f'<mxCell id="edge-{i}" value="{label_attr}" style="{_edge_style(edge)}" edge="1" parent="1" '
f'source="{node_cell_id(edge.source)}" target="{node_cell_id(edge.target)}">'
f'<mxGeometry relative="1" as="geometry" /></mxCell>'
)
total_w = max((chart.nodes[n]._layout_x + chart.nodes[n]._layout_w for n in chart.node_order), default=800)
total_h = max((chart.nodes[n]._layout_y + chart.nodes[n]._layout_h for n in chart.node_order), default=600)
return _wrap_mxfile("\n ".join(cells), total_w, total_h)
def flowchart_to_json(chart: Flowchart) -> dict:
return {
"type": "flowchart",
"direction": chart.direction,
"nodes": [
{"id": n, "label": chart.nodes[n].label, "shape": chart.nodes[n].shape, "subgraph": chart.nodes[n].subgraph}
for n in chart.node_order
],
"edges": [
{"source": e.source, "target": e.target, "label": e.label, "style": e.line_style}
for e in chart.edges
],
"subgraphs": [
{"id": s, "title": chart.subgraphs[s].title, "parent": chart.subgraphs[s].parent}
for s in chart.subgraph_order
],
}
@dataclass
class ClassMember:
text: str
is_method: bool
@dataclass
class ClassBox:
id: str
display_label: str | None = None
fields: list[ClassMember] = field(default_factory=list)
methods: list[ClassMember] = field(default_factory=list)
x: float = 0.0
y: float = 0.0
width: float = 0.0
height: float = 0.0
@dataclass
class ClassRelation:
left: str
right: str
left_end: str
right_end: str
dashed: bool
label: str | None = None
@dataclass
class ClassDiagram:
classes: dict[str, ClassBox] = field(default_factory=dict)
class_order: list[str] = field(default_factory=list)
relations: list[ClassRelation] = field(default_factory=list)
_CLASS_BLOCK_OPEN_RE = re.compile(r'^class\s+([A-Za-z0-9_]+)(?:\[(?P<label>.*)\])?\s*\{$')
_CLASS_DECL_RE = re.compile(r'^class\s+([A-Za-z0-9_]+)(?:\[(?P<label>.*)\])?\s*$')
_CLASS_INLINE_MEMBER_RE = re.compile(r"^([A-Za-z0-9_]+)\s*:\s*(.+)$")
_LEND_RE = re.compile(r"^(<\||<|\*|o)")
_REND_RE = re.compile(r"(\|>|>|\*|o)$")
_REL_RE = re.compile(
r'^(?P<lhs>[A-Za-z0-9_]+)\s+'
r'(?:"(?P<lmult>[^"]*)"\s+)?'
r'(?P<op>[<>|*o.\-]+)\s*'
r'(?:"(?P<rmult>[^"]*)"\s+)?'
r'(?P<rhs>[A-Za-z0-9_]+)'
r'(?:\s*:\s*(?P<label>.*))?$'
)
def _ensure_class(diagram: ClassDiagram, name: str, display_label: str | None = None) -> ClassBox:
if name not in diagram.classes:
diagram.classes[name] = ClassBox(id=name, display_label=display_label)
diagram.class_order.append(name)
elif display_label is not None and diagram.classes[name].display_label is None:
diagram.classes[name].display_label = display_label
return diagram.classes[name]
def _decode_relation_op(op: str) -> tuple[str, str, bool]:
dashed = ".." in op
left_match = _LEND_RE.match(op)
right_match = _REND_RE.search(op)
left_tok = left_match.group(1) if left_match else ""
right_tok = right_match.group(1) if right_match else ""
def decode(tok: str) -> str:
return {
"<|": "triangle", "|>": "triangle",
"<": "open", ">": "open",
"*": "diamond-filled", "o": "diamond",
}.get(tok, "")
return decode(left_tok), decode(right_tok), dashed
def parse_class_diagram(text: str) -> ClassDiagram:
diagram = ClassDiagram()
header_consumed = False
in_block: str | None = None
for raw_line in text.splitlines():
line = raw_line.strip().rstrip(";")
if not line or line.startswith("%%"):
continue
if not header_consumed:
if line.lower() != "classdiagram":
raise MermaidParseError(f"expected a `classDiagram` header line, got {line!r}")
header_consumed = True
continue
if in_block is not None:
if line == "}":
in_block = None
continue
box = diagram.classes[in_block]
is_method = "(" in line
member = ClassMember(text=line, is_method=is_method)
(box.methods if is_method else box.fields).append(member)
continue
m = _CLASS_BLOCK_OPEN_RE.match(line)
if m:
label = _unescape_label(m.group("label")) if m.group("label") is not None else None
_ensure_class(diagram, m.group(1), display_label=label)
in_block = m.group(1)
continue
m = _CLASS_DECL_RE.match(line)
if m:
label = _unescape_label(m.group("label")) if m.group("label") is not None else None
_ensure_class(diagram, m.group(1), display_label=label)
continue
if line.startswith("<<") or line.startswith("note "):
continue
m = _CLASS_INLINE_MEMBER_RE.match(line)
if m and "--" not in line and ".." not in line:
box = _ensure_class(diagram, m.group(1))
member_text = m.group(2).strip()
is_method = "(" in member_text
(box.methods if is_method else box.fields).append(ClassMember(text=member_text, is_method=is_method))
continue
m = _REL_RE.match(line)
if m and ("--" in m.group("op") or ".." in m.group("op")):
_ensure_class(diagram, m.group("lhs"))
_ensure_class(diagram, m.group("rhs"))
left_end, right_end, dashed = _decode_relation_op(m.group("op"))
label = m.group("label").strip() if m.group("label") else None
diagram.relations.append(
ClassRelation(left=m.group("lhs"), right=m.group("rhs"), left_end=left_end, right_end=right_end, dashed=dashed, label=label)
)
continue
raise MermaidParseError(f"unrecognized classDiagram statement: {line!r}")
if in_block is not None:
raise MermaidParseError(f"unclosed class block for {in_block!r} (missing `}}`)")
return diagram
CLASS_TITLE_HEIGHT = 30
CLASS_MEMBER_HEIGHT = 18
CLASS_MIN_WIDTH = 160
CLASS_H_GAP = 80
CLASS_V_GAP = 60
CLASS_PER_ROW = 4
def layout_class_diagram(diagram: ClassDiagram) -> None:
"""A simple grid layout (fixed columns, row height driven by the
tallest box seen so far isn't tracked — each row instead uses a
generous fixed band) — classDiagram has no subgraph-style nesting in
Mermaid, so there's no rank/edge-direction structure worth threading
a layered layout through the way flowcharts get one."""
for i, cid in enumerate(diagram.class_order):
box = diagram.classes[cid]
longest = max(
[len(cid)] + [len(m.text) for m in box.fields] + [len(m.text) for m in box.methods],
default=len(cid),
)
box.width = max(CLASS_MIN_WIDTH, int(longest * CHAR_WIDTH) + 24)
n_members = len(box.fields) + len(box.methods)
dividers = 2 if (box.fields and box.methods) else (1 if n_members else 0)
box.height = CLASS_TITLE_HEIGHT + n_members * CLASS_MEMBER_HEIGHT + dividers * 6 + 10
col = i % CLASS_PER_ROW
row = i // CLASS_PER_ROW
box.x = col * (CLASS_MIN_WIDTH + CLASS_H_GAP)
box.y = row * (CLASS_TITLE_HEIGHT + 6 * CLASS_MEMBER_HEIGHT + CLASS_V_GAP)
_UML_END_STYLE = {
"triangle": ("block", 0),
"diamond": ("diamond", 0),
"diamond-filled": ("diamond", 1),
"open": ("open", 1),
"": ("none", 0),
}
_CLASS_DIVIDER = "<hr>"
def _class_label_html(box: ClassBox) -> str:
parts = [f"<b>{_xml_escape_attr(box.display_label or box.id)}</b>"]
if box.fields:
parts.append(_CLASS_DIVIDER)
parts.extend(_xml_escape_attr(m.text) for m in box.fields)
if box.methods:
parts.append(_CLASS_DIVIDER)
parts.extend(_xml_escape_attr(m.text) for m in box.methods)
html_parts = [parts[0]]
prev_was_break = True
for p in parts[1:]:
if p == _CLASS_DIVIDER:
html_parts.append(p)
prev_was_break = True
else:
html_parts.append(p if prev_was_break else f"<br>{p}")
prev_was_break = False
return "".join(html_parts)
def render_class_diagram_xml(diagram: ClassDiagram) -> str:
cells: list[str] = ['<mxCell id="0" />', '<mxCell id="1" parent="0" />']
for cid in diagram.class_order:
box = diagram.classes[cid]
style = "rounded=0;whiteSpace=wrap;html=1;align=left;verticalAlign=top;spacingLeft=6;spacingTop=6;"
cells.append(
f'<mxCell id="class-{cid}" value="{_class_label_html(box)}" style="{style}" vertex="1" parent="1">'
f'<mxGeometry x="{box.x:.1f}" y="{box.y:.1f}" width="{box.width:.1f}" height="{box.height:.1f}" as="geometry" /></mxCell>'
)
for i, rel in enumerate(diagram.relations):
if rel.left not in diagram.classes or rel.right not in diagram.classes:
continue
start_shape, start_fill = _UML_END_STYLE[rel.left_end]
end_shape, end_fill = _UML_END_STYLE[rel.right_end]
style = (
"edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;"
f"startArrow={start_shape};startFill={start_fill};endArrow={end_shape};endFill={end_fill};"
)
if rel.dashed:
style += "dashed=1;"
label_attr = _label_html(rel.label) if rel.label else ""
cells.append(
f'<mxCell id="rel-{i}" value="{label_attr}" style="{style}" edge="1" parent="1" '
f'source="class-{rel.left}" target="class-{rel.right}">'
f'<mxGeometry relative="1" as="geometry" /></mxCell>'
)
total_w = max((diagram.classes[c].x + diagram.classes[c].width for c in diagram.class_order), default=800)
total_h = max((diagram.classes[c].y + diagram.classes[c].height for c in diagram.class_order), default=600)
return _wrap_mxfile("\n ".join(cells), total_w, total_h)
def class_diagram_to_json(diagram: ClassDiagram) -> dict:
return {
"type": "classDiagram",
"classes": [
{
"id": c,
"fields": [m.text for m in diagram.classes[c].fields],
"methods": [m.text for m in diagram.classes[c].methods],
}
for c in diagram.class_order
],
"relations": [
{"left": r.left, "right": r.right, "leftEnd": r.left_end, "rightEnd": r.right_end, "dashed": r.dashed, "label": r.label}
for r in diagram.relations
],
}
def _wrap_mxfile(cells_xml: str, content_w: float, content_h: float) -> str:
"""Wraps rendered `<mxCell>` elements in the same `<mxfile>` envelope
a real draw.io "Save As .drawio" produces, so the output opens
directly — no import step, no dialog, nothing that depends on
draw.io's own Mermaid importer succeeding. `id="page1"` is a fixed,
deterministic literal (not a random uuid) so the same input always
produces byte-identical output — genuinely reproducible, and easy to
assert on in tests."""
page_w = max(850, int(content_w) + 40)
page_h = max(1100, int(content_h) + 40)
return (
'<mxfile host="app.diagrams.net" version="24.0.0">\n'
' <diagram id="page1" name="Page-1">\n'
f' <mxGraphModel dx="800" dy="600" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" '
f'arrows="1" fold="1" page="1" pageScale="1" pageWidth="{page_w}" pageHeight="{page_h}" math="0" shadow="0">\n'
" <root>\n"
f" {cells_xml}\n"
" </root>\n"
" </mxGraphModel>\n"
" </diagram>\n"
"</mxfile>\n"
)
def convert(text: str, as_json: bool = False) -> str:
"""Converts Mermaid source `text` (flowchart/graph or classDiagram) to
drawio XML, or to its parsed IR as JSON if `as_json`. Raises
`MermaidParseError` for unsupported/unparseable input."""
diagram_type = sniff_diagram_type(text)
if diagram_type == "flowchart":
chart = parse_flowchart(text)
layout_flowchart(chart)
return json.dumps(flowchart_to_json(chart), indent=2) if as_json else render_flowchart_xml(chart)
if diagram_type == "classDiagram":
diagram = parse_class_diagram(text)
layout_class_diagram(diagram)
return json.dumps(class_diagram_to_json(diagram), indent=2) if as_json else render_class_diagram_xml(diagram)
if diagram_type == "empty":
raise MermaidParseError("no diagram content found (empty input)")
raise MermaidParseError(
f"unsupported diagram type {diagram_type!r} — only `flowchart`/`graph` and `classDiagram` are "
"converted; see README.md's Honest scope for the full list of what's out of scope and why"
)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="Convert a Mermaid flowchart/classDiagram into a real, editable draw.io (.drawio) file."
)
parser.add_argument("input", help="Path to a .mmd/.mermaid file, or '-' to read from stdin")
parser.add_argument("-o", "--output", help="Write the .drawio XML here instead of stdout")
parser.add_argument("--json", action="store_true", help="Print the parsed diagram data as JSON instead of drawio XML")
args = parser.parse_args(argv)
if args.input == "-":
text = sys.stdin.read()
else:
path = Path(args.input)
if not path.is_file():
print(f"mermaid-to-drawio: {args.input!r} is not a file", file=sys.stderr)
return 1
text = path.read_text()
try:
output = convert(text, as_json=args.json)
except MermaidParseError as exc:
print(f"mermaid-to-drawio: {exc}", file=sys.stderr)
return 1
if args.output:
Path(args.output).write_text(output)
else:
print(output)
return 0
if __name__ == "__main__":
sys.exit(main())