Coverage for app / documents / visuals / mermaid / labels.py: 88%
42 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""A label as Mermaid shows it: ``<br>`` breaks a line, ``#quot;`` and the
2like are characters, HTML tags and markdown string quotes are dropped."""
4from __future__ import annotations
6import html
7import re
9from ..text import ELLIPSIS, ellipsize, wrap_lines
11_BREAK = re.compile(r"<br\s*/?>|\\n", re.IGNORECASE)
12_TAG = re.compile(r"</?[a-zA-Z][^>]*>")
13#: Mermaid's own entity codes: ``#quot;``, ``#35;``, ``#9829;``.
14_CODE = re.compile(r"#([a-zA-Z]+|\d+);")
15_ICON = re.compile(r"\bfa[bsrl]?:fa-[\w-]+\s*")
16_NAMED = {"quot": '"', "amp": "&", "lt": "<", "gt": ">", "nbsp": " ", "apos": "'"}
19def _code(match: re.Match[str]) -> str:
20 code = match.group(1)
21 if code.isdigit():
22 try:
23 return chr(int(code))
24 except (ValueError, OverflowError):
25 return ""
26 return _NAMED.get(code.lower(), match.group(0))
29def clean(text: str) -> list[str]:
30 """``text`` as the lines Mermaid would draw."""
31 text = text.strip()
32 if len(text) >= 2 and text[0] == '"' and text[-1] == '"':
33 text = text[1:-1]
34 if len(text) >= 2 and text[0] == "`" and text[-1] == "`":
35 text = text[1:-1].replace("**", "").replace("*", "")
36 text = _ICON.sub("", text)
37 lines = _BREAK.split(text)
38 out = []
39 for line in lines:
40 line = _TAG.sub("", line)
41 line = _CODE.sub(_code, line)
42 line = html.unescape(line)
43 out.append(" ".join(line.split()))
44 while out and not out[-1]:
45 out.pop()
46 return out or [""]
49def fit(
50 text: str, font: str, size: float, max_width: float, max_lines: int
51) -> list[str]:
52 """``text`` cleaned and wrapped to ``max_width``, at most ``max_lines``
53 lines (the last ending in an ellipsis when some is left over)."""
54 out: list[str] = []
55 for line in clean(text):
56 out += wrap_lines(line, font, size, max_width, max_lines) if line else [""]
57 if len(out) > max_lines:
58 out = out[:max_lines]
59 out[-1] = ellipsize(out[-1] + ELLIPSIS, font, size, max_width)
60 return out or [""]