Coverage for app / documents / visuals / mermaid / flowchart.py: 94%
429 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""``flowchart`` and ``graph``: read as Mermaid's ``flow.jison`` reads them,
2laid out in layers, drawn in Mermaid's default theme.
4Read: a node is an id and an optional shape (``A[x]``, ``A(x)``, ``A([x])``,
5``A[[x]]``, ``A[(x)]``, ``A((x))``, ``A(((x)))``, ``A>x]``, ``A{x}``,
6``A{{x}}``, ``A[/x/]``, ``A[\\x\\]``, ``A[/x\\]``, ``A[\\x/]``, or v11's
7``A@{ shape: …, label: … }``) and ``:::class``; a link is ``-->``, ``---``,
8``-.->``, ``-.-``, ``==>``, ``===``, ``~~~``, with ``o`` / ``x`` / ``<`` ends,
9extra dashes for length, and text as ``-- x -->`` or ``-->|x|``; ``A & B``
10links each. ``subgraph`` … ``end`` (with ``direction``), ``classDef``,
11``class``, ``style`` and ``linkStyle`` style them; ``click`` and the
12accessibility lines are left out (nothing in a PDF is clicked).
13"""
15from __future__ import annotations
17import re
18from dataclasses import dataclass, field
19from typing import ClassVar
21from reportlab.lib.colors import Color
23from ..colors import parse_color
24from ..registry import Layout
25from ..theme import Theme
26from . import look
27from .base import Diagram, MermaidSyntaxError, Statement, register_diagram
28from .canvas import Canvas, block_size
29from .compound import (
30 MAX_EDGES,
31 MAX_NODES,
32 Cluster,
33 Direction,
34 Edge,
35 Graph,
36 Node,
37 layout,
38)
39from .labels import fit
40from .layered import Spacing
41from .markers import draw_edge
42from .shapes import SHAPES, Look
44_DIRECTIONS: dict[str, Direction] = {
45 "TB": "TB", "TD": "TB", "BT": "BT", "LR": "LR", "RL": "RL",
46 "v": "TB", "^": "BT", ">": "LR", "<": "RL",
47} # fmt: skip
49#: (opener, closer, shape), longest opener first. ``[/`` and ``[\\`` close
50#: either way, and the closer names the shape.
51_OPENERS: tuple[tuple[str, str, str], ...] = (
52 ("(((", ")))", "doublecircle"),
53 ("((", "))", "circle"),
54 ("([", "])", "stadium"),
55 ("[[", "]]", "subroutine"),
56 ("[(", ")]", "cylinder"),
57 ("{{", "}}", "hexagon"),
58 ("[/", "/]", "lean_right"),
59 ("[\\", "\\]", "lean_left"),
60 ("(", ")", "rounded"),
61 ("[", "]", "rect"),
62 ("{", "}", "diamond"),
63 (">", "]", "asymmetric"),
64)
65_SLANTS = {("[/", "\\]"): "trapezoid", ("[\\", "/]"): "inv_trapezoid"}
66#: v11's ``@{ shape: … }`` names.
67_NAMED_SHAPES: dict[str, str] = {
68 **dict.fromkeys(("rect", "rectangle", "proc", "process"), "rect"),
69 **dict.fromkeys(("rounded", "event"), "rounded"),
70 **dict.fromkeys(("stadium", "pill", "terminal"), "stadium"),
71 **dict.fromkeys(("subroutine", "subprocess", "subproc", "fr-rect", "framed-rectangle"), "subroutine"),
72 **dict.fromkeys(("cyl", "cylinder", "database", "db"), "cylinder"),
73 **dict.fromkeys(("circle", "circ", "sm-circ", "small-circle", "start"), "circle"),
74 **dict.fromkeys(("dbl-circ", "double-circle"), "doublecircle"),
75 **dict.fromkeys(("diam", "diamond", "decision", "question"), "diamond"),
76 **dict.fromkeys(("hex", "hexagon", "prepare"), "hexagon"),
77 **dict.fromkeys(("lean-r", "lean-right", "in-out"), "lean_right"),
78 **dict.fromkeys(("lean-l", "lean-left", "out-in"), "lean_left"),
79 **dict.fromkeys(("trap-b", "trapezoid", "trapezoid-bottom", "priority"), "trapezoid"),
80 **dict.fromkeys(("trap-t", "inv-trapezoid", "trapezoid-top", "manual"), "inv_trapezoid"),
81 **dict.fromkeys(("odd", "flag"), "asymmetric"),
82} # fmt: skip
84_ID = re.compile(r"[^\W](?:[\w.]|-(?![-.>=]))*", re.UNICODE)
85_SPACE = re.compile(r"\s*")
86_TEXT_START = re.compile(r"\s*(?:[\w-]+@)?(?P<start>[<ox])?(?P<kind>--|==|-\.)\s+")
87_TEXT_END = {
88 "--": re.compile(r"\s*(?P<dashes>-{2,})(?P<end>[->ox])"),
89 "==": re.compile(r"\s*(?P<dashes>={2,})(?P<end>[=>ox])"),
90 "-.": re.compile(r"\s*(?P<dashes>\.+)-(?P<end>[>ox])?"),
91}
92_LINKS = (
93 (
94 "normal",
95 re.compile(r"\s*(?:[\w-]+@)?(?P<start>[<ox])?(?P<dashes>-{2,})(?P<end>[->ox])"),
96 ),
97 (
98 "thick",
99 re.compile(r"\s*(?:[\w-]+@)?(?P<start>[<ox])?(?P<dashes>={2,})(?P<end>[=>ox])"),
100 ),
101 (
102 "dotted",
103 re.compile(r"\s*(?:[\w-]+@)?(?P<start>[<ox])?-(?P<dashes>\.+)-(?P<end>[>ox])?"),
104 ),
105 ("invisible", re.compile(r"\s*(?:[\w-]+@)?(?P<dashes>~{3,})")),
106)
107_PIPE = re.compile(r"\s*\|(?P<text>[^|]*)\|")
108_MARKER = {">": "arrow", "<": "arrow", "x": "cross", "o": "circle"}
109_KIND_OF_TEXT_START = {"--": "normal", "==": "thick", "-.": "dotted"}
112@dataclass
113class FlowNode:
114 id: str
115 text: str
116 shape: str = "rect"
117 classes: list[str] = field(default_factory=list)
118 style: dict[str, str] = field(default_factory=dict)
119 #: The subgraphs it was named in, innermost open at each mention.
120 named_in: list[str] = field(default_factory=list)
121 shaped: bool = False
124@dataclass
125class FlowEdge:
126 source: str
127 target: str
128 kind: str
129 start: str | None
130 end: str | None
131 minlen: int
132 text: str | None
133 style: dict[str, str] = field(default_factory=dict)
136@dataclass
137class Subgraph:
138 id: str
139 title: str
140 parent: str | None
141 direction: Direction | None = None
142 classes: list[str] = field(default_factory=list)
143 style: dict[str, str] = field(default_factory=dict)
144 closed_at: int = 0
147def parse_style(text: str) -> dict[str, str]:
148 """``fill:#f9f,stroke:#333,stroke-width:4px`` as a mapping."""
149 out: dict[str, str] = {}
150 for part in re.split(r"[,;]", text):
151 key, sep, value = part.partition(":")
152 if sep and key.strip():
153 out[key.strip().lower()] = value.strip()
154 return out
157def _width(value: str | None, default: float) -> float:
158 if not value:
159 return default
160 m = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*(px)?\s*", value)
161 if not m:
162 return default
163 return max(0.0, min(12.0, float(m.group(1)) * 0.75))
166def _dash(value: str | None) -> tuple[float, ...] | None:
167 if not value:
168 return None
169 parts = re.findall(r"\d+(?:\.\d+)?", value)
170 dash = tuple(min(30.0, float(p) * 0.75) for p in parts[:6])
171 return dash if dash and any(dash) else None
174class _Cursor:
175 def __init__(self, text: str, line: int) -> None:
176 self.text = text
177 self.at = 0
178 self.line = line
180 def skip_space(self) -> None:
181 self.at = _SPACE.match(self.text, self.at).end() # type: ignore[union-attr]
183 def done(self) -> bool:
184 self.skip_space()
185 return self.at >= len(self.text)
187 def peek(self, token: str) -> bool:
188 return self.text.startswith(token, self.at)
190 def error(self, message: str) -> MermaidSyntaxError:
191 return MermaidSyntaxError(self.line, message)
194@register_diagram
195class Flowchart(Diagram):
196 keywords = ("flowchart", "flowchart-elk", "graph")
197 noun = "a flowchart"
198 #: A rhombus's label wraps narrower: it grows by its width and height.
199 NARROW_WIDTH: ClassVar[float] = 110.0
201 def __init__(self, direction: Direction) -> None:
202 self.direction = direction
203 self.nodes: dict[str, FlowNode] = {}
204 self.edges: list[FlowEdge] = []
205 self.subgraphs: dict[str, Subgraph] = {}
206 self.class_defs: dict[str, dict[str, str]] = {}
207 self.link_styles: dict[int | str, dict[str, str]] = {}
208 self._open: list[Subgraph] = []
209 self._closed = 0
211 @classmethod
212 def parse(cls, header: Statement, statements: list[Statement]) -> Flowchart:
213 words = header.text.split()
214 direction: Direction = "TB"
215 if len(words) > 1:
216 found = _DIRECTIONS.get(words[1])
217 if found is None:
218 raise MermaidSyntaxError(
219 header.line, "the direction is not one Mermaid knows"
220 )
221 direction = found
222 if len(words) > 2:
223 statements = [Statement(header.line, " ".join(words[2:])), *statements]
224 chart = cls(direction)
225 lines = iter(statements)
226 for statement in lines:
227 text = statement.text
228 first = text.split(maxsplit=1)[0]
229 if first.startswith("accDescr") and "{" in text and "}" not in text:
230 for later in lines:
231 if "}" in later.text:
232 break
233 continue
234 chart._statement(statement)
235 if chart._open:
236 raise MermaidSyntaxError(None, "a subgraph has no 'end'")
237 chart._settle()
238 return chart
240 def _statement(self, statement: Statement) -> None:
241 text, line = statement.text, statement.line
242 first, _, rest = text.partition(" ")
243 rest = rest.strip()
244 if first == "subgraph":
245 self._subgraph(rest, line)
246 elif text == "end":
247 if not self._open:
248 raise MermaidSyntaxError(line, "'end' closes no subgraph")
249 self._closed += 1
250 self._open.pop().closed_at = self._closed
251 elif first == "direction":
252 found = _DIRECTIONS.get(rest)
253 if found is None:
254 raise MermaidSyntaxError(line, "the direction is not one Mermaid knows")
255 if self._open:
256 self._open[-1].direction = found
257 elif first == "classDef":
258 names, _, style = rest.partition(" ")
259 for name in names.split(","):
260 self.class_defs.setdefault(name.strip(), {}).update(parse_style(style))
261 elif first == "class":
262 ids, _, name = rest.rpartition(" ")
263 for item in ids.split(","):
264 self._classes_of(item.strip()).append(name.strip())
265 elif first == "style":
266 item, _, style = rest.partition(" ")
267 self._style_of(item.strip()).update(parse_style(style))
268 elif first == "linkStyle":
269 which, _, style = rest.partition(" ")
270 for key in which.split(","):
271 key = key.strip()
272 index: int | str = int(key) if key.isdigit() else key
273 self.link_styles.setdefault(index, {}).update(parse_style(style))
274 elif first in (
275 "click",
276 "accTitle",
277 "accTitle:",
278 "accDescr",
279 "accDescr:",
280 ) or first.startswith(("accTitle:", "accDescr:")):
281 return
282 else:
283 self._chain(_Cursor(text, line))
285 def _classes_of(self, item: str) -> list[str]:
286 """Mermaid's ``setClass``: a class on an id not yet seen is lost."""
287 if item in self.subgraphs:
288 return self.subgraphs[item].classes
289 if item in self.nodes:
290 return self.nodes[item].classes
291 return []
293 def _style_of(self, item: str) -> dict[str, str]:
294 if item in self.subgraphs:
295 return self.subgraphs[item].style
296 return self._node(item, None).style
298 def _subgraph(self, rest: str, line: int) -> None:
299 m = re.fullmatch(r"([^\s\[\]\"]+)\s*\[(.*)\]", rest)
300 if m:
301 sid, title = m.group(1), m.group(2).strip()
302 elif rest.startswith('"') and rest.endswith('"') and len(rest) > 1:
303 sid, title = "", rest
304 elif not rest or re.search(r"\s", rest):
305 sid, title = "", rest
306 else:
307 sid, title = rest, rest
308 if not sid:
309 sid = f"subGraph{len(self.subgraphs)}"
310 if sid == "end":
311 raise MermaidSyntaxError(line, "'end' cannot name a subgraph")
312 parent = self._open[-1].id if self._open else None
313 graph = Subgraph(sid, title, parent)
314 self.subgraphs[sid] = graph
315 self._open.append(graph)
316 if sid in self.nodes and not self.nodes[sid].shaped:
317 del self.nodes[sid]
319 def _node(self, nid: str, line: int | None) -> FlowNode:
320 if nid == "end":
321 raise MermaidSyntaxError(
322 line, "'end' cannot be a node id: write 'End' or 'END'"
323 )
324 node = self.nodes.get(nid)
325 if node is None:
326 node = self.nodes[nid] = FlowNode(nid, nid)
327 if line is not None and self._open:
328 node.named_in.append(self._open[-1].id)
329 return node
331 # ── chains: nodes and links ───────────────────────────────────────────
333 def _chain(self, cursor: _Cursor) -> None:
334 groups = [self._group(cursor)]
335 links: list[tuple[str, str | None, str | None, int, str | None]] = []
336 while not cursor.done():
337 links.append(self._link(cursor))
338 groups.append(self._group(cursor))
339 for (sources, targets), (kind, start, end, minlen, text) in zip(
340 zip(groups, groups[1:]), links
341 ):
342 for s in sources:
343 for t in targets:
344 self.edges.append(FlowEdge(s, t, kind, start, end, minlen, text))
345 if len(self.nodes) > MAX_NODES:
346 raise MermaidSyntaxError(None, f"it has more than {MAX_NODES} nodes")
347 if len(self.edges) > MAX_EDGES:
348 raise MermaidSyntaxError(None, f"it has more than {MAX_EDGES} links")
350 def _group(self, cursor: _Cursor) -> list[str]:
351 ids = [self._vertex(cursor)]
352 while True:
353 cursor.skip_space()
354 if not cursor.peek("&"):
355 return ids
356 cursor.at += 1
357 ids.append(self._vertex(cursor))
359 def _vertex(self, cursor: _Cursor) -> str:
360 cursor.skip_space()
361 m = _ID.match(cursor.text, cursor.at)
362 if not m:
363 raise cursor.error("a node id is missing")
364 nid = m.group(0)
365 cursor.at = m.end()
366 if nid in self.subgraphs:
367 return nid
368 node = self._node(nid, cursor.line)
369 if cursor.peek("@{"):
370 self._named_shape(cursor, node)
371 else:
372 self._shape(cursor, node)
373 while cursor.peek(":::"):
374 cursor.at += 3
375 m = re.compile(r"[\w-]+").match(cursor.text, cursor.at)
376 if not m:
377 raise cursor.error("a class name is missing after ':::'")
378 node.classes.append(m.group(0))
379 cursor.at = m.end()
380 return nid
382 def _shape(self, cursor: _Cursor, node: FlowNode) -> None:
383 for opener, closer, shape in _OPENERS:
384 if not cursor.peek(opener):
385 continue
386 cursor.at += len(opener)
387 text, used = self._shape_text(cursor, opener, closer)
388 node.text = text
389 node.shape = _SLANTS.get((opener, used), shape)
390 node.shaped = True
391 return
393 def _shape_text(self, cursor: _Cursor, opener: str, closer: str) -> tuple[str, str]:
394 text = cursor.text
395 closers = [closer]
396 if opener in ("[/", "[\\"):
397 closers = ["/]", "\\]"]
398 start = cursor.at
399 lead = _SPACE.match(text, start).end() # type: ignore[union-attr]
400 if text.startswith('"', lead):
401 end_quote = text.find('"', lead + 1)
402 if end_quote < 0:
403 raise cursor.error("a quoted label is not closed")
404 after = _SPACE.match(text, end_quote + 1).end() # type: ignore[union-attr]
405 for c in closers:
406 if text.startswith(c, after):
407 cursor.at = after + len(c)
408 return text[lead : end_quote + 1], c
409 raise cursor.error("a node's shape is not closed")
410 if len(closer) == 1 and opener in ("(", "[", "{"):
411 depth = 0
412 for i in range(start, len(text)):
413 ch = text[i]
414 if ch == opener:
415 depth += 1
416 elif ch == closer:
417 if depth == 0:
418 cursor.at = i + 1
419 return text[start:i], closer
420 depth -= 1
421 raise cursor.error("a node's shape is not closed")
422 best: tuple[int, str] | None = None
423 for c in closers:
424 i = text.find(c, start)
425 if i >= 0 and (best is None or i < best[0]):
426 best = (i, c)
427 if best is None:
428 raise cursor.error("a node's shape is not closed")
429 cursor.at = best[0] + len(best[1])
430 return text[start : best[0]], best[1]
432 def _named_shape(self, cursor: _Cursor, node: FlowNode) -> None:
433 end = cursor.text.find("}", cursor.at)
434 if end < 0:
435 raise cursor.error("a node's '@{' is not closed")
436 body = cursor.text[cursor.at + 2 : end]
437 cursor.at = end + 1
438 for key, value in re.findall(r"(\w+)\s*:\s*(\"[^\"]*\"|[^,]+)", body):
439 value = value.strip()
440 if key == "shape":
441 node.shape = _NAMED_SHAPES.get(value.strip("\"'"), "rect")
442 elif key == "label":
443 node.text = value
444 node.shaped = True
446 def _link(
447 self, cursor: _Cursor
448 ) -> tuple[str, str | None, str | None, int, str | None]:
449 text = cursor.text
450 m = _TEXT_START.match(text, cursor.at)
451 if m:
452 kind = _KIND_OF_TEXT_START[m.group("kind")]
453 closing = _TEXT_END[m.group("kind")]
454 for found in closing.finditer(text, m.end()):
455 label = text[m.end() : found.start()].strip()
456 if not label:
457 continue
458 cursor.at = found.end()
459 end = found.group("end")
460 minlen = self._length(kind, found.group("dashes"), end)
461 return (
462 kind,
463 _MARKER.get(m.group("start") or ""),
464 _MARKER.get(end or ""),
465 minlen,
466 label,
467 )
468 for kind, pattern in _LINKS:
469 m = pattern.match(text, cursor.at)
470 if not m:
471 continue
472 cursor.at = m.end()
473 end = m.groupdict().get("end")
474 start = m.groupdict().get("start")
475 minlen = self._length(kind, m.group("dashes"), end)
476 label = None
477 pipe = _PIPE.match(text, cursor.at)
478 if pipe:
479 cursor.at = pipe.end()
480 label = pipe.group("text").strip() or None
481 return kind, _MARKER.get(start or ""), _MARKER.get(end or ""), minlen, label
482 raise cursor.error("a link is expected between two nodes")
484 @staticmethod
485 def _length(kind: str, dashes: str, end: str | None) -> int:
486 if kind == "dotted":
487 return max(1, len(dashes))
488 if kind == "invisible":
489 return max(1, len(dashes) - 2)
490 # "-->" and "---" are one row long; each dash more is a row more.
491 return max(1, len(dashes) - 1)
493 def _settle(self) -> None:
494 """Each node in the subgraph that closed first of those it was
495 named in, as Mermaid assigns parents; a subgraph's own id is the
496 subgraph, never a node."""
497 for sid in self.subgraphs:
498 self.nodes.pop(sid, None)
499 for node in self.nodes.values():
500 node.named_in = sorted(
501 set(node.named_in), key=lambda s: self.subgraphs[s].closed_at
502 )[:1]
504 # ── drawing ───────────────────────────────────────────────────────────
506 def _look(
507 self, classes: list[str], style: dict[str, str], is_cluster: bool
508 ) -> dict[str, str]:
509 merged: dict[str, str] = {}
510 if not is_cluster:
511 merged.update(self.class_defs.get("default", {}))
512 for name in classes:
513 merged.update(self.class_defs.get(name, {}))
514 merged.update(style)
515 return merged
517 def layout(self, theme: Theme) -> Layout:
518 font, size = theme.regular, look.FONT_SIZE
519 node_lines: dict[str, list[str]] = {}
520 nodes: list[Node] = []
521 for node in self.nodes.values():
522 shape = SHAPES[node.shape]
523 width = self.NARROW_WIDTH if shape.narrow else look.MAX_LINE_WIDTH
524 lines = fit(node.text, font, size, width, look.MAX_LINES)
525 node_lines[node.id] = lines
526 tw, th = block_size(lines, font, size)
527 w, h = shape.size(tw, th, look.PAD_X, look.PAD_Y)
528 nodes.append(
529 Node(
530 node.id,
531 max(w, 20.0),
532 max(h, 18.0),
533 node.named_in[0] if node.named_in else None,
534 )
535 )
536 edge_lines: list[list[str] | None] = []
537 edges: list[Edge] = []
538 for edge in self.edges:
539 lines = fit(edge.text, font, size, 140.0, 4) if edge.text else None
540 edge_lines.append(lines)
541 label = None
542 if lines:
543 tw, th = block_size(lines, font, size)
544 label = (tw + 6.0, th + 2.0)
545 edges.append(Edge(edge.source, edge.target, edge.minlen, label))
546 clusters: list[Cluster] = []
547 cluster_lines: dict[str, list[str]] = {}
548 for graph in self.subgraphs.values():
549 lines = (
550 [line for line in fit(graph.title, font, size, 200.0, 2) if line]
551 if graph.title.strip()
552 else []
553 )
554 cluster_lines[graph.id] = lines
555 label = block_size(lines, font, size) if lines else (0.0, 0.0)
556 clusters.append(
557 Cluster(
558 graph.id, graph.parent, label, graph.direction, look.CLUSTER_PAD
559 )
560 )
561 shapes = {node.id: SHAPES[node.shape] for node in self.nodes.values()}
562 placed = layout(
563 Graph(
564 self.direction,
565 nodes,
566 edges,
567 clusters,
568 Spacing(look.NODE_SEP, look.RANK_SEP, look.EDGE_SEP),
569 ),
570 lambda nid, box, toward: shapes[nid].boundary(box, toward),
571 )
572 canvas = Canvas(placed.width, placed.height)
573 depth = {c.id: self._depth(c.id) for c in clusters}
574 for cid in sorted(placed.clusters, key=lambda c: depth[c]):
575 box = placed.clusters[cid]
576 graph = self.subgraphs[cid]
577 styled = self._look(graph.classes, graph.style, True)
578 canvas.rect(
579 box.x, box.y, box.width, box.height,
580 fill=parse_color(styled.get("fill"), look.CLUSTER_FILL),
581 stroke=parse_color(styled.get("stroke"), look.CLUSTER_STROKE),
582 width=_width(styled.get("stroke-width"), look.NODE_STROKE_WIDTH),
583 dash=_dash(styled.get("stroke-dasharray")),
584 ) # fmt: skip
585 lines = cluster_lines[cid]
586 if lines:
587 _, th = block_size(lines, font, size)
588 canvas.lines(
589 box.cx, box.y + look.CLUSTER_PAD / 2 + 2 + th / 2, lines,
590 font=font, size=size, color=parse_color(styled.get("color"), look.TEXT),
591 ) # fmt: skip
592 for i, (edge, route) in enumerate(zip(self.edges, placed.routes)):
593 if route is None or edge.kind == "invisible":
594 continue
595 styled = {
596 **self.link_styles.get("default", {}),
597 **self.link_styles.get(i, {}),
598 }
599 width = look.THICK_EDGE_WIDTH if edge.kind == "thick" else look.EDGE_WIDTH
600 draw_edge(
601 canvas,
602 route.points,
603 color=parse_color(styled.get("stroke"), look.LINE),
604 width=_width(styled.get("stroke-width"), width),
605 dash=_dash(styled.get("stroke-dasharray"))
606 or (look.DOTTED if edge.kind == "dotted" else None),
607 start=edge.start,
608 end=edge.end,
609 )
610 for edge, route, lines in zip(self.edges, placed.routes, edge_lines):
611 if (
612 route is None
613 or not lines
614 or route.label is None
615 or edge.kind == "invisible"
616 ):
617 continue
618 label_box(canvas, route.label, lines, font, size, look.TEXT)
619 for node in self.nodes.values():
620 box = placed.nodes[node.id]
621 styled = self._look(node.classes, node.style, False)
622 shape_look = Look(
623 parse_color(styled.get("fill"), look.NODE_FILL),
624 parse_color(styled.get("stroke"), look.NODE_STROKE),
625 _width(styled.get("stroke-width"), look.NODE_STROKE_WIDTH),
626 _dash(styled.get("stroke-dasharray")),
627 )
628 shapes[node.id].draw(canvas, box, shape_look)
629 canvas.lines(
630 box.cx, box.cy, node_lines[node.id],
631 font=font, size=size, color=parse_color(styled.get("color"), look.TEXT),
632 ) # fmt: skip
633 return Layout(
634 canvas.drawing(), placed.width, placed.height, breaks=placed.breaks
635 )
637 def _depth(self, cid: str) -> int:
638 depth = 0
639 current: str | None = cid
640 while current is not None:
641 depth += 1
642 current = self.subgraphs[current].parent
643 return depth
646def label_box(
647 canvas: Canvas,
648 at: tuple[float, float],
649 lines: list[str],
650 font: str,
651 size: float,
652 color: Color,
653 fill: Color = look.EDGE_LABEL,
654) -> None:
655 """An edge's label on a pale ground, as Mermaid draws it."""
656 tw, th = block_size(lines, font, size)
657 x, y = at
658 canvas.rect(
659 x - tw / 2 - 2, y - th / 2 - 1, tw + 4, th + 2,
660 fill=fill, stroke=None, width=0, fill_opacity=0.85,
661 ) # fmt: skip
662 canvas.lines(x, y, lines, font=font, size=size, color=color)