Coverage for app / documents / visuals / mermaid / state.py: 92%

360 statements  

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

1"""``stateDiagram`` and ``stateDiagram-v2``. 

2 

3Read: transitions ``A --> B : label`` with ``[*]`` as the start or end of 

4the scope it is written in; ``A : description``; ``state "name" as A``; 

5composites ``state A { … }`` with ``--`` between concurrent regions; 

6``<<choice>>``, ``<<fork>>`` and ``<<join>>``; ``note left of`` / ``note 

7right of`` (one line or up to ``end note``); ``classDef``, ``class``, 

8``:::`` and ``style``. ``hide empty description``, ``scale``, ``click`` and 

9the accessibility lines are left out. 

10""" 

11 

12from __future__ import annotations 

13 

14import re 

15from dataclasses import dataclass, field 

16from typing import Literal 

17 

18from ..colors import parse_color 

19from ..registry import Layout 

20from ..theme import Theme 

21from . import look 

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

23from .canvas import Canvas, block_size 

24from .compound import ( 

25 MAX_EDGES, 

26 MAX_NODES, 

27 Box, 

28 Cluster, 

29 Direction, 

30 Edge, 

31 Graph, 

32 Node, 

33 layout, 

34 rect_boundary, 

35) 

36from .flowchart import _DIRECTIONS, _dash, _width, label_box, parse_style 

37from .labels import fit 

38from .layered import Spacing 

39from .markers import draw_edge 

40from .shapes import SHAPES 

41 

42Kind = Literal["state", "start", "end", "fork", "join", "choice"] 

43_ID = r"[^\s:\-<>\[\]{}\"]+(?:-[^\s:\-<>\[\]{}\"]+)*" 

44_END = re.compile(rf"(\[\*\]|{_ID})((?::::[\w-]+)*)") 

45_TRANSITION = re.compile( 

46 rf"^(?P<a>\[\*\]|{_ID})(?P<ac>(?::::[\w-]+)*)\s*-->\s*" 

47 rf"(?P<b>\[\*\]|{_ID})(?P<bc>(?::::[\w-]+)*)\s*(?::\s*(?P<label>.*))?$" 

48) 

49_DESCRIPTION = re.compile(rf"^(?P<id>{_ID})\s*:\s*(?P<text>.*)$") 

50_STATE = re.compile( 

51 rf'^state\s+(?:"(?P<named>[^"]*)"\s+as\s+(?P<alias>{_ID})|(?P<id>{_ID}))' 

52 r"(?P<rest>.*)$" 

53) 

54_NOTE = re.compile( 

55 rf"^note\s+(?P<side>left|right)\s+of\s+(?P<id>{_ID})\s*(?::\s*(?P<text>.*))?$" 

56) 

57_SPECIAL = {"<<fork>>": "fork", "<<join>>": "join", "<<choice>>": "choice"} 

58#: A start or end dot, a fork's bar, a choice's rhombus. 

59DOT = 10.5 

60BAR = (52.0, 7.0) 

61CHOICE = 20.0 

62 

63 

64@dataclass 

65class State: 

66 id: str 

67 name: str 

68 kind: Kind = "state" 

69 descriptions: list[str] = field(default_factory=list) 

70 parent: str | None = None 

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

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

73 notes: list[tuple[Literal["before", "after"], str]] = field(default_factory=list) 

74 

75 

76@dataclass 

77class Composite: 

78 id: str 

79 name: str 

80 parent: str | None 

81 #: A concurrent region: drawn dashed, with no title. 

82 region: bool = False 

83 direction: Direction | None = None 

84 regions: list[str] = field(default_factory=list) 

85 

86 

87@dataclass 

88class Transition: 

89 source: str 

90 target: str 

91 label: str | None 

92 

93 

94@register_diagram 

95class StateDiagram(Diagram): 

96 keywords = ("stateDiagram-v2", "stateDiagram") 

97 noun = "a state diagram" 

98 

99 def __init__(self) -> None: 

100 self.direction: Direction = "TB" 

101 self.states: dict[str, State] = {} 

102 self.composites: dict[str, Composite] = {} 

103 self.transitions: list[Transition] = [] 

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

105 self._open: list[str] = [] 

106 

107 @classmethod 

108 def parse(cls, header: Statement, statements: list[Statement]) -> StateDiagram: 

109 diagram = cls() 

110 lines = iter(statements) 

111 for statement in lines: 

112 text = statement.text 

113 m = _NOTE.match(text) 

114 if m and m.group("text") is None: 

115 body = [] 

116 for later in lines: 

117 if later.text == "end note": 

118 break 

119 body.append(later.text) 

120 else: 

121 raise MermaidSyntaxError(statement.line, "a note has no 'end note'") 

122 diagram._note(m.group("side"), m.group("id"), "<br>".join(body)) 

123 continue 

124 diagram._statement(statement) 

125 if diagram._open: 

126 raise MermaidSyntaxError(None, "a composite state has no closing '}'") 

127 return diagram 

128 

129 @property 

130 def _scope(self) -> str | None: 

131 return self._open[-1] if self._open else None 

132 

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

134 text, line = statement.text, statement.line 

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

136 rest = rest.strip() 

137 if text == "}": 

138 if not self._open: 

139 raise MermaidSyntaxError(line, "'}' closes no composite state") 

140 closing = self._open.pop() 

141 if self.composites[closing].region: 

142 self._open.pop() 

143 return 

144 if text == "--": 

145 self._region(line) 

146 return 

147 if first == "direction": 

148 found = _DIRECTIONS.get(rest) 

149 if found is None: 

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

151 if self._open: 

152 self.composites[self._composite_of(self._open[-1])].direction = found 

153 else: 

154 self.direction = found 

155 return 

156 if first == "classDef": 

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

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

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

160 return 

161 if first == "class": 

162 ids, _, name = rest.rpartition(" ") 

163 for item in ids.split(","): 

164 if item.strip() in self.states: 

165 self.states[item.strip()].classes.append(name.strip()) 

166 return 

167 if first == "style": 

168 item, _, style = rest.partition(" ") 

169 if item in self.states: 

170 self.states[item].style.update(parse_style(style)) 

171 return 

172 if first in ( 

173 "hide", 

174 "scale", 

175 "click", 

176 "accTitle:", 

177 "accDescr:", 

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

179 return 

180 if first == "state": 

181 self._state(text, line) 

182 return 

183 if first == "note": 

184 m = _NOTE.match(text) 

185 if not m: 

186 raise MermaidSyntaxError( 

187 line, "a note is not written 'note left of' or 'note right of'" 

188 ) 

189 self._note(m.group("side"), m.group("id"), m.group("text") or "") 

190 return 

191 m = _TRANSITION.match(text) 

192 if m: 

193 source = self._end_of(m.group("a"), m.group("ac"), start=True, line=line) 

194 target = self._end_of(m.group("b"), m.group("bc"), start=False, line=line) 

195 label = (m.group("label") or "").strip() or None 

196 self.transitions.append(Transition(source, target, label)) 

197 if len(self.transitions) > MAX_EDGES: 

198 raise MermaidSyntaxError( 

199 None, f"it has more than {MAX_EDGES} transitions" 

200 ) 

201 return 

202 m = _DESCRIPTION.match(text) 

203 if m: 

204 self._declare(m.group("id"), line).descriptions.append( 

205 m.group("text").strip() 

206 ) 

207 return 

208 if re.fullmatch(_ID, text): 

209 self._declare(text, line) 

210 return 

211 raise MermaidSyntaxError( 

212 line, "this line is not a state, a transition or a note" 

213 ) 

214 

215 def _composite_of(self, scope: str) -> str: 

216 composite = self.composites[scope] 

217 return composite.parent if composite.region and composite.parent else scope 

218 

219 def _region(self, line: int) -> None: 

220 """``--``: what the composite holds so far is its first region, and 

221 what follows goes in the next.""" 

222 if not self._open: 

223 raise MermaidSyntaxError(line, "'--' splits only a composite state") 

224 owner = self._composite_of(self._open[-1]) 

225 composite = self.composites[owner] 

226 if composite.regions: 

227 self._open.pop() 

228 else: 

229 first = f"{owner}\0region0" 

230 self.composites[first] = Composite(first, "", owner, region=True) 

231 composite.regions.append(first) 

232 for state in self.states.values(): 

233 if state.parent == owner: 

234 state.parent = first 

235 for other in self.composites.values(): 

236 if other.parent == owner and other.id != first: 

237 other.parent = first 

238 region = f"{owner}\0region{len(composite.regions)}" 

239 self.composites[region] = Composite(region, "", owner, region=True) 

240 composite.regions.append(region) 

241 self._open.append(region) 

242 

243 def _state(self, text: str, line: int) -> None: 

244 m = _STATE.match(text) 

245 if not m: 

246 raise MermaidSyntaxError(line, "a state is not written 'state name'") 

247 sid = m.group("alias") or m.group("id") 

248 named = m.group("named") 

249 rest = (m.group("rest") or "").strip() 

250 opens = rest.endswith("{") 

251 if opens: 

252 rest = rest[:-1].strip() 

253 if rest.startswith("as "): 

254 named = rest[3:].strip().strip('"') 

255 rest = "" 

256 special = _SPECIAL.get(rest) 

257 if opens: 

258 if sid in self.composites: 

259 raise MermaidSyntaxError(line, "a composite state is declared twice") 

260 self.composites[sid] = Composite(sid, named or sid, self._scope) 

261 self.states.pop(sid, None) 

262 self._open.append(sid) 

263 return 

264 state = self._declare(sid, line) 

265 if named: 

266 state.name = named 

267 if special: 

268 state.kind = special # type: ignore[assignment] 

269 elif rest.startswith(":"): 

270 state.descriptions.append(rest[1:].strip()) 

271 

272 def _declare(self, sid: str, line: int | None) -> State: 

273 if sid in self.composites: 

274 return State(sid, sid) # a reference to the composite: not a state 

275 state = self.states.get(sid) 

276 if state is None: 

277 state = self.states[sid] = State(sid, sid, parent=self._scope) 

278 if len(self.states) > MAX_NODES: 

279 raise MermaidSyntaxError(None, f"it has more than {MAX_NODES} states") 

280 return state 

281 

282 def _end_of(self, token: str, classes: str, *, start: bool, line: int) -> str: 

283 if token == "[*]": 

284 scope = self._scope or "\0root" 

285 sid = f"{scope}\0{'start' if start else 'end'}" 

286 if sid not in self.states: 

287 self.states[sid] = State( 

288 sid, "", "start" if start else "end", parent=self._scope 

289 ) 

290 return sid 

291 state = self._declare(token, line) 

292 state.classes += [c for c in classes.split(":::") if c] 

293 return token 

294 

295 def _note(self, side: str, sid: str, text: str) -> None: 

296 state = self._declare(sid, None) 

297 state.notes.append(("after" if side == "right" else "before", text)) 

298 

299 # ── drawing ─────────────────────────────────────────────────────────── 

300 

301 def _size( 

302 self, state: State, theme: Theme 

303 ) -> tuple[float, float, list[str], list[str]]: 

304 """Its size, its name's lines and its descriptions' lines.""" 

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

306 if state.kind in ("start", "end"): 

307 return DOT, DOT, [], [] 

308 if state.kind in ("fork", "join"): 

309 w, h = BAR 

310 if self.direction in ("LR", "RL"): 

311 w, h = h, w 

312 return w, h, [], [] 

313 if state.kind == "choice": 

314 return CHOICE, CHOICE, [], [] 

315 name = fit(state.name, font, size, look.MAX_LINE_WIDTH, 3) 

316 details: list[str] = [] 

317 for text in state.descriptions: 

318 details += fit(text, font, size, look.MAX_LINE_WIDTH, 4) 

319 nw, nh = block_size(name, font, size) 

320 dw, dh = block_size(details, font, size) if details else (0.0, 0.0) 

321 w = max(nw, dw) + 2 * look.PAD_X 

322 h = nh + 2 * look.PAD_Y + (dh + look.PAD_Y if details else 0.0) 

323 return max(w, 40.0), max(h, 20.0), name, details 

324 

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

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

327 nodes: list[Node] = [] 

328 texts: dict[str, tuple[list[str], list[str]]] = {} 

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

330 for state in self.states.values(): 

331 w, h, name, details = self._size(state, theme) 

332 texts[state.id] = (name, details) 

333 beside = [] 

334 for side, text in state.notes: 

335 lines = fit(text, font, look.SMALL_SIZE, 150.0, 8) 

336 note_lines.setdefault(state.id, []).append(lines) 

337 nw, nh = block_size(lines, font, look.SMALL_SIZE) 

338 beside.append((side, nw + 2 * look.PAD_X + 10.0, nh + 2 * look.PAD_Y)) 

339 nodes.append(Node(state.id, w, h, state.parent, beside)) 

340 clusters = [] 

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

342 for composite in self.composites.values(): 

343 lines = ( 

344 [] if composite.region else fit(composite.name, font, size, 200.0, 2) 

345 ) 

346 titles[composite.id] = lines 

347 label = block_size(lines, font, size) if lines else (0.0, 0.0) 

348 pad = 6.0 if composite.region else look.CLUSTER_PAD 

349 clusters.append( 

350 Cluster(composite.id, composite.parent, label, composite.direction, pad) 

351 ) 

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

353 edges = [] 

354 for transition in self.transitions: 

355 lines = ( 

356 fit(transition.label, font, size, 140.0, 3) 

357 if transition.label 

358 else None 

359 ) 

360 edge_lines.append(lines) 

361 label = None 

362 if lines: 

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

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

365 edges.append(Edge(transition.source, transition.target, 1, label)) 

366 

367 def boundary( 

368 sid: str, box: Box, toward: tuple[float, float] 

369 ) -> tuple[float, float]: 

370 kind = self.states[sid].kind 

371 if kind in ("start", "end"): 

372 return SHAPES["circle"].boundary(box, toward) 

373 if kind == "choice": 

374 return SHAPES["diamond"].boundary(box, toward) 

375 return rect_boundary(box, toward) 

376 

377 placed = layout( 

378 Graph( 

379 self.direction, 

380 nodes, 

381 edges, 

382 clusters, 

383 Spacing(look.NODE_SEP, look.RANK_SEP, look.EDGE_SEP), 

384 ), 

385 boundary, 

386 ) 

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

388 depth = {cid: self._depth(cid) for cid in self.composites} 

389 for cid in sorted(placed.clusters, key=lambda c: depth[c]): 

390 box = placed.clusters[cid] 

391 composite = self.composites[cid] 

392 if composite.region: 

393 canvas.rect( 

394 box.x, 

395 box.y, 

396 box.width, 

397 box.height, 

398 fill=None, 

399 stroke=look.NODE_STROKE, 

400 width=0.6, 

401 dash=(3.0, 3.0), 

402 ) 

403 continue 

404 canvas.rect( 

405 box.x, box.y, box.width, box.height, radius=5.0, 

406 fill=look.COMPOSITE_FILL, stroke=look.NODE_STROKE, width=look.NODE_STROKE_WIDTH, 

407 ) # fmt: skip 

408 lines = titles[cid] 

409 if lines: 

410 _, th = block_size(lines, font, size) 

411 band = look.CLUSTER_PAD / 2 + 2 + th + 3 

412 canvas.lines( 

413 box.cx, 

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

415 lines, 

416 font=font, 

417 size=size, 

418 color=look.TEXT, 

419 ) 

420 canvas.line( 

421 box.x, 

422 box.y + band, 

423 box.right, 

424 box.y + band, 

425 color=look.NODE_STROKE, 

426 width=0.6, 

427 ) 

428 for edge, route in zip(self.transitions, placed.routes): 

429 if route is not None: 

430 draw_edge( 

431 canvas, 

432 route.points, 

433 color=look.LINE, 

434 width=look.EDGE_WIDTH, 

435 end="arrow", 

436 ) 

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

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

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

440 for state in self.states.values(): 

441 self._draw_state( 

442 canvas, state, placed.nodes[state.id], texts[state.id], theme 

443 ) 

444 for (side, _), lines, room in zip( 

445 state.notes, 

446 note_lines.get(state.id, []), 

447 placed.beside.get(state.id, []), 

448 ): 

449 self._draw_note( 

450 canvas, placed.nodes[state.id], room, side, lines, theme 

451 ) 

452 return Layout( 

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

454 ) 

455 

456 def _depth(self, cid: str) -> int: 

457 depth = 0 

458 current: str | None = cid 

459 while current is not None: 

460 depth += 1 

461 current = self.composites[current].parent 

462 return depth 

463 

464 def _draw_state( 

465 self, 

466 canvas: Canvas, 

467 state: State, 

468 box: Box, 

469 text: tuple[list[str], list[str]], 

470 theme: Theme, 

471 ) -> None: 

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

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

474 for name in state.classes: 

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

476 styled.update(state.style) 

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

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

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

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

481 r = min(box.width, box.height) / 2 

482 if state.kind == "start": 

483 canvas.circle( 

484 box.cx, box.cy, r, fill=look.SPECIAL, stroke=look.SPECIAL, width=0.5 

485 ) 

486 return 

487 if state.kind == "end": 

488 canvas.circle( 

489 box.cx, box.cy, r, fill=look.WHITE, stroke=look.SPECIAL, width=1.0 

490 ) 

491 canvas.circle( 

492 box.cx, 

493 box.cy, 

494 r * 0.62, 

495 fill=look.SPECIAL, 

496 stroke=look.SPECIAL, 

497 width=0.5, 

498 ) 

499 return 

500 if state.kind in ("fork", "join"): 

501 canvas.rect( 

502 box.x, 

503 box.y, 

504 box.width, 

505 box.height, 

506 fill=look.SPECIAL, 

507 stroke=look.SPECIAL, 

508 width=0.5, 

509 ) 

510 return 

511 if state.kind == "choice": 

512 canvas.polygon( 

513 SHAPES["diamond"].outline(box), fill=fill, stroke=stroke, width=width 

514 ) 

515 return 

516 canvas.rect( 

517 box.x, box.y, box.width, box.height, radius=5.0, 

518 fill=fill, stroke=stroke, width=width, dash=_dash(styled.get("stroke-dasharray")), 

519 ) # fmt: skip 

520 name, details = text 

521 if not details: 

522 canvas.lines(box.cx, box.cy, name, font=font, size=size, color=color) 

523 return 

524 _, nh = block_size(name, font, size) 

525 divider = box.y + look.PAD_Y + nh + look.PAD_Y / 2 

526 canvas.lines( 

527 box.cx, box.y + look.PAD_Y + nh / 2, name, font=font, size=size, color=color 

528 ) 

529 canvas.line(box.x, divider, box.right, divider, color=stroke, width=0.6) 

530 _, dh = block_size(details, font, size) 

531 canvas.lines( 

532 box.cx, 

533 divider + look.PAD_Y / 2 + dh / 2, 

534 details, 

535 font=font, 

536 size=size, 

537 color=color, 

538 ) 

539 

540 @staticmethod 

541 def _draw_note( 

542 canvas: Canvas, box: Box, room: Box, side: str, lines: list[str], theme: Theme 

543 ) -> None: 

544 note = Box( 

545 room.x + (10.0 if side == "after" else 0.0), 

546 room.y, 

547 room.width - 10.0, 

548 room.height, 

549 ) 

550 joint = (note.x, note.cy) if side == "after" else (note.right, note.cy) 

551 start = (box.right, box.cy) if side == "after" else (box.x, box.cy) 

552 canvas.line( 

553 start[0], 

554 start[1], 

555 joint[0], 

556 joint[1], 

557 color=look.NOTE_STROKE, 

558 width=0.6, 

559 dash=(2.0, 2.0), 

560 ) 

561 canvas.rect( 

562 note.x, 

563 note.y, 

564 note.width, 

565 note.height, 

566 fill=look.NOTE_FILL, 

567 stroke=look.NOTE_STROKE, 

568 width=0.6, 

569 ) 

570 canvas.lines( 

571 note.cx, 

572 note.cy, 

573 lines, 

574 font=theme.regular, 

575 size=look.SMALL_SIZE, 

576 color=look.TEXT, 

577 )