Coverage for app / documents / visuals / mermaid / compound.py: 98%
439 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"""Clusters, directions and borders on top of the layered layout.
3A cluster (a subgraph, a composite state, a namespace) is laid out inside
4first and then placed as one large node of the level above, so its box can
5never overlap anything outside it. An edge that crosses its border gets a
6**port**: a point on the box's top (where the edge comes in) or bottom
7(where it goes out), placed inside the cluster's own layout with the edge's
8inner end, so the edge reaches that end through the cluster's rows rather
9than across its nodes. Which side is known before any size is: ranks need
10only the arcs, so each level is ranked first, its clusters laid out with
11their ports, then the level arranged at the sizes they came to.
13A cluster with no edge across its border may run in its own direction
14(Mermaid honours a subgraph's ``direction`` only then). LR, RL and BT are
15TB with the axes swapped or mirrored. Edges are routed as dagre routes
16them — through their dummies — and cut at each node's own outline.
17"""
19from __future__ import annotations
21from collections.abc import Callable
22from dataclasses import dataclass, field
23from typing import Literal
25from .layered import Beside, Link, Spacing, acyclic, arrange, assign_ranks
27Direction = Literal["TB", "BT", "LR", "RL"]
28DIRECTIONS: tuple[Direction, ...] = ("TB", "BT", "LR", "RL")
29Point = tuple[float, float]
31#: The most nodes and edges a diagram may lay out.
32MAX_NODES = 150
33MAX_EDGES = 300
36@dataclass(frozen=True)
37class Box:
38 """A rectangle, its top left at ``(x, y)``, y down."""
40 x: float
41 y: float
42 width: float
43 height: float
45 @property
46 def cx(self) -> float:
47 return self.x + self.width / 2
49 @property
50 def cy(self) -> float:
51 return self.y + self.height / 2
53 @property
54 def right(self) -> float:
55 return self.x + self.width
57 @property
58 def bottom(self) -> float:
59 return self.y + self.height
61 def moved(self, dx: float, dy: float) -> Box:
62 return Box(self.x + dx, self.y + dy, self.width, self.height)
65@dataclass
66class Node:
67 id: str
68 width: float
69 height: float
70 cluster: str | None = None
71 #: Room beside it across its row: ``(side, width, height)``, screen size.
72 beside: list[tuple[Literal["before", "after"], float, float]] = field(
73 default_factory=list
74 )
77@dataclass
78class Edge:
79 source: str
80 target: str
81 minlen: int = 1
82 #: The label's size, screen points.
83 label: tuple[float, float] | None = None
84 #: A self-loop's room, beside its node.
85 loop: float = 14.0
88@dataclass
89class Cluster:
90 id: str
91 parent: str | None = None
92 #: Its title's size, kept at the top of its box.
93 label: tuple[float, float] = (0.0, 0.0)
94 direction: Direction | None = None
95 padding: float = 10.0
98@dataclass
99class Graph:
100 direction: Direction
101 nodes: list[Node]
102 edges: list[Edge]
103 clusters: list[Cluster] = field(default_factory=list)
104 spacing: Spacing = field(default_factory=lambda: Spacing(24.0, 30.0, 8.0))
105 margin: float = 4.0
108@dataclass
109class Route:
110 points: list[Point]
111 label: Point | None = None
112 loop: bool = False
115@dataclass
116class Placed:
117 width: float
118 height: float
119 nodes: dict[str, Box]
120 clusters: dict[str, Box]
121 #: Per edge, in ``Graph.edges`` order: ``None`` for one that has no route
122 #: (a cluster to its own member).
123 routes: list[Route | None]
124 #: Per node, what was kept beside it.
125 beside: dict[str, list[Box]]
126 #: Where it may be cut across pages: the middle of each band across it
127 #: that no node, cluster, label or loop reaches into.
128 breaks: tuple[float, ...] = ()
131#: Where an edge leaves a node's outline, from its centre toward a point.
132Boundary = Callable[[str, Box, Point], Point]
135def rect_boundary(box: Box, toward: Point) -> Point:
136 """dagre's ``intersectRect``."""
137 x, y = box.cx, box.cy
138 dx, dy = toward[0] - x, toward[1] - y
139 w, h = box.width / 2, box.height / 2
140 if not dx and not dy:
141 return (x, y + h)
142 if abs(dy) * w > abs(dx) * h:
143 if dy < 0:
144 h = -h
145 sx, sy = (h * dx / dy if dy else 0.0), h
146 else:
147 if dx < 0:
148 w = -w
149 sx, sy = w, (w * dy / dx if dx else 0.0)
150 return (x + sx, y + sy)
153def _to_tb(direction: Direction, width: float, height: float) -> tuple[float, float]:
154 return (height, width) if direction in ("LR", "RL") else (width, height)
157def _to_screen(direction: Direction, point: Point) -> Point:
158 x, y = point
159 if direction == "BT":
160 return (x, -y)
161 if direction == "LR":
162 return (y, x)
163 if direction == "RL":
164 return (-y, x)
165 return (x, y)
168@dataclass(frozen=True)
169class _Port:
170 edge: int
171 #: "in" on the side edges arrive (the top, for TB), "out" opposite.
172 side: Literal["in", "out"]
173 #: The edge's end inside the cluster: a node or a cluster in it.
174 inner: str
177@dataclass
178class _Segment:
179 edge: int
180 points: list[Point]
181 #: "main" where the edge runs between its two ends' items; "source" and
182 #: "target" inside a cluster on the way to an end, with its depth.
183 role: Literal["main", "source", "target"]
184 depth: int = 0
185 label: Point | None = None
188@dataclass
189class _Level:
190 width: float
191 height: float
192 nodes: dict[str, Box] = field(default_factory=dict)
193 clusters: dict[str, Box] = field(default_factory=dict)
194 segments: list[_Segment] = field(default_factory=list)
195 loops: dict[int, Route] = field(default_factory=dict)
196 ports: dict[int, Point] = field(default_factory=dict)
197 beside: dict[str, list[Box]] = field(default_factory=dict)
199 def moved(self, dx: float, dy: float) -> _Level:
200 def point(p: Point) -> Point:
201 return (p[0] + dx, p[1] + dy)
203 return _Level(
204 self.width,
205 self.height,
206 {k: b.moved(dx, dy) for k, b in self.nodes.items()},
207 {k: b.moved(dx, dy) for k, b in self.clusters.items()},
208 [
209 _Segment(
210 s.edge,
211 [point(p) for p in s.points],
212 s.role,
213 s.depth,
214 point(s.label) if s.label else None,
215 )
216 for s in self.segments
217 ],
218 {
219 k: Route(
220 [point(p) for p in r.points],
221 point(r.label) if r.label else None,
222 True,
223 )
224 for k, r in self.loops.items()
225 },
226 {k: point(p) for k, p in self.ports.items()},
227 {k: [b.moved(dx, dy) for b in boxes] for k, boxes in self.beside.items()},
228 )
231class _Layout:
232 def __init__(self, graph: Graph, boundary: Boundary) -> None:
233 self.graph = graph
234 self.boundary = boundary
235 self.nodes = {n.id: n for n in graph.nodes}
236 self.clusters = {c.id: c for c in graph.clusters}
237 self.parent: dict[str, str | None] = {n.id: n.cluster for n in graph.nodes}
238 self.parent.update({c.id: c.parent for c in graph.clusters})
239 self.children: dict[str | None, list[str]] = {}
240 for item in [*graph.clusters, *graph.nodes]:
241 key = item.parent if isinstance(item, Cluster) else item.cluster
242 self.children.setdefault(key, []).append(item.id)
243 order = {item: i for i, item in enumerate(self._declared())}
244 for items in self.children.values():
245 items.sort(key=lambda item: order[item])
246 self.depth: dict[str | None, int] = {None: 0}
247 for c in graph.clusters:
248 self.depth[c.id] = self._depth(c.id)
250 def _declared(self) -> list[str]:
251 """Every item in the order the diagram first named it: a cluster
252 where its first member was, or where it was declared if empty."""
253 seen: dict[str, None] = {}
254 for node in self.graph.nodes:
255 chain = []
256 parent = node.cluster
257 while parent is not None:
258 chain.append(parent)
259 parent = self.parent.get(parent)
260 for cluster in reversed(chain):
261 seen.setdefault(cluster, None)
262 seen.setdefault(node.id, None)
263 for cluster in self.graph.clusters:
264 seen.setdefault(cluster.id, None)
265 return list(seen)
267 def _depth(self, cluster: str) -> int:
268 depth = 0
269 parent: str | None = cluster
270 while parent is not None:
271 depth += 1
272 parent = self.parent.get(parent)
273 return depth
275 def _lift(self, item: str, level: str | None) -> str | None:
276 """The item of ``level`` that holds ``item``; ``None`` when it is
277 outside the level, or is the level itself."""
278 current: str | None = item
279 while current is not None:
280 if self.parent.get(current) == level:
281 return current
282 current = self.parent.get(current)
283 return None
285 def run(self) -> Placed:
286 top = self._level(None, [], self.graph.direction)
287 margin = self.graph.margin
288 top = top.moved(margin, margin)
289 routes: list[Route | None] = [None] * len(self.graph.edges)
290 parts: dict[int, list[_Segment]] = {}
291 for segment in top.segments:
292 parts.setdefault(segment.edge, []).append(segment)
293 for edge, segments in parts.items():
294 sources = sorted(
295 (s for s in segments if s.role == "source"), key=lambda s: -s.depth
296 )
297 mains = [s for s in segments if s.role == "main"]
298 targets = sorted(
299 (s for s in segments if s.role == "target"), key=lambda s: s.depth
300 )
301 if not mains:
302 continue
303 points: list[Point] = []
304 for s in [*sources, *mains, *targets]:
305 for p in s.points:
306 if not points or _far(points[-1], p):
307 points.append(p)
308 routes[edge] = Route(points, mains[0].label)
309 for edge, loop in top.loops.items():
310 routes[edge] = loop
311 beside = {k: v for k, v in top.beside.items() if v}
312 height = top.height + 2 * margin
313 spans = [(b.y, b.bottom) for b in [*top.nodes.values(), *top.clusters.values()]]
314 spans += [(b.y, b.bottom) for boxes in beside.values() for b in boxes]
315 for edge, route in zip(self.graph.edges, routes):
316 if route is None:
317 continue
318 if route.loop:
319 ys = [p[1] for p in route.points]
320 spans.append((min(ys), max(ys)))
321 if route.label is not None and edge.label:
322 half = edge.label[1] / 2
323 spans.append((route.label[1] - half, route.label[1] + half))
324 return Placed(
325 top.width + 2 * margin,
326 height,
327 top.nodes,
328 top.clusters,
329 routes,
330 beside,
331 _gaps(spans, height),
332 )
334 def _level(
335 self, level: str | None, ports: list[_Port], direction: Direction
336 ) -> _Level:
337 items = self.children.get(level, [])
338 index = {item: i for i, item in enumerate(items)}
339 count = len(items) + len(ports)
340 edges = self.graph.edges
341 # (edge, source vertex, target vertex, source end, target end)
342 arcs: list[tuple[int, int, int, str | None, str | None]] = []
343 loops: list[int] = []
344 for i, edge in enumerate(edges):
345 s = self._lift(edge.source, level)
346 t = self._lift(edge.target, level)
347 if s is None or t is None:
348 continue
349 if s == t:
350 # A self-loop belongs to the level its node is an item of.
351 if edge.source == edge.target == s and s in self.nodes:
352 loops.append(i)
353 continue
354 arcs.append((i, index[s], index[t], edge.source, edge.target))
355 pins: dict[int, Literal["top", "bottom"]] = {}
356 for k, port in enumerate(ports):
357 vertex = len(items) + k
358 pins[vertex] = "top" if port.side == "in" else "bottom"
359 inner = self._lift(port.inner, level)
360 if inner is None: # pragma: no cover — the parent made the port
361 continue
362 if port.side == "in":
363 arcs.append((port.edge, vertex, index[inner], None, port.inner))
364 else:
365 arcs.append((port.edge, index[inner], vertex, port.inner, None))
366 turned = acyclic(count, [(a[1], a[2]) for a in arcs])
367 links: list[Link] = []
368 for k, (i, s, t, _, _) in enumerate(arcs):
369 edge = edges[i]
370 is_main = s < len(items) and t < len(items)
371 label = _to_tb(direction, *edge.label) if (edge.label and is_main) else None
372 a, b = (t, s) if k in turned else (s, t)
373 links.append(Link(a, b, edge.minlen if is_main else 1, 1.0, label))
374 ranks = assign_ranks(count, links, pins)
376 child_ports: dict[str, list[_Port]] = {}
377 for k, (i, s, t, s_end, t_end) in enumerate(arcs):
378 for vertex, end, is_target in ((s, s_end, False), (t, t_end, True)):
379 if vertex >= len(items) or end is None:
380 continue
381 item = items[vertex]
382 if item not in self.clusters or end == item:
383 continue
384 arrives = is_target != (k in turned)
385 child_ports.setdefault(item, []).append(
386 _Port(i, "in" if arrives else "out", end)
387 )
388 children: dict[str, _Level] = {}
389 for item in items:
390 if item in self.clusters:
391 cluster = self.clusters[item]
392 own = cluster.direction if not child_ports.get(item) else None
393 children[item] = self._level(
394 item, child_ports.get(item, []), own or direction
395 )
397 sizes: list[tuple[float, float]] = []
398 for item in items:
399 if item in children:
400 sizes.append(
401 _to_tb(direction, children[item].width, children[item].height)
402 )
403 else:
404 node = self.nodes[item]
405 sizes.append(_to_tb(direction, node.width, node.height))
406 sizes += [(0.0, 0.0)] * len(ports)
407 beside: list[Beside] = []
408 beside_of: list[str] = []
409 for item in items:
410 node = self.nodes.get(item)
411 if node is None:
412 continue
413 for side, width, height in node.beside:
414 w, h = _to_tb(direction, width, height)
415 beside.append(Beside(index[item], side, w, h))
416 beside_of.append(item)
417 for i in loops:
418 if edges[i].source == item:
419 label = edges[i].label
420 w, h = _to_tb(direction, *(label or (0.0, 0.0)))
421 room = edges[i].loop + (w + 4.0 if label else 0.0)
422 beside.append(
423 Beside(
424 index[item], "after", room, max(h, sizes[index[item]][1])
425 )
426 )
427 beside_of.append(f"\0loop{i}")
428 spacing = self.graph.spacing
429 placed = arrange(sizes, links, ranks, beside, spacing)
431 def screen(p: Point) -> Point:
432 return _to_screen(direction, p)
434 boxes: dict[str, Box] = {}
435 for item in items:
436 v = index[item]
437 cx, cy = screen((placed.x[v], placed.y[v]))
438 w, h = (
439 (children[item].width, children[item].height)
440 if item in children
441 else (self.nodes[item].width, self.nodes[item].height)
442 )
443 boxes[item] = Box(cx - w / 2, cy - h / 2, w, h)
444 beside_boxes: list[Box] = []
445 for item, room, at in zip(beside_of, beside, placed.beside):
446 cx, cy = screen(at)
447 w, h = (
448 (room.height, room.width)
449 if direction in ("LR", "RL")
450 else (room.width, room.height)
451 )
452 beside_boxes.append(Box(cx - w / 2, cy - h / 2, w, h))
453 chains = [[screen(p) for p in chain] for chain in placed.chains]
454 labels = [screen(p) if p else None for p in placed.labels]
456 # The level's box: everything placed, but its own ports.
457 xs: list[float] = []
458 ys: list[float] = []
459 for box in [*boxes.values(), *beside_boxes]:
460 xs += [box.x, box.right]
461 ys += [box.y, box.bottom]
462 for k, chain in enumerate(chains):
463 inner = chain[1:-1]
464 if arcs[k][1] >= len(items):
465 inner = inner[1:]
466 if arcs[k][2] >= len(items):
467 inner = inner[:-1]
468 for p in inner:
469 xs.append(p[0])
470 ys.append(p[1])
471 label = links[k].label
472 if labels[k] is not None and label:
473 w, h = edges[arcs[k][0]].label or (0.0, 0.0)
474 lx, ly = labels[k] # type: ignore[misc]
475 xs += [lx - w / 2, lx + w / 2]
476 ys += [ly - h / 2, ly + h / 2]
477 if not xs:
478 xs, ys = [0.0], [0.0]
479 left, top_, right, bottom = min(xs), min(ys), max(xs), max(ys)
480 cluster = self.clusters.get(level) if level is not None else None
481 if cluster is not None:
482 pad = cluster.padding
483 label_w, label_h = cluster.label
484 left -= pad
485 right += pad
486 top_ -= pad + (label_h + 4.0 if label_h else 0.0)
487 bottom += pad
488 need = label_w + 2 * pad
489 if right - left < need:
490 grow = (need - (right - left)) / 2
491 left -= grow
492 right += grow
493 width, height = right - left, bottom - top_
495 out = _Level(width, height)
497 def local(p: Point) -> Point:
498 return (p[0] - left, p[1] - top_)
500 for item, box in boxes.items():
501 box = box.moved(-left, -top_)
502 if item in children:
503 child = children[item].moved(box.x, box.y)
504 out.nodes.update(child.nodes)
505 out.clusters.update(child.clusters)
506 out.clusters[item] = box
507 out.segments += child.segments
508 out.loops.update(child.loops)
509 for k, v in child.beside.items():
510 out.beside.setdefault(k, []).extend(v)
511 boxes[item] = box
512 children[item] = child
513 else:
514 out.nodes[item] = box
515 boxes[item] = box
516 for item, box in zip(beside_of, beside_boxes):
517 if not item.startswith("\0"):
518 out.beside.setdefault(item, []).append(box.moved(-left, -top_))
519 # Ports sit on the border their side names.
520 port_points: dict[int, Point] = {}
521 for k, port in enumerate(ports):
522 x, y = local(screen((placed.x[len(items) + k], placed.y[len(items) + k])))
523 arrives = port.side == "in"
524 if direction == "TB":
525 y = 0.0 if arrives else height
526 elif direction == "BT":
527 y = height if arrives else 0.0
528 elif direction == "LR":
529 x = 0.0 if arrives else width
530 else:
531 x = width if arrives else 0.0
532 port_points[port.edge] = (min(max(x, 0.0), width), min(max(y, 0.0), height))
533 out.ports = port_points
535 for k, (i, s, t, s_end, t_end) in enumerate(arcs):
536 chain = [local(p) for p in chains[k]]
537 # The bend beside a port is in the gap above the cluster's rows:
538 # the edge runs from the border instead.
539 if s >= len(items) and len(chain) > 2:
540 del chain[1]
541 if t >= len(items) and len(chain) > 2:
542 del chain[-2]
543 a, b = (t, s) if k in turned else (s, t)
544 a_end, b_end = (t_end, s_end) if k in turned else (s_end, t_end)
545 chain[0] = self._end(
546 a, a_end, chain, 0, items, boxes, children, port_points, ports, i
547 )
548 chain[-1] = self._end(
549 b, b_end, chain, -1, items, boxes, children, port_points, ports, i
550 )
551 if k in turned:
552 chain.reverse()
553 label = labels[k]
554 if s < len(items) and t < len(items):
555 role: Literal["main", "source", "target"] = "main"
556 else:
557 inner = t_end if s >= len(items) else s_end
558 role = "source" if inner == edges[i].source else "target"
559 if role == "source" and s >= len(items):
560 chain.reverse()
561 if role == "target" and t >= len(items):
562 chain.reverse()
563 out.segments.append(
564 _Segment(
565 i,
566 chain,
567 role,
568 self.depth.get(level, 0),
569 local(label) if (label and role == "main") else None,
570 )
571 )
572 for i in loops:
573 node = edges[i].source
574 box = boxes[node]
575 room = next(
576 b.moved(-left, -top_)
577 for item, b in zip(beside_of, beside_boxes)
578 if item == f"\0loop{i}"
579 )
580 out.loops[i] = self._loop(i, node, box, room, direction)
581 return out
583 def _end(
584 self,
585 vertex: int,
586 end: str | None,
587 chain: list[Point],
588 at: int,
589 items: list[str],
590 boxes: dict[str, Box],
591 children: dict[str, _Level],
592 port_points: dict[int, Point],
593 ports: list[_Port],
594 edge: int,
595 ) -> Point:
596 toward = chain[1] if at == 0 else chain[-2]
597 if vertex >= len(items):
598 return port_points[ports[vertex - len(items)].edge]
599 item = items[vertex]
600 box = boxes[item]
601 if item in children:
602 if end is not None and end != item and edge in children[item].ports:
603 return children[item].ports[edge]
604 return rect_boundary(box, toward)
605 return self.boundary(item, box, toward)
607 def _loop(
608 self, edge: int, node: str, box: Box, room: Box, direction: Direction
609 ) -> Route:
610 """A self-loop out of the side kept for it and back."""
611 reach = self.graph.edges[edge].loop
612 label = self.graph.edges[edge].label
613 if direction in ("LR", "RL"):
614 # The room is below (LR) or above: the loop leaves downward.
615 down = room.cy >= box.cy
616 sign = 1 if down else -1
617 q = min(box.width / 4, 8.0)
618 y0 = box.bottom if down else box.y
619 points = [
620 (box.cx - q, y0),
621 (box.cx - q - reach * 0.5, y0 + sign * reach),
622 (box.cx + q + reach * 0.5, y0 + sign * reach),
623 (box.cx + q, y0),
624 ]
625 at = (box.cx, y0 + sign * (reach + 4.0 + (label[1] / 2 if label else 0)))
626 else:
627 right = room.cx >= box.cx
628 sign = 1 if right else -1
629 q = min(box.height / 4, 8.0)
630 x0 = box.right if right else box.x
631 points = [
632 (x0, box.cy - q),
633 (x0 + sign * reach, box.cy - q - reach * 0.5),
634 (x0 + sign * reach, box.cy + q + reach * 0.5),
635 (x0, box.cy + q),
636 ]
637 at = (x0 + sign * (reach + 4.0 + (label[0] / 2 if label else 0)), box.cy)
638 points[0] = self.boundary(node, box, points[1])
639 points[-1] = self.boundary(node, box, points[-2])
640 return Route(points, at if label else None, loop=True)
643def _gaps(spans: list[tuple[float, float]], height: float) -> tuple[float, ...]:
644 """The middle of each band from top to bottom that no span reaches."""
645 out: list[float] = []
646 reached = 0.0
647 for lo, hi in sorted(spans):
648 if lo > reached + 1.0:
649 out.append((reached + lo) / 2)
650 reached = max(reached, hi)
651 return tuple(y for y in out if 20.0 < y < height - 20.0)
654def _far(a: Point, b: Point) -> bool:
655 return abs(a[0] - b[0]) > 0.01 or abs(a[1] - b[1]) > 0.01
658def layout(graph: Graph, boundary: Boundary | None = None) -> Placed:
659 """``graph`` laid out; ``boundary`` cuts an edge at a node's outline
660 (a rectangle's by default)."""
661 return _Layout(
662 graph, boundary or (lambda _id, box, toward: rect_boundary(box, toward))
663 ).run()