Coverage for app / documents / visuals / mermaid / base.py: 100%

81 statements  

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

1"""Reading a Mermaid diagram: its lines, its type, and why one is refused. 

2 

3There is no Python Mermaid renderer and no browser in the image, so each 

4diagram type is read and laid out here, one registered class a type 

5(``Diagram``, ``DIAGRAMS``). ``preprocess`` keeps every statement's line 

6number, so a diagram that cannot be read says where ("line 4: …"). 

7""" 

8 

9from __future__ import annotations 

10 

11import re 

12from abc import ABC, abstractmethod 

13from dataclasses import dataclass 

14from typing import ClassVar 

15 

16from ..registry import Layout 

17from ..theme import Theme 

18 

19#: The longest diagram read. 

20MAX_MERMAID_CHARS = 20_000 

21 

22 

23class MermaidSyntaxError(ValueError): 

24 """A diagram that cannot be read; ``line`` is where, from 1.""" 

25 

26 def __init__(self, line: int | None, message: str) -> None: 

27 self.line = line 

28 super().__init__(f"line {line}: {message}" if line else message) 

29 

30 

31@dataclass(frozen=True) 

32class Statement: 

33 line: int 

34 text: str 

35 

36 

37@dataclass(frozen=True) 

38class Source: 

39 title: str | None 

40 statements: list[Statement] 

41 

42 

43_DIRECTIVE = re.compile(r"%%\{.*?\}%%", re.DOTALL) 

44 

45 

46def _split(text: str) -> list[str]: 

47 """A line's statements: split at ``;`` outside quotes and brackets.""" 

48 out: list[str] = [] 

49 depth = 0 

50 quote = False 

51 start = 0 

52 for i, char in enumerate(text): 

53 if char == '"': 

54 quote = not quote 

55 elif not quote and char in "([{": 

56 depth += 1 

57 elif not quote and char in ")]}": 

58 depth = max(0, depth - 1) 

59 elif char == ";" and not quote and depth == 0: 

60 out.append(text[start:i]) 

61 start = i + 1 

62 out.append(text[start:]) 

63 return [part.strip() for part in out if part.strip()] 

64 

65 

66def _without_comment(line: str) -> str: 

67 """``line`` up to a ``%%`` comment written after it, outside quotes.""" 

68 quote = False 

69 for i in range(len(line) - 1): 

70 if line[i] == '"': 

71 quote = not quote 

72 elif ( 

73 not quote and line[i : i + 2] == "%%" and (i == 0 or line[i - 1].isspace()) 

74 ): 

75 return line[:i] 

76 return line 

77 

78 

79def preprocess(text: str) -> Source: 

80 """``text``'s statements with their line numbers: front matter read for 

81 its title, ``%%{…}%%`` directives and ``%%`` comments left out.""" 

82 text = _DIRECTIVE.sub(lambda m: "\n" * m.group(0).count("\n"), text.lstrip("")) 

83 lines = text.replace("\r\n", "\n").replace("\r", "\n").split("\n") 

84 title: str | None = None 

85 first = next((i for i, line in enumerate(lines) if line.strip()), None) 

86 if first is not None and lines[first].strip() == "---": 

87 end = next( 

88 (i for i in range(first + 1, len(lines)) if lines[i].strip() == "---"), None 

89 ) 

90 if end is not None: 

91 for line in lines[first + 1 : end]: 

92 key, _, value = line.partition(":") 

93 if key.strip() == "title" and value.strip(): 

94 title = value.strip().strip("\"'") 

95 lines = [""] * (end + 1) + lines[end + 1 :] 

96 statements: list[Statement] = [] 

97 for number, line in enumerate(lines, start=1): 

98 stripped = _without_comment(line).strip() 

99 if not stripped: 

100 continue 

101 for part in _split(stripped): 

102 statements.append(Statement(number, part)) 

103 return Source(title, statements) 

104 

105 

106class Diagram(ABC): 

107 """One diagram type: how it is read, and laid out at its natural size 

108 (the PDF scales it down to the page, and splits a tall one across 

109 pages where its layout allows: ``Layout.breaks``).""" 

110 

111 #: Every first word it is read from; the first is the one offered. 

112 keywords: ClassVar[tuple[str, ...]] 

113 #: What it is called in a note: "a flowchart". 

114 noun: ClassVar[str] 

115 #: A ``title`` statement's text, where the type has one. 

116 title: str | None = None 

117 

118 @classmethod 

119 def keyword(cls) -> str: 

120 return cls.keywords[0] 

121 

122 @classmethod 

123 @abstractmethod 

124 def parse(cls, header: Statement, statements: list[Statement]) -> Diagram: ... 

125 

126 @abstractmethod 

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

128 

129 

130DIAGRAMS: dict[str, type[Diagram]] = {} 

131 

132 

133def register_diagram(cls: type[Diagram]) -> type[Diagram]: 

134 for keyword in cls.keywords: 

135 DIAGRAMS[keyword] = cls 

136 return cls 

137 

138 

139def keyword_of(header: str) -> str: 

140 return header.split(maxsplit=1)[0] if header.strip() else ""