Coverage for src/python/ensembl/vep/render/graph/mermaid.py: 100%
23 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
1# See the NOTICE file distributed with this work for additional information
2# regarding copyright ownership.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Rendering a graph as Mermaid flowchart source."""
16from __future__ import annotations
18import re
20from ensembl.vep.render.graph.model import Graph
22__all__ = ["render_mermaid"]
24_UNSAFE = re.compile(r"[^0-9A-Za-z_]")
27def _identifier(raw: str) -> str:
28 """Return an identifier Mermaid accepts unquoted."""
29 return _UNSAFE.sub("_", raw)
32def _label(text: str) -> str:
33 """Return label text with the characters Mermaid treats as syntax removed."""
34 return text.replace('"', "'").replace("[", "(").replace("]", ")")
37def render_mermaid(graph: Graph) -> str:
38 """Return a graph as a left-to-right Mermaid flowchart.
40 Node state becomes a Mermaid class rather than a colour, so the diagram picks up whatever
41 theme the surrounding document defines.
42 """
43 lines = ["flowchart LR"]
45 for node in graph.nodes:
46 identifier = _identifier(node.identifier)
47 lines.append(f' {identifier}["{_label(node.label)}"]')
48 if node.state:
49 lines.append(f" class {identifier} {_identifier(node.state)};")
51 for edge in graph.edges:
52 source = _identifier(edge.source)
53 target = _identifier(edge.target)
54 if edge.label:
55 lines.append(f" {source} -->|{_label(edge.label)}| {target}")
56 else:
57 lines.append(f" {source} --> {target}")
59 return "\n".join(lines)