Coverage for app / documents / visuals / mermaid / pie.py: 94%

63 statements  

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

1"""``pie``: ``pie [showData] [title …]``, an optional ``title`` line, then 

2``"label" : value`` lines. 

3 

4Drawn by the chart drawer (``visuals.chart``), in the chart palette, so a 

5pie looks the same whether a model wrote a chart fence or a Mermaid one. 

6``showData`` puts each value after its label, as Mermaid's legend does; a 

7label given twice keeps its first value, as Mermaid does. 

8""" 

9 

10from __future__ import annotations 

11 

12import math 

13import re 

14 

15from app.util import safe_json 

16 

17from ..chart import ChartVisual 

18from ..fence import VisualError 

19from ..registry import Layout 

20from ..theme import Theme 

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

22 

23_SLICE = re.compile( 

24 r'^"(?P<label>[^"]*)"\s*:\s*(?P<value>[-+]?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?)$' 

25) 

26#: The most slices drawn. 

27MAX_SLICES = 100 

28#: Its size before the page scales it. 

29WIDTH = 380.0 

30HEIGHT = 300.0 

31 

32 

33def _number(value: float) -> str: 

34 """As JavaScript writes it: no ".0" on a whole number.""" 

35 return str(int(value)) if value == int(value) and abs(value) < 1e15 else repr(value) 

36 

37 

38@register_diagram 

39class PieDiagram(Diagram): 

40 keywords = ("pie",) 

41 noun = "a pie chart" 

42 

43 def __init__(self, show_data: bool) -> None: 

44 self.show_data = show_data 

45 self.slices: dict[str, float] = {} 

46 self.title = None 

47 

48 @classmethod 

49 def parse(cls, header: Statement, statements: list[Statement]) -> PieDiagram: 

50 words = header.text.split(maxsplit=1) 

51 rest = words[1].strip() if len(words) > 1 else "" 

52 show = False 

53 if rest.startswith("showData"): 

54 show, rest = True, rest[len("showData") :].strip() 

55 diagram = cls(show) 

56 if rest.startswith("title"): 

57 diagram.title = rest[len("title") :].strip() or None 

58 elif rest: 

59 raise MermaidSyntaxError( 

60 header.line, "a pie opens with 'pie', then 'showData' or a title" 

61 ) 

62 for statement in statements: 

63 text, line = statement.text, statement.line 

64 first = text.split(maxsplit=1)[0] 

65 if first == "title": 

66 diagram.title = text[len("title") :].strip() or None 

67 continue 

68 if first.startswith(("accTitle", "accDescr")): 

69 continue 

70 m = _SLICE.match(text) 

71 if not m: 

72 raise MermaidSyntaxError(line, 'a slice is written "label" : value') 

73 value = float(m.group("value")) 

74 if not math.isfinite(value) or value < 0: 

75 raise MermaidSyntaxError( 

76 line, "a slice's value is a number of 0 or more" 

77 ) 

78 diagram.slices.setdefault(m.group("label"), value) 

79 if len(diagram.slices) > MAX_SLICES: 

80 raise MermaidSyntaxError(None, f"it has more than {MAX_SLICES} slices") 

81 if not diagram.slices: 

82 raise MermaidSyntaxError(None, "it has no slices") 

83 return diagram 

84 

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

86 rows = [ 

87 { 

88 "name": f"{label} [{_number(value)}]" if self.show_data else label, 

89 "value": value, 

90 } 

91 for label, value in self.slices.items() 

92 ] 

93 chart = ChartVisual() 

94 try: 

95 spec = chart.read(safe_json.dumps({"type": "pie", "data": rows})) 

96 return chart.layout(spec, WIDTH, HEIGHT, theme) 

97 except VisualError as exc: 

98 raise MermaidSyntaxError(None, str(exc)) from None