Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support node name for non-captioned #145

Merged
merged 1 commit into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ Then add ``sphinxcontrib.mermaid`` in ``extensions`` list of your project's ``co
Directive options
------------------

``:name:``: determines the image's name (id) for HTML output.

``:alt:``: determines the image's alternate text for HTML output. If not given, the alternate text defaults to the mermaid code.

``:align:``: determines the image's position. Valid options are ``'left'``, ``'center'``, ``'right'``
Expand Down
53 changes: 28 additions & 25 deletions sphinxcontrib/mermaid.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@
import codecs
import errno
import os
import shlex
import posixpath
import re
import shlex
import uuid
from hashlib import sha1
from json import loads
from subprocess import PIPE, Popen
from tempfile import TemporaryDirectory
import uuid

import sphinx
from docutils import nodes
Expand Down Expand Up @@ -115,6 +115,7 @@ class Mermaid(Directive):
final_argument_whitespace = False
option_spec = {
# Sphinx directives
"name": directives.unchanged,
"alt": directives.unchanged,
"align": align_spec,
"caption": directives.unchanged,
Expand Down Expand Up @@ -200,9 +201,10 @@ def run(self, **kwargs):
node["code"] = mm_config + node["code"]

caption = self.options.get("caption")
if caption:
if caption is not None:
node = figure_wrapper(self, node, caption)

self.add_name(node)
return [node]


Expand Down Expand Up @@ -298,28 +300,29 @@ def render_mm(self, code, options, _fmt, prefix="mermaid"):
def _render_mm_html_raw(
self, node, code, options, prefix="mermaid", imgcls=None, alt=None
):
if "align" in node and "zoom_id" in node:
tag_template = """<pre align="{align}" id="{zoom_id}" class="mermaid align-{align}">
{code}
</pre>
"""
elif "align" in node and "zoom_id" not in node:
tag_template = """<pre align="{align}" class="mermaid align-{align}">
{code}
</pre>
"""
elif "align" not in node and "zoom_id" in node:
tag_template = """<pre id="{zoom_id}" class="mermaid">
{code}
</pre>
"""
else:
tag_template = """<pre class="mermaid">
{code}
</pre>"""
classes = ["mermaid"]
attrs = {}

if "align" in node:
classes.append(f"align-{node['align']}")
attrs["align"] = node["align"]

if "zoom_id" in node:
attrs["data-zoom-id"] = node["zoom_id"]

if "ids" in node and len(node["ids"]) == 1:
attrs["id"] = node["ids"][0]

tag_template = """<pre {attr_defs} class="{classes}">
{code}
</pre>"""
attr_defs = ["{}=\"{}\"".format(k, v) for k, v in attrs.items()]
self.body.append(
tag_template.format(align=node.get("align"), zoom_id=node.get("zoom_id"), code=self.encode(code))
tag_template.format(
attr_defs=" ".join(attr_defs),
classes=" ".join(classes),
code=self.encode(code)
)
)
raise nodes.SkipNode

Expand Down Expand Up @@ -540,9 +543,9 @@ def install_js(
if "zoom_id" in mermaid_node:
_zoom_id = mermaid_node["zoom_id"]
if _d3_selector == "":
_d3_selector += f".mermaid#{_zoom_id} svg"
_d3_selector += f".mermaid[data-zoom-id={_zoom_id}] svg"
else:
_d3_selector += f", .mermaid#{_zoom_id} svg"
_d3_selector += f", .mermaid[data-zoom-id={_zoom_id}] svg"
count += 1
if _d3_selector != "":
_d3_js_script = _MERMAID_RUN_D3_ZOOM.format(d3_selector=_d3_selector, d3_node_count=count, mermaid_js_url=_mermaid_js_url)
Expand Down
1 change: 1 addition & 0 deletions tests/roots/test-basic/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ Hi, basic test
--------------

.. mermaid::
:name: participants

sequenceDiagram
participant Alice
Expand Down
1 change: 1 addition & 0 deletions tests/roots/test-basic/zoom.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ Zooming
-------

.. mermaid::
:name: participants

sequenceDiagram
participant Alice
Expand Down
6 changes: 5 additions & 1 deletion tests/roots/test-markdown/index.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
# Hi from Markdown!

```{mermaid}
:align: center
---
align: center
name: participants
---

sequenceDiagram
participant Alice
participant Bob
Expand Down
24 changes: 7 additions & 17 deletions tests/test_html.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import pytest
import re

import pytest


@pytest.fixture
def build_all(app):
Expand All @@ -22,12 +23,7 @@ def test_html_raw(index):
)
assert '<script type="module">import mermaid from "https://cdn.jsdelivr.net/npm/[email protected]/dist/mermaid.esm.min.mjs";import elkLayouts from "https://cdn.jsdelivr.net/npm/@mermaid-js/[email protected]/dist/mermaid-layout-elk.esm.min.mjs";mermaid.registerLayoutLoaders(elkLayouts);mermaid.initialize({startOnLoad:false});</script>' in index
assert (
"""<pre class="mermaid">
sequenceDiagram
participant Alice
participant Bob
Alice-&gt;John: Hello John, how are you?
</pre>"""
'<pre id="participants" class="mermaid">\n sequenceDiagram\n participant Alice\n participant Bob\n Alice-&gt;John: Hello John, how are you?\n </pre>'
in index
)

Expand All @@ -40,13 +36,13 @@ def test_html_zoom_option(index, app):
assert "svg.call(zoom);" in zoom_page

# the first diagram has no id
assert '<pre class="mermaid">\n sequenceDiagram' in zoom_page
assert '<pre id="participants" class="mermaid">\n sequenceDiagram' in zoom_page

# the second has id and its loaded in the zooming code.
pre_id = re.findall(
r'<pre id="(id\-[a-fA-F0-9-]+)" class="mermaid">\n\s+flowchart TD', zoom_page
r'<pre data-zoom-id="(id\-[a-fA-F0-9-]+)" class="mermaid">\n\s+flowchart TD', zoom_page
)
assert f'var svgs = d3.selectAll(".mermaid#{pre_id[0]} svg")' in zoom_page
assert f'var svgs = d3.selectAll(".mermaid[data-zoom-id={pre_id[0]}] svg")' in zoom_page


@pytest.mark.sphinx("html", testroot="basic", confoverrides={"mermaid_d3_zoom": True})
Expand Down Expand Up @@ -126,12 +122,6 @@ def test_html_raw_from_markdown(index):
)
assert '<script type="module">import mermaid from "https://cdn.jsdelivr.net/npm/[email protected]/dist/mermaid.esm.min.mjs";import elkLayouts from "https://cdn.jsdelivr.net/npm/@mermaid-js/[email protected]/dist/mermaid-layout-elk.esm.min.mjs";mermaid.registerLayoutLoaders(elkLayouts);mermaid.initialize({startOnLoad:false});</script>' in index
assert (
"""
<pre align="center" class="mermaid align-center">
sequenceDiagram
participant Alice
participant Bob
Alice-&gt;John: Hello John, how are you?
</pre>"""
'<pre align="center" id="participants" class="mermaid align-center">\n sequenceDiagram\n participant Alice\n participant Bob\n Alice-&gt;John: Hello John, how are you?\n </pre>'
in index
)