MkDiagram¶
Class representing a mermaid diagram.¶
Description
MkDiagrams can show directed acyclic graphs and allows to manually create diagrams.
Example: Regular
Jinja
{{ ["1", "2", "3"] | MkDiagram(connections=[("1", "2"), ("2", "3")]) }}
Python
MkDiagram(['1', '2', '3'], {('1', '2'), ('2', '3')})
graph TD
1
2
3
1 --> 2
2 --> 3
````mermaid
graph TD
1
2
3
1 --> 2
2 --> 3
````
<pre><code class="language-mermaid">graph TD
1
2
3
1 --> 2
2 --> 3
</code></pre>
````mermaid
graph TD
1
2
3
1 --> 2
2 --> 3
````
Example: Direction
Jinja
{{ ["1", "2", "3"] | MkDiagram(connections=[("1", "2"), ("2", "3", "comment")], direction="LR") }}
Python
MkDiagram(['1', '2', '3'], {('2', '3', 'comment'), ('1', '2')}, direction='LR')
graph LR
1
2
3
2 --> |comment| 3
1 --> 2
````mermaid
graph LR
1
2
3
2 --> |comment| 3
1 --> 2
````
<pre><code class="language-mermaid">graph LR
1
2
3
2 --> |comment| 3
1 --> 2
</code></pre>
````mermaid
graph LR
1
2
3
2 --> |comment| 3
1 --> 2
````
Name |
Children |
Inherits |
|---|---|---|
MkClassDiagram |
||
MkPipDepTree |
Name |
Children |
Inherits |
|---|---|---|
MkCode |
graph TD
1128373226["mkdiagram.MkDiagram"]
1761293797["mkcode.MkCode"]
835538629["mkcontainer.MkContainer"]
1956333208["mkcontainer.MkContainerBase"]
1359323199["mknode.MkNode"]
2751680898["builtins.object"]
1761293797 --> 1128373226
835538629 --> 1761293797
1956333208 --> 835538629
1359323199 --> 1956333208
2751680898 --> 1359323199
/home/runner/work/mknodes/mknodes/src/mknodes/basenodes/mkdiagram/metadata.toml¶
[metadata]
icon = "mdi:graph-outline"
name = "MkDiagram"
group = "diagram"
[[requirements.extension."pymdownx.superfences".custom_fences]]
name = "mermaid"
class = "mermaid"
format = "pymdownx.superfences.fence_code_format"
[examples.regular]
title = "Regular"
jinja = """
{{ ["1", "2", "3"] | MkDiagram(connections=[("1", "2"), ("2", "3")]) }}
"""
[examples.direction]
title = "Direction"
jinja = """
{{ ["1", "2", "3"] | MkDiagram(connections=[("1", "2"), ("2", "3", "comment")], direction="LR") }}
"""
[output.markdown]
template = """
{{ node.fence_boundary }} mermaid
graph {{ node.direction }}
{% if node.connections %}
{% for name in node.names %}
{{ name }}
{% endfor %}
{% for connection in node.connections %}
{% if connection | length == 2 %}
{{ connection[0] }} --> {{ connection[1] }}
{% else %}
{{ connection[0] }} --> |{{ connection[2] }}| {{ connection[1] }}
{% endif %}
{% endfor %}
{% else %}
{% for name in node.names %}
{{ name | get_hash }}["{{ name }}"]
{% endfor %}
{% for prev, nxt in node.names | pairwise %}
{{ prev | get_hash }} --> {{ nxt | get_hash }}
{% endfor %}
{% endif %}
{{ node.fence_boundary }}
"""
mknodes.basenodes.mkdiagram.MkDiagram¶
22class MkDiagram(mkcode.MkCode):
23 """Class representing a mermaid diagram.
24
25 MkDiagrams can show directed acyclic graphs and allows to manually
26 create diagrams.
27 """
28
29 ICON = "material/graph-outline"
30 REQUIRED_EXTENSIONS = [resources.Extension("pymdownx.superfences", **config)]
31
32 def __init__(
33 self,
34 names: list[str] | None = None,
35 connections: list[tuple[str, str] | tuple[str, str, str]] | None = None,
36 *,
37 direction: Literal["TD", "DT", "LR", "RL"] = "TD",
38 **kwargs: Any,
39 ) -> None:
40 """Constructor.
41
42 Args:
43 names: names which should be part of the diagram
44 connections: tuples indicating the connections of the names
45 direction: diagram direction
46 kwargs: Keyword arguments passed to parent
47 """
48 super().__init__(language="mermaid", **kwargs)
49 self.direction = direction
50 # Preserve order. Useful if only names are passed, order is important then.
51 self.names = iterfilters.reduce_list(names or [])
52 self.connections = set(connections or [])
53
54 def get_text(self) -> str:
55 """MkCode override."""
56 return f"graph {self.direction}\n{self.get_mermaid_code()}"
57
58 def get_mermaid_code(self) -> str:
59 """Return code block, excluding fences and (graph type direction) line.
60
61 Can be overriden by subclasses.
62 """
63 lines = list(self.names)
64 if not self.connections:
65 lines = [f'{utils.get_hash(i)}["{i}"]' for i in lines]
66 for prev, nxt in itertools.pairwise(self.names):
67 lines.append(f"{utils.get_hash(prev)} --> {utils.get_hash(nxt)}")
68 return textwrap.indent("\n".join(lines), " ")
69 for connection in self.connections:
70 if len(connection) == 2: # noqa: PLR2004
71 source, target = connection
72 lines.append(f"{source} --> {target}")
73 elif len(connection) == 3: # noqa: PLR2004
74 source, target, mark = connection
75 lines.append(f"{source} --> |{mark}| {target}")
76 else:
77 msg = f"Tuple with wrong length: {connection}"
78 raise TypeError(msg)
79 return textwrap.indent("\n".join(lines), " ")
80
81 @property
82 def fence_title(self) -> str:
83 """MkCode override."""
84 return "mermaid"
Page info
Code for this page
mknodes.manual.nodes_section.create_section_for_nodes¶
93def create_section_for_nodes(
94 nav: mk.MkNav,
95 klasses: Sequence[type[mk.MkNode]],
96) -> mk.MkTable:
97 table = mk.MkTable(columns=["Node", "Docstrings", "Markdown extensions"])
98 for kls in klasses:
99 tpl = "classpage_custom.jinja"
100 page = mk.MkClassPage(kls, icon=kls.ICON, template_path=tpl, parent=nav, hide="toc")
101 nav += page
102 if kls.STATUS:
103 page.metadata.status = kls.STATUS
104 elif kls.JS_FILES:
105 page.metadata.status = "js"
106 elif kls.CSS:
107 page.metadata.status = "css"
108 page.created_by = create_section_for_nodes
109 link = mk.MkLink(page, kls.__name__, icon=kls.ICON)
110 extensions = ", ".join(f"`{i}`" for i in kls.REQUIRED_EXTENSIONS)
111 table.add_row((link, kls.__doc__, extensions))
112 return table
Resources
Resources(css=[],
markdown_extensions={'admonition': {},
'pymdownx.details': {},
'pymdownx.highlight': {'anchor_linenums': True,
'line_spans': '__span',
'pygments_lang_class': True},
'pymdownx.superfences': {'custom_fences': [{'class': 'mermaid',
'format': <function fence_code_format at 0x7ff77e88b060>,
'name': 'mermaid'}]},
'pymdownx.tabbed': {},
'tables': {}},
plugins=[Plugin('mkdocstrings')],
js=[],
assets=[],
packages=[])
Metadata
created:
source_filename: /home/runner/work/mknodes/mknodes/src/mknodes/manual/nodes_section.py
source_function: create_section_for_nodes
source_line_no: 93
hide:
- toc
icon: material/graph-outline
title: MkDiagram