Coverage for app / documents / visuals / mermaid / visual.py: 93%

85 statements  

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

1"""A ```mermaid fence drawn: its type read from its first statement, then 

2read and laid out by that type's ``Diagram``.""" 

3 

4from __future__ import annotations 

5 

6import copy 

7import re 

8from dataclasses import dataclass 

9from app.util import vocab 

10 

11from ..fence import VisualError 

12from ..registry import Layout, Visual, register_visual 

13from ..theme import Theme 

14from . import classes, er, flowchart, gantt, pie, sequence, state # noqa: F401 — they register 

15from .base import ( 

16 DIAGRAMS, 

17 MAX_MERMAID_CHARS, 

18 Diagram, 

19 MermaidSyntaxError, 

20 keyword_of, 

21 preprocess, 

22) 

23from .vocabulary import MermaidKeyword, MermaidType, offered 

24 

25vocab.check({keyword: cls.noun for keyword, cls in DIAGRAMS.items()}, MermaidKeyword) 

26vocab.check({cls.keyword(): cls.noun for cls in DIAGRAMS.values()}, MermaidType) 

27 

28#: The smallest a diagram is drawn: its text is vector, so a reader can 

29#: zoom in, but below this it is a texture. 

30MIN_SCALE = 0.3 

31#: A left-to-right diagram drawn smaller than this is laid out again top to 

32#: bottom, and drawn that way when it then comes out larger: a long chain 

33#: across a page is otherwise too small to read. 

34TURN_BELOW = 0.6 

35_KEYWORD = re.compile(r"[A-Za-z][\w-]{0,39}") 

36 

37 

38def check(source: str) -> str | None: 

39 """Why ``source`` would not be drawn, in words for the model that wrote 

40 it, or ``None``: what ``render_mermaid`` refuses, so every diagram it 

41 returns can be drawn in a PDF too. Reads; never lays out (the chat draws 

42 any size).""" 

43 if len(source) > MAX_MERMAID_CHARS: 

44 return f"it is longer than {MAX_MERMAID_CHARS:,} characters" 

45 text = preprocess(source) 

46 if not text.statements: 

47 return "it is empty" 

48 header = text.statements[0] 

49 keyword = keyword_of(header.text) 

50 drawer = DIAGRAMS.get(keyword) 

51 if drawer is None: 

52 named = f", not '{keyword}'" if _KEYWORD.fullmatch(keyword) else "" 

53 return f"it must open with one of these diagram types{named}: {offered()}" 

54 try: 

55 drawer.parse(header, text.statements[1:]) 

56 except MermaidSyntaxError as exc: 

57 return str(exc) 

58 return None 

59 

60 

61@dataclass(frozen=True) 

62class MermaidSpec: 

63 title: str | None 

64 diagram: Diagram 

65 

66 

67@register_visual 

68class MermaidVisual(Visual): 

69 kind = "mermaid" 

70 noun = "Diagram" 

71 tall = True 

72 fills_width = False 

73 

74 def read(self, source: str) -> MermaidSpec: 

75 if not source.strip(): 

76 raise VisualError("it is empty") 

77 if len(source) > MAX_MERMAID_CHARS: 

78 raise VisualError(f"it is longer than {MAX_MERMAID_CHARS:,} characters") 

79 text = preprocess(source) 

80 if not text.statements: 

81 raise VisualError("it is empty") 

82 header = text.statements[0] 

83 keyword = keyword_of(header.text) 

84 drawer = DIAGRAMS.get(keyword) 

85 if drawer is None: 

86 if _KEYWORD.fullmatch(keyword): 

87 raise VisualError(f"'{keyword}' is not a diagram type the PDF draws") 

88 raise VisualError("it does not start with a diagram type") 

89 try: 

90 diagram = drawer.parse(header, text.statements[1:]) 

91 except MermaidSyntaxError as exc: 

92 raise VisualError(f"it could not be read ({exc})") from None 

93 return MermaidSpec(text.title or diagram.title, diagram) 

94 

95 def title(self, spec: MermaidSpec) -> str | None: 

96 return spec.title 

97 

98 def layout( 

99 self, spec: MermaidSpec, width: float, max_height: float, theme: Theme 

100 ) -> Layout: 

101 def scale_of(drawn: Layout) -> float: 

102 scale = min(1.0, width / drawn.width if drawn.width else 1.0) 

103 if drawn.breaks: # split across pages: its height is no limit 

104 return scale 

105 return min(scale, max_height / drawn.height if drawn.height else 1.0) 

106 

107 try: 

108 drawn = spec.diagram.layout(theme) 

109 except MermaidSyntaxError as exc: 

110 raise VisualError(str(exc)) from None 

111 scale = scale_of(drawn) 

112 if scale < TURN_BELOW and getattr(spec.diagram, "direction", None) in ( 

113 "LR", 

114 "RL", 

115 ): 

116 turned = copy.copy(spec.diagram) 

117 turned.direction = "TB" # type: ignore[attr-defined] 

118 other = turned.layout(theme) 

119 if scale_of(other) > scale: 

120 drawn, scale = other, scale_of(other) 

121 if scale < MIN_SCALE: 

122 raise VisualError("it is too large to draw legibly on a page") 

123 return drawn