Skip to content

Commit e48544e

Browse files
author
Laurent Franceschetti
committed
Add a new parameter javascript to the mermaid config
- it contains a url or local javascript file (relative to docs dir) - extra_javascript still allowed (and bypasses the new mechanism), but is now DEPRECATED
1 parent 70b52d0 commit e48544e

File tree

11 files changed

+3531
-58
lines changed

11 files changed

+3531
-58
lines changed

mermaid2/plugin.py

Lines changed: 73 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,9 @@
1717
# Constants and utilities
1818
# ------------------------
1919
# the default (recommended) mermaid lib
20-
MERMAID_LIB_VERSION = '10.1.0'
21-
# MERMAID_LIB = "https://unpkg.com/mermaid@%s/dist/mermaid.min.js"
22-
MERMAID_LIB_PRE_10 = "https://unpkg.com/mermaid@%s/dist/mermaid.min.js"
23-
MERMAID_LIB = "https://unpkg.com/mermaid@%s/dist/mermaid.esm.min.mjs"
20+
JAVASCRIPT_VERSION = '10.1.0'
21+
JAVASCRIPT_PRE_10 = "https://unpkg.com/mermaid@%s/dist/mermaid.min.js"
22+
JAVASCRIPT = "https://unpkg.com/mermaid@%s/dist/mermaid.esm.min.mjs"
2423

2524

2625

@@ -40,7 +39,8 @@ class MarkdownMermaidPlugin(BasePlugin):
4039
"""
4140
config_scheme = (
4241

43-
('version', PluginType(str, default=MERMAID_LIB_VERSION)),
42+
('version', PluginType(str, default=JAVASCRIPT_VERSION)),
43+
('javascript', PluginType(str, default=None)),
4444
('arguments', PluginType(dict, default={})),
4545
# ('custom_loader', PluginType(bool, default=False))
4646
)
@@ -70,9 +70,9 @@ def mermaid_version(self) -> str:
7070
"""
7171
The version of mermaid
7272
This information comes from the YAML file parameter,
73-
or, if empty, from MERMAID_LIB_VERSION.
73+
or, if empty, from JAVASCRIPT_VERSION.
7474
"""
75-
version = self.config['version']
75+
version = self.config['version'] or JAVASCRIPT_VERSION
7676
assert version, "No correct version of mermaid is provided!"
7777
return version
7878

@@ -89,41 +89,60 @@ def mermaid_major_version(self) -> int:
8989

9090

9191
@property
92-
def extra_mermaid_lib(self) -> str:
92+
def extra_javascript(self) -> str:
9393
"""
94-
Provides the mermaid library defined in mkdocs.yml (if any)
94+
Provides the mermaid.js library defined in mkdocs.yml
95+
under extra_javascript.
96+
97+
To be recognized, the library must have 'mermaid' in the filename.
98+
99+
WARNING:
100+
Using extra_javascript for that purpose was the original way,
101+
but is now DEPRECATED; it bypasses the new and better mechanisms
102+
for selecting the javascript library.
103+
It will insert the mermaid library in all pages, regardless
104+
of whether a mermaid diagram is present or not.
95105
"""
96-
# As of mkdocs 1.5, extra_javascript is a list of objects;
97-
# no longer a string. Call to str was used.
98-
# Patched in 1.5.1, with __fspath___ method,
99-
# see https://github.com/mkdocs/mkdocs/issues/3310
100-
# But we keep it, to guarantee it's a string.
101-
extra_javascript = map(str, self.full_config.get('extra_javascript', []))
102-
for lib in extra_javascript:
103-
# get the actual library name
104-
if libname(lib) == 'mermaid':
105-
return lib
106-
return ''
106+
if not hasattr(self, '_extra_javascript'):
107+
# As of mkdocs 1.5, extra_javascript is a list of objects;
108+
# no longer a string. Call to str was used.
109+
# Patched in 1.5.1, with __fspath___ method,
110+
# see https://github.com/mkdocs/mkdocs/issues/3310
111+
# But we keep it, to guarantee it's a string.
112+
extra_javascript = map(str, self.full_config.get('extra_javascript', []))
113+
for lib in extra_javascript:
114+
# check that 'mermaid' is in the filename, minus the extension.
115+
basename = os.path.basename(lib)
116+
basename, ext = os.path.splitext(basename)
117+
if 'mermaid' in basename.lower():
118+
self._extra_javascript = lib
119+
return lib
120+
self._extra_javascript = None
121+
return self._extra_javascript
107122

108123

109124
@property
110-
def mermaid_lib(self) -> str:
125+
def javascript(self) -> str:
111126
"""
112-
Provides the url of mermaid library according to version
113-
(distinction between version < 10 and after)
127+
Provides the url/pathanme of mermaid library according to version
128+
(distinction on the default, between version < 10 and after)
114129
"""
115-
if not hasattr(self, '_mermaid_lib'):
116-
if self.mermaid_major_version < 10:
117-
mermaid_lib = MERMAID_LIB_PRE_10 % self.mermaid_version
118-
else:
119-
# newer versions
120-
mermaid_lib = MERMAID_LIB % self.mermaid_version
121-
# make checks
122-
if not url_exists(mermaid_lib):
130+
if not hasattr(self, '_javascript'):
131+
# check if a mermaid javascript parameter exists:
132+
javascript = self.config['javascript']
133+
if not javascript:
134+
if self.mermaid_major_version < 10:
135+
javascript = JAVASCRIPT_PRE_10 % self.mermaid_version
136+
else:
137+
# newer versions
138+
javascript = JAVASCRIPT % self.mermaid_version
139+
# make checks
140+
if not url_exists(javascript,
141+
local_base_dir=self.full_config['docs_dir']):
123142
raise FileNotFoundError("Cannot find Mermaid library: %s" %
124-
mermaid_lib)
125-
self._mermaid_lib = mermaid_lib
126-
return self._mermaid_lib
143+
javascript)
144+
self._javascript = javascript
145+
return self._javascript
127146

128147

129148
@property
@@ -186,13 +205,18 @@ def on_config(self, config):
186205
assert isinstance(self.mermaid_args, dict)
187206
info("Initialization arguments:", self.mermaid_args)
188207
# info on the javascript library:
189-
if self.extra_mermaid_lib:
190-
info("Explicit mermaid javascript library:\n ",
191-
self.extra_mermaid_lib)
208+
if self.extra_javascript:
209+
info("Explicit mermaid javascript library from extra_javascript:\n ",
210+
self.extra_javascript)
211+
info("WARNING: Using extra_javascript is now DEPRECATED; "
212+
"use mermaid:javascript instead!")
213+
elif self.config['javascript']:
214+
info("Using specified javascript library: %s" %
215+
self.config['javascript'])
192216
else:
193217
info("Using javascript library (%s):\n "%
194218
self.config['version'],
195-
self.mermaid_lib)
219+
self.javascript)
196220

197221
def on_post_page(self, output_content, config, page, **kwargs):
198222
"""
@@ -239,23 +263,23 @@ def on_post_page(self, output_content, config, page, **kwargs):
239263
# insertion of the <script> tag, with the initialization arguments
240264
new_tag = soup.new_tag("script")
241265
js_code = [] # the code lines
242-
if not self.extra_mermaid_lib:
266+
if not self.extra_javascript:
243267
# if no extra library mentioned,
244268
# add the <SCRIPT> tag needed for mermaid
245-
info("Adding call to script for version"
246-
f"{self.mermaid_version}.")
247-
if self.mermaid_major_version < 10:
248-
# <script src="...">
249-
new_tag['src'] = self.mermaid_lib
250-
# it's necessary to close and reopen the tag:
251-
soup.body.append(new_tag)
252-
new_tag = soup.new_tag("script")
253-
else:
269+
if self.javascript.endswith('.mjs'):
254270
# <script type="module">
255271
# import mermaid from ...
256272
new_tag['type'] = "module"
257273
js_code.append('import mermaid from "%s";'
258-
% self.mermaid_lib)
274+
% self.javascript)
275+
else:
276+
# <script src="...">
277+
# generally for self.mermaid_major_version < 10:
278+
new_tag['src'] = self.javascript
279+
# it's necessary to close and reopen the tag:
280+
soup.body.append(new_tag)
281+
new_tag = soup.new_tag("script")
282+
259283
# (self.mermaid_args), as found in the config file.
260284
if self.activate_custom_loader:
261285
# if the superfences extension is present, use the specific loader

mermaid2/util.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,18 +32,21 @@ def info(*args) -> str:
3232
# Paths and URLs
3333
# -------------------
3434
def libname(lib:str) -> str:
35-
"Get the library name from a path"
35+
"Get the library name from a path -- not used"
3636
basename = os.path.basename(lib)
3737
# remove extension three times, e.g. mermaid.min.js => mermaid
3838
t = basename
3939
for _ in range(3):
4040
t = os.path.splitext(t)[0]
4141
return t
4242

43-
def url_exists(url:str) -> bool:
43+
44+
45+
def url_exists(url:str, local_base_dir:str='') -> bool:
4446
"Checks that a url exists"
4547
if url.startswith('http'):
4648
request = requests.get(url)
4749
return request.status_code == 200
4850
else:
49-
os.path.exists(url)
51+
pathname = os.path.join(local_base_dir, url)
52+
return os.path.exists(pathname)

setup.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from setuptools import setup, find_packages
22

33

4-
VERSION = '1.0.8'
4+
VERSION = '1.0.9'
55

66
# required if you want to run tests
77
# pip install 'mkdocs-mermaid2-plugin[test]'
@@ -16,9 +16,7 @@ def readme():
1616

1717
LONG_DESCRIPTION = (
1818
"An Mkdocs plugin that renders Mermaid graphs in the markdown file. "
19-
"To install, please follow instructions in the Readme file.\n"
20-
"This is a fork of the Pugong Liu's excellent project, "
21-
"which is no longer maintained."
19+
"To install, please follow instructions in the README file."
2220
)
2321

2422
setup(
@@ -28,8 +26,8 @@ def readme():
2826
long_description=LONG_DESCRIPTION,
2927
keywords='mkdocs python markdown mermaid',
3028
url='https://github.com/fralau/mkdocs-mermaid2-plugin',
31-
author='pugong, Fralau',
32-
29+
author='Fralau',
30+
author_email='[email protected]',
3331
license='MIT',
3432
python_requires='>=3.6',
3533
install_requires=[
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Mermaid test (simple)
2+
3+
## Mermaid usual
4+
This is a test of Mermaid:
5+
6+
```mermaid
7+
graph TD
8+
hello --> world
9+
world --> world2
10+
```
11+
12+
> If you don't see a graph here, it's broken.
13+
14+
## Git Graph
15+
This is a test of Git Graph:
16+
17+
```mermaid
18+
gitGraph
19+
commit
20+
commit
21+
branch develop
22+
checkout develop
23+
commit
24+
commit
25+
checkout main
26+
merge develop
27+
commit
28+
commit
29+
```
30+
31+
32+
## Normal fences
33+
This is usual fenced code (with no highlighting)
34+
35+
```python
36+
for page in pages:
37+
page.read()
38+
```
39+

test/extra_javascript/docs/js/mermaid.min.js

Lines changed: 1642 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Second page
2+
Testing special cases
3+
4+
## Wrong diagram
5+
6+
```mermaid
7+
graph FG
8+
A[Client]
9+
```
10+
11+
## Correct
12+
13+
```mermaid
14+
graph TD
15+
A[Client] --> B[Load Balancer]
16+
```
17+
18+
## Other
19+
20+
```mermaid
21+
graph TD
22+
A[Client] --> B[Load Balancer]
23+
B --> C[Server01]
24+
B --> D[Server02]
25+
```

test/extra_javascript/mkdocs.yml

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
site_name: Mermaid test (simple, extra_javascript)
2+
site_description: Test for mermaid
3+
docs_dir: docs # indispensable or readthedocs will fail
4+
theme: readthedocs # you may want to try windmill?
5+
6+
7+
nav:
8+
- Main: index.md
9+
- Second: second.md
10+
11+
plugins:
12+
- search
13+
- mermaid2
14+
15+
extra_javascript:
16+
- js/mermaid.min.js
17+
18+
19+

test/local_lib/docs/index.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Mermaid test (simple)
2+
3+
## Mermaid usual
4+
This is a test of Mermaid:
5+
6+
```mermaid
7+
graph TD
8+
hello --> world
9+
world --> world2
10+
```
11+
12+
> If you don't see a graph here, it's broken.
13+
14+
## Git Graph
15+
This is a test of Git Graph:
16+
17+
```mermaid
18+
gitGraph
19+
commit
20+
commit
21+
branch develop
22+
checkout develop
23+
commit
24+
commit
25+
checkout main
26+
merge develop
27+
commit
28+
commit
29+
```
30+
31+
32+
## Normal fences
33+
This is usual fenced code (with no highlighting)
34+
35+
```python
36+
for page in pages:
37+
page.read()
38+
```
39+

test/local_lib/docs/js/mermaid.min.js

Lines changed: 1642 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

test/local_lib/docs/second.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Second page
2+
Testing special cases
3+
4+
## Wrong diagram
5+
6+
```mermaid
7+
graph FG
8+
A[Client]
9+
```
10+
11+
## Correct
12+
13+
```mermaid
14+
graph TD
15+
A[Client] --> B[Load Balancer]
16+
```
17+
18+
## Other
19+
20+
```mermaid
21+
graph TD
22+
A[Client] --> B[Load Balancer]
23+
B --> C[Server01]
24+
B --> D[Server02]
25+
```

0 commit comments

Comments
 (0)