Coverage for app / documents / visuals / mermaid / classes.py: 91%

384 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""``classDiagram`` and ``classDiagram-v2``. 

2 

3Read: ``class A``, ``class A~T~``, ``class A["label"]``, ``class A { … }`` 

4with its members, ``A : member``, ``<<annotation>>`` (before a name or in a 

5body), relations ``A "1" <|-- "*" B : label`` between any two of ``<|``, 

6``*``, ``o``, ``<``, ``>``, ``|>``, ``()`` either side of ``--`` or ``..``, 

7``namespace N { … }``, ``note "…"`` and ``note for A "…"``, ``classDef``, 

8``cssClass``, ``:::`` and ``style``. ``click``, ``link`` and ``callback`` are 

9left out. 

10 

11A member is shown as Mermaid shows it: a method ``name(args) : type``, an 

12attribute as written, ``~T~`` as ``<T>``; a static one (``$``) underlined. 

13""" 

14 

15from __future__ import annotations 

16 

17import re 

18from dataclasses import dataclass, field 

19 

20from ..colors import parse_color 

21from ..registry import Layout 

22from ..text import ellipsize, measure 

23from ..theme import Theme 

24from . import look 

25from .base import Diagram, MermaidSyntaxError, Statement, register_diagram 

26from .canvas import Canvas, block_size 

27from .compound import ( 

28 MAX_EDGES, 

29 MAX_NODES, 

30 Box, 

31 Cluster, 

32 Direction, 

33 Edge, 

34 Graph, 

35 Node, 

36 layout, 

37 rect_boundary, 

38) 

39from .flowchart import _DIRECTIONS, _width, label_box, parse_style 

40from .labels import clean, fit 

41from .layered import Spacing 

42from .markers import draw_edge 

43 

44#: A relation's end, as written beside its line, and the marker it draws. 

45_ENDS = {"<|": "triangle", "|>": "triangle", "*": "diamond_filled", "o": "diamond", 

46 "<": "small_arrow", ">": "small_arrow", "()": "lollipop"} # fmt: skip 

47_NAME = r"[\w.]+(?:~[^~\s]*(?:~[^~\s]*~)?[^~\s]*~)?" 

48_CLASS = re.compile( 

49 rf'^class\s+(?P<name>{_NAME})(?:\s*\["(?P<label>[^"]*)"\])?(?P<css>(?::::[\w-]+)*)\s*(?P<open>\{{)?\s*(?P<rest>.*)$' 

50) 

51_MEMBER = re.compile(rf"^(?P<name>{_NAME})\s*:\s*(?P<member>.*)$") 

52_ANNOTATION = re.compile(rf"^<<(?P<text>[^>]+)>>\s*(?P<name>{_NAME})?$") 

53_NOTE_FOR = re.compile(rf'^note\s+for\s+(?P<name>{_NAME})\s+"(?P<text>[^"]*)"$') 

54_NOTE = re.compile(r'^note\s+"(?P<text>[^"]*)"$') 

55_CSS_CLASS = re.compile(r'^cssClass\s+"(?P<names>[^"]*)"\s+(?P<css>[\w-]+)$') 

56_QUOTED = re.compile(r'"([^"]*)"') 

57#: The widest a member line runs before it is cut. 

58MEMBER_WIDTH = 220.0 

59 

60 

61def generic(text: str) -> str: 

62 """``List~int~`` as ``List<int>``, nested ones too — written as 

63 entities, so ``labels.clean`` reads them as text, not as a tag.""" 

64 while text.count("~") >= 2: 

65 first = text.index("~") 

66 last = text.rindex("~") 

67 text = f"{text[:first]}&lt;{text[first + 1 : last]}&gt;{text[last + 1 :]}" 

68 return text.replace("~", "") 

69 

70 

71def _bare(name: str) -> str: 

72 return name.split("~", 1)[0] 

73 

74 

75@dataclass 

76class Member: 

77 text: str 

78 static: bool = False 

79 

80 

81@dataclass 

82class ClassBox: 

83 id: str 

84 label: str 

85 annotations: list[str] = field(default_factory=list) 

86 attributes: list[Member] = field(default_factory=list) 

87 methods: list[Member] = field(default_factory=list) 

88 namespace: str | None = None 

89 classes: list[str] = field(default_factory=list) 

90 style: dict[str, str] = field(default_factory=dict) 

91 notes: list[str] = field(default_factory=list) 

92 

93 

94@dataclass 

95class Relation: 

96 source: str 

97 target: str 

98 start: str | None 

99 end: str | None 

100 dashed: bool 

101 label: str | None 

102 source_cardinality: str | None 

103 target_cardinality: str | None 

104 

105 

106def member(text: str) -> tuple[Member, bool]: 

107 """A member as shown, and whether it is a method.""" 

108 text = text.strip() 

109 static = False 

110 if text.endswith("$"): 

111 static, text = True, text[:-1].rstrip() 

112 elif text.endswith("*"): 

113 text = text[:-1].rstrip() 

114 # A leading "~" is package visibility, not half of a generic. 

115 visibility = "" 

116 if text[:1] in "+-#~" and text[:1]: 

117 visibility, text = text[0], text[1:] 

118 m = re.match( 

119 r"^(?P<head>[^()]*)\((?P<args>.*)\)(?P<tail>[$*]?)\s*(?P<returns>.*)$", text 

120 ) 

121 if not m: 

122 return Member(visibility + generic(text), static), False 

123 if m.group("tail") == "$": 

124 static = True 

125 shown = f"{visibility}{generic(m.group('head').strip())}({generic(m.group('args').strip())})" 

126 if m.group("returns").strip(): 

127 shown += f" : {generic(m.group('returns').strip())}" 

128 return Member(shown, static), True 

129 

130 

131def _split_relation(text: str) -> tuple[str, str, str, str, str] | None: 

132 """``(left, start, line, end, right)`` of a relation, or ``None``. A 

133 lone ``o`` beside the line is aggregation only when it stands apart 

134 from a name, as ``A o-- B``.""" 

135 quoted = [(m.start(), m.end()) for m in _QUOTED.finditer(text)] 

136 

137 def inside(i: int) -> bool: 

138 return any(a <= i < b for a, b in quoted) 

139 

140 for m in re.finditer(r"--|\.\.", text): 

141 i, j = m.start(), m.end() 

142 if inside(i): 

143 continue 

144 start = "" 

145 if text[max(0, i - 2) : i] in ("<|", "()"): 

146 start = text[i - 2 : i] 

147 elif i >= 1 and text[i - 1] in "*<": 

148 start = text[i - 1] 

149 elif i >= 1 and text[i - 1] == "o" and (i < 2 or text[i - 2] in ' "'): 

150 start = "o" 

151 end = "" 

152 if text[j : j + 2] in ("|>", "()"): 

153 end = text[j : j + 2] 

154 elif j < len(text) and text[j] in "*>": 

155 end = text[j] 

156 elif ( 

157 j < len(text) 

158 and text[j] == "o" 

159 and (j + 1 >= len(text) or text[j + 1] in ' "') 

160 ): 

161 end = "o" 

162 left = text[: i - len(start)] 

163 right = text[j + len(end) :] 

164 return left, start, m.group(0), end, right 

165 return None 

166 

167 

168@register_diagram 

169class ClassDiagram(Diagram): 

170 keywords = ("classDiagram", "classDiagram-v2") 

171 noun = "a class diagram" 

172 

173 def __init__(self) -> None: 

174 self.direction: Direction = "TB" 

175 self.boxes: dict[str, ClassBox] = {} 

176 self.relations: list[Relation] = [] 

177 self.namespaces: dict[str, str | None] = {} 

178 self.free_notes: list[str] = [] 

179 self.class_defs: dict[str, dict[str, str]] = {} 

180 self._namespace: list[str] = [] 

181 

182 @classmethod 

183 def parse(cls, header: Statement, statements: list[Statement]) -> ClassDiagram: 

184 diagram = cls() 

185 lines = iter(statements) 

186 for statement in lines: 

187 m = _CLASS.match(statement.text) 

188 if m and m.group("open"): 

189 box = diagram._class(m, statement.line) 

190 body = m.group("rest").strip() 

191 closed = body.endswith("}") 

192 if body.rstrip("}").strip(): 

193 diagram._body(box, body.rstrip("}").strip()) 

194 if not closed: 

195 for later in lines: 

196 if later.text == "}": 

197 break 

198 text = later.text 

199 if text.endswith("}"): 

200 diagram._body(box, text[:-1].strip()) 

201 break 

202 diagram._body(box, text) 

203 else: 

204 raise MermaidSyntaxError( 

205 statement.line, "a class body has no closing '}'" 

206 ) 

207 continue 

208 diagram._statement(statement) 

209 if diagram._namespace: 

210 raise MermaidSyntaxError(None, "a namespace has no closing '}'") 

211 return diagram 

212 

213 def _box(self, name: str, line: int | None) -> ClassBox: 

214 key = _bare(name) 

215 box = self.boxes.get(key) 

216 if box is None: 

217 box = self.boxes[key] = ClassBox(key, generic(name)) 

218 if len(self.boxes) > MAX_NODES: 

219 raise MermaidSyntaxError(None, f"it has more than {MAX_NODES} classes") 

220 elif "~" in name: 

221 box.label = generic(name) 

222 return box 

223 

224 def _class(self, m: re.Match[str], line: int) -> ClassBox: 

225 box = self._box(m.group("name"), line) 

226 if self._namespace and box.namespace is None: 

227 box.namespace = self._namespace[-1] 

228 if m.group("label"): 

229 box.label = m.group("label") 

230 box.classes += [c for c in (m.group("css") or "").split(":::") if c] 

231 return box 

232 

233 def _body(self, box: ClassBox, text: str) -> None: 

234 if not text: 

235 return 

236 annotation = _ANNOTATION.match(text) 

237 if annotation and not annotation.group("name"): 

238 box.annotations.append(annotation.group("text").strip()) 

239 return 

240 shown, is_method = member(text) 

241 (box.methods if is_method else box.attributes).append(shown) 

242 

243 def _statement(self, statement: Statement) -> None: 

244 text, line = statement.text, statement.line 

245 first, _, rest = text.partition(" ") 

246 rest = rest.strip() 

247 if first == "direction": 

248 found = _DIRECTIONS.get(rest) 

249 if found is None: 

250 raise MermaidSyntaxError(line, "the direction is not one Mermaid knows") 

251 self.direction = found 

252 return 

253 if first == "namespace": 

254 name = rest.rstrip("{").strip() 

255 if not name or not rest.endswith("{"): 

256 raise MermaidSyntaxError( 

257 line, "a namespace is written 'namespace Name {'" 

258 ) 

259 self.namespaces[name] = self._namespace[-1] if self._namespace else None 

260 self._namespace.append(name) 

261 return 

262 if text == "}": 

263 if not self._namespace: 

264 raise MermaidSyntaxError(line, "'}' closes nothing") 

265 self._namespace.pop() 

266 return 

267 if first in ( 

268 "click", 

269 "link", 

270 "callback", 

271 "accTitle:", 

272 "accDescr:", 

273 ) or first.startswith(("accTitle", "accDescr")): 

274 return 

275 if first == "classDef": 

276 names, _, style = rest.partition(" ") 

277 for name in names.split(","): 

278 self.class_defs.setdefault(name.strip(), {}).update(parse_style(style)) 

279 return 

280 if first == "style": 

281 name, _, style = rest.partition(" ") 

282 if _bare(name) in self.boxes: 

283 self.boxes[_bare(name)].style.update(parse_style(style)) 

284 return 

285 m = _CSS_CLASS.match(text) 

286 if m: 

287 for name in m.group("names").split(","): 

288 if _bare(name.strip()) in self.boxes: 

289 self.boxes[_bare(name.strip())].classes.append(m.group("css")) 

290 return 

291 m = _NOTE_FOR.match(text) 

292 if m: 

293 self._box(m.group("name"), line).notes.append(m.group("text")) 

294 return 

295 m = _NOTE.match(text) 

296 if m: 

297 self.free_notes.append(m.group("text")) 

298 return 

299 m = _CLASS.match(text) 

300 if m: 

301 self._class(m, line) 

302 return 

303 m = _ANNOTATION.match(text) 

304 if m and m.group("name"): 

305 self._box(m.group("name"), line).annotations.append(m.group("text").strip()) 

306 return 

307 relation = _split_relation(text) 

308 # "A : member" may hold dashes or dots after its colon; a relation 

309 # has no colon before its line. 

310 if relation is not None and ":" not in relation[0]: 

311 self._relation(relation, line) 

312 return 

313 m = _MEMBER.match(text) 

314 if m: 

315 self._body(self._box(m.group("name"), line), m.group("member")) 

316 return 

317 if re.fullmatch(_NAME, text): 

318 self._box(text, line) 

319 return 

320 raise MermaidSyntaxError( 

321 line, "this line is not a class, a member or a relation" 

322 ) 

323 

324 def _relation(self, parts: tuple[str, str, str, str, str], line: int) -> None: 

325 left, start, link, end, right = parts 

326 label = None 

327 if ":" in right: 

328 right, _, label = right.partition(":") 

329 label = label.strip().strip('"') or None 

330 source_card = target_card = None 

331 left = left.strip() 

332 right = right.strip() 

333 m = re.fullmatch(rf'(?P<name>{_NAME})\s*(?:"(?P<card>[^"]*)")?', left) 

334 if not m: 

335 raise MermaidSyntaxError( 

336 line, "a relation's first class is not a class name" 

337 ) 

338 source, source_card = m.group("name"), m.group("card") 

339 m = re.fullmatch(rf'(?:"(?P<card>[^"]*)")?\s*(?P<name>{_NAME})', right) 

340 if not m: 

341 raise MermaidSyntaxError( 

342 line, "a relation's second class is not a class name" 

343 ) 

344 target, target_card = m.group("name"), m.group("card") 

345 self._box(source, line) 

346 self._box(target, line) 

347 self.relations.append( 

348 Relation( 

349 _bare(source), 

350 _bare(target), 

351 _ENDS.get(start), 

352 _ENDS.get(end), 

353 link == "..", 

354 label, 

355 source_card or None, 

356 target_card or None, 

357 ) # fmt: skip 

358 ) 

359 if len(self.relations) > MAX_EDGES: 

360 raise MermaidSyntaxError(None, f"it has more than {MAX_EDGES} relations") 

361 

362 # ── drawing ─────────────────────────────────────────────────────────── 

363 

364 def _sections( 

365 self, box: ClassBox, theme: Theme 

366 ) -> tuple[list[str], list[str], list[Member], list[Member]]: 

367 font, size = theme.regular, look.FONT_SIZE 

368 annotations = [f"«{a}»" for a in box.annotations] 

369 name = fit(box.label, theme.bold, size, look.MAX_LINE_WIDTH, 2) 

370 cut = [ 

371 Member( 

372 ellipsize(" ".join(clean(m.text)), font, size, MEMBER_WIDTH), m.static 

373 ) 

374 for m in box.attributes 

375 ] 

376 methods = [ 

377 Member( 

378 ellipsize(" ".join(clean(m.text)), font, size, MEMBER_WIDTH), m.static 

379 ) 

380 for m in box.methods 

381 ] 

382 return annotations, name, cut, methods 

383 

384 def layout(self, theme: Theme) -> Layout: 

385 font, bold, size = theme.regular, theme.bold, look.FONT_SIZE 

386 small = look.SMALL_SIZE 

387 step = size * look.LINE_HEIGHT 

388 sections: dict[ 

389 str, tuple[list[str], list[str], list[Member], list[Member]] 

390 ] = {} 

391 nodes: list[Node] = [] 

392 note_lines: dict[str, list[list[str]]] = {} 

393 for box in self.boxes.values(): 

394 annotations, name, attributes, methods = sections[box.id] = self._sections( 

395 box, theme 

396 ) 

397 widths = [measure(a, font, small) for a in annotations] 

398 widths += [measure(n, bold, size) for n in name] 

399 widths += [measure(m.text, font, size) for m in [*attributes, *methods]] 

400 w = max(widths, default=0.0) + 2 * look.PAD_X 

401 head = small * look.LINE_HEIGHT * len(annotations) + step * len(name) 

402 h = head + 2 * look.PAD_Y 

403 h += max(step * len(attributes), 4.0) + look.PAD_Y 

404 h += max(step * len(methods), 4.0) + look.PAD_Y 

405 beside = [] 

406 for text in box.notes: 

407 lines = fit(text, font, small, 150.0, 8) 

408 note_lines.setdefault(box.id, []).append(lines) 

409 nw, nh = block_size(lines, font, small) 

410 beside.append( 

411 ("after", nw + 2 * look.PAD_X + 10.0, nh + 2 * look.PAD_Y) 

412 ) 

413 nodes.append(Node(box.id, max(w, 60.0), h, box.namespace, beside)) # type: ignore[arg-type] 

414 free = [] 

415 for i, text in enumerate(self.free_notes): 

416 lines = fit(text, font, small, 150.0, 8) 

417 nw, nh = block_size(lines, font, small) 

418 free.append(lines) 

419 nodes.append(Node(f"\0note{i}", nw + 2 * look.PAD_X, nh + 2 * look.PAD_Y)) 

420 edge_lines: list[list[str] | None] = [] 

421 edges = [] 

422 for relation in self.relations: 

423 lines = ( 

424 fit(relation.label, font, size, 140.0, 3) if relation.label else None 

425 ) 

426 edge_lines.append(lines) 

427 label = None 

428 if lines: 

429 tw, th = block_size(lines, font, size) 

430 label = (tw + 6.0, th + 2.0) 

431 edges.append(Edge(relation.source, relation.target, 1, label)) 

432 clusters = [] 

433 titles: dict[str, list[str]] = {} 

434 for name, parent in self.namespaces.items(): 

435 titles[name] = fit(name, bold, size, 200.0, 1) 

436 clusters.append( 

437 Cluster( 

438 name, 

439 parent, 

440 block_size(titles[name], bold, size), 

441 None, 

442 look.CLUSTER_PAD, 

443 ) 

444 ) 

445 placed = layout( 

446 Graph( 

447 self.direction, 

448 nodes, 

449 edges, 

450 clusters, 

451 Spacing(look.NODE_SEP * 1.4, look.RANK_SEP * 1.3, look.EDGE_SEP), 

452 ), 

453 lambda _id, b, toward: rect_boundary(b, toward), 

454 ) 

455 canvas = Canvas(placed.width, placed.height) 

456 for name, box in placed.clusters.items(): 

457 canvas.rect( 

458 box.x, 

459 box.y, 

460 box.width, 

461 box.height, 

462 fill=look.CLUSTER_FILL, 

463 stroke=look.CLUSTER_STROKE, 

464 width=look.NODE_STROKE_WIDTH, 

465 ) 

466 _, th = block_size(titles[name], bold, size) 

467 canvas.lines( 

468 box.cx, 

469 box.y + look.CLUSTER_PAD / 2 + 2 + th / 2, 

470 titles[name], 

471 font=bold, 

472 size=size, 

473 color=look.TEXT, 

474 ) 

475 for relation, route in zip(self.relations, placed.routes): 

476 if route is None: 

477 continue 

478 draw_edge( 

479 canvas, route.points, color=look.LINE, width=look.EDGE_WIDTH, 

480 dash=(3.0, 3.0) if relation.dashed else None, 

481 start=relation.start, end=relation.end, 

482 ) # fmt: skip 

483 for card, at_start in ( 

484 (relation.source_cardinality, True), 

485 (relation.target_cardinality, False), 

486 ): 

487 if card: 

488 self._cardinality(canvas, route.points, at_start, card, theme) 

489 for route, lines in zip(placed.routes, edge_lines): 

490 if route is not None and lines and route.label is not None: 

491 label_box(canvas, route.label, lines, font, size, look.TEXT) 

492 for box in self.boxes.values(): 

493 self._draw_box(canvas, box, placed.nodes[box.id], sections[box.id], theme) 

494 for lines, room in zip( 

495 note_lines.get(box.id, []), placed.beside.get(box.id, []) 

496 ): 

497 note = Box(room.x + 10.0, room.y, room.width - 10.0, room.height) 

498 own = placed.nodes[box.id] 

499 canvas.line( 

500 own.right, 

501 own.cy, 

502 note.x, 

503 note.cy, 

504 color=look.NOTE_STROKE, 

505 width=0.6, 

506 dash=(2.0, 2.0), 

507 ) 

508 self._note(canvas, note, lines, theme) 

509 for i, lines in enumerate(free): 

510 self._note(canvas, placed.nodes[f"\0note{i}"], lines, theme) 

511 return Layout( 

512 canvas.drawing(), placed.width, placed.height, breaks=placed.breaks 

513 ) 

514 

515 @staticmethod 

516 def _note(canvas: Canvas, box: Box, lines: list[str], theme: Theme) -> None: 

517 canvas.rect( 

518 box.x, 

519 box.y, 

520 box.width, 

521 box.height, 

522 fill=look.NOTE_FILL, 

523 stroke=look.NOTE_STROKE, 

524 width=0.6, 

525 ) 

526 canvas.lines( 

527 box.cx, 

528 box.cy, 

529 lines, 

530 font=theme.regular, 

531 size=look.SMALL_SIZE, 

532 color=look.TEXT, 

533 ) 

534 

535 @staticmethod 

536 def _cardinality( 

537 canvas: Canvas, 

538 points: list[tuple[float, float]], 

539 at_start: bool, 

540 text: str, 

541 theme: Theme, 

542 ) -> None: 

543 tip, neighbour = ( 

544 (points[0], points[1]) if at_start else (points[-1], points[-2]) 

545 ) 

546 dx, dy = neighbour[0] - tip[0], neighbour[1] - tip[1] 

547 d = (dx * dx + dy * dy) ** 0.5 or 1.0 

548 ux, uy = dx / d, dy / d 

549 x = tip[0] + ux * 14.0 - uy * 9.0 

550 y = tip[1] + uy * 14.0 + ux * 9.0 

551 shown = ellipsize(" ".join(clean(text)), theme.regular, look.SMALL_SIZE, 60.0) 

552 canvas.lines( 

553 x, y, [shown], font=theme.regular, size=look.SMALL_SIZE, color=look.TEXT 

554 ) 

555 

556 def _draw_box( 

557 self, 

558 canvas: Canvas, 

559 box: ClassBox, 

560 at: Box, 

561 sections: tuple[list[str], list[str], list[Member], list[Member]], 

562 theme: Theme, 

563 ) -> None: 

564 font, bold, size, small = ( 

565 theme.regular, 

566 theme.bold, 

567 look.FONT_SIZE, 

568 look.SMALL_SIZE, 

569 ) 

570 styled: dict[str, str] = {} 

571 for name in box.classes: 

572 styled.update(self.class_defs.get(name, {})) 

573 styled.update(box.style) 

574 stroke = parse_color(styled.get("stroke"), look.NODE_STROKE) 

575 color = parse_color(styled.get("color"), look.TEXT) 

576 canvas.rect( 

577 at.x, at.y, at.width, at.height, 

578 fill=parse_color(styled.get("fill"), look.NODE_FILL), stroke=stroke, 

579 width=_width(styled.get("stroke-width"), look.NODE_STROKE_WIDTH), 

580 ) # fmt: skip 

581 annotations, name, attributes, methods = sections 

582 step = size * look.LINE_HEIGHT 

583 small_step = small * look.LINE_HEIGHT 

584 y = at.y + look.PAD_Y 

585 for text in annotations: 

586 canvas.text( 

587 at.cx, 

588 y + small_step / 2 + small * 0.35, 

589 text, 

590 font=font, 

591 size=small, 

592 color=color, 

593 ) 

594 y += small_step 

595 for text in name: 

596 canvas.text( 

597 at.cx, 

598 y + step / 2 + size * 0.35, 

599 text, 

600 font=bold, 

601 size=size, 

602 color=color, 

603 ) 

604 y += step 

605 y += look.PAD_Y 

606 for group in (attributes, methods): 

607 canvas.line(at.x, y, at.right, y, color=stroke, width=0.6) 

608 y += look.PAD_Y / 2 

609 for item in group: 

610 baseline = y + step / 2 + size * 0.35 

611 canvas.text( 

612 at.x + look.PAD_X, 

613 baseline, 

614 item.text, 

615 font=font, 

616 size=size, 

617 color=color, 

618 anchor="start", 

619 ) 

620 if item.static: 

621 w = measure(item.text, font, size) 

622 canvas.line( 

623 at.x + look.PAD_X, 

624 baseline + 1.2, 

625 at.x + look.PAD_X + w, 

626 baseline + 1.2, 

627 color=color, 

628 width=0.5, 

629 ) 

630 y += step 

631 if not group: 

632 y += 4.0 

633 y += look.PAD_Y / 2