Skip to content

Commit

Permalink
Make the plugin compatible with mermaid library >= 10 (#70)
Browse files Browse the repository at this point in the history
  - now the plugin works with versions of the library > 10 and lower
    (the proper <SCRIPT></SCRIPT> call is inserted)
  - Git Graph works and can be check in test/simple (#75)
  • Loading branch information
Laurent Franceschetti committed Apr 27, 2023
1 parent 3608781 commit e17764d
Show file tree
Hide file tree
Showing 7 changed files with 250 additions and 67 deletions.
143 changes: 88 additions & 55 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ descriptions into [Mermaid](https://mermaid-js.github.io/mermaid) graphs
> which is no longer maintained. It offers expanded documentation as
> well as new functions.
> As of version 1.0.0, this plugin works with versions of the Mermaid library > 10,
> **and** with lower versions.

<!-- To update the toc, run the following command:
Expand All @@ -26,47 +28,46 @@ markdown-toc -i README.md

<!-- toc -->

- [mkdocs-mermaid2-plugin](#mkdocs-mermaid2-plugin)
- [How it works](#how-it-works)
- [Installation](#installation)
- [Automatic](#automatic)
- [Manual](#manual)
- [Configuration](#configuration)
- [Basic configuration](#basic-configuration)
- [Specifying the version of the Mermaid library](#specifying-the-version-of-the-mermaid-library)
- [Explicit declaration of the Mermaid library](#explicit-declaration-of-the-mermaid-library)
- [Usage](#usage)
- [General Principle](#general-principle)
- [How to write Mermaid diagrams](#how-to-write-mermaid-diagrams)
- [Adding arguments to the Mermaid engine](#adding-arguments-to-the-mermaid-engine)
- [Testing](#testing)
- [Adding a Javascript callback function](#adding-a-javascript-callback-function)
- [Use Case](#use-case)
- [Method](#method)
- [Tips and Tricks](#tips-and-tricks)
- [Setting the security level to "loose"](#setting-the-security-level-to-loose)
- [Formating text in diagrams](#formating-text-in-diagrams)
- [Adding Hyperlinks to a Diagram (versions of Mermaid javascript >~ 8.5.0)](#adding-hyperlinks-to-a-diagram-versions-of-mermaid-javascript--850)
- [Adding Hyperlinks to a Diagram (versions of Mermaid javascript <~ 8.5.0)](#adding-hyperlinks-to-a-diagram-versions-of-mermaid-javascript--850-1)
- [Auto-configure dark mode based on Host OS](#auto-configure-dark-mode-based-on-host-os)
- [Material Theme: Switching the Mermaid diagram on the fly between light and dark mode](#material-theme-switching-the-mermaid-diagram-on-the-fly-between-light-and-dark-mode)
- [Compatibility](#compatibility)
- [List](#list)
- [Using Mermaid and code highlighting at the same time](#using-mermaid-and-code-highlighting-at-the-same-time)
- [Usage](#usage-1)
- [Use of markdown extensions](#use-of-markdown-extensions)
- [Declaring the superfences extension](#declaring-the-superfences-extension)
- [Troubleshooting: the mermaid diagram is not being displayed](#troubleshooting-the-mermaid-diagram-is-not-being-displayed)
- [Seeing an error message at the place of the diagram?](#seeing-an-error-message-at-the-place-of-the-diagram)
- [The mermaid source code appears as-is (not read)?](#the-mermaid-source-code-appears-as-is-not-read)
- [Using another theme than material ?](#using-another-theme-than-material-)
- [Using superfences, but no diagram is displayed?](#using-superfences-but-no-diagram-is-displayed)
- [Is mkdocs' version up to date (>= 1.1) ?](#is-mkdocs-version-up-to-date--11-)
- [Is the javascript library properly called?](#is-the-javascript-library-properly-called)
- [Troubleshooting: other issues](#troubleshooting-other-issues)
- [Rich text diagrams, or links are not displayed properly?](#rich-text-diagrams-or-links-are-not-displayed-properly)
- [With pymdownx.details, diagrams in collapsed elements are not displayed?](#with-pymdownxdetails-diagrams-in-collapsed-elements-are-not-displayed)
- [Using the mermaid2.dumps() function](#using-the-mermaid2dumps-function)
- [How it works](#how-it-works)
- [Installation](#installation)
* [Automatic](#automatic)
* [Manual](#manual)
- [Configuration](#configuration)
* [Basic configuration](#basic-configuration)
* [Specifying the version of the Mermaid library](#specifying-the-version-of-the-mermaid-library)
* [Explicit declaration of the Mermaid library](#explicit-declaration-of-the-mermaid-library)
- [Usage](#usage)
* [General Principle](#general-principle)
* [How to write Mermaid diagrams](#how-to-write-mermaid-diagrams)
* [Adding arguments to the Mermaid engine](#adding-arguments-to-the-mermaid-engine)
* [Testing](#testing)
* [Adding a Javascript callback function](#adding-a-javascript-callback-function)
+ [Use Case](#use-case)
+ [Method](#method)
- [Tips and Tricks](#tips-and-tricks)
* [Setting the security level to "loose"](#setting-the-security-level-to-loose)
* [Formating text in diagrams](#formating-text-in-diagrams)
* [Adding Hyperlinks to a Diagram (versions of Mermaid javascript >~ 8.5.0)](#adding-hyperlinks-to-a-diagram-versions-of-mermaid-javascript--850)
* [Adding Hyperlinks to a Diagram (versions of Mermaid javascript <~ 8.5.0)](#adding-hyperlinks-to-a-diagram-versions-of-mermaid-javascript--850)
* [Auto-configure dark mode based on Host OS](#auto-configure-dark-mode-based-on-host-os)
* [Material Theme: Switching the Mermaid diagram on the fly between light and dark mode](#material-theme-switching-the-mermaid-diagram-on-the-fly-between-light-and-dark-mode)
- [Compatibility](#compatibility)
* [List](#list)
* [Using Mermaid and code highlighting at the same time](#using-mermaid-and-code-highlighting-at-the-same-time)
+ [Usage](#usage-1)
+ [Use of markdown extensions](#use-of-markdown-extensions)
+ [Declaring the superfences extension](#declaring-the-superfences-extension)
- [Troubleshooting: the mermaid diagram is not being displayed](#troubleshooting-the-mermaid-diagram-is-not-being-displayed)
* [Seeing an error message at the place of the diagram?](#seeing-an-error-message-at-the-place-of-the-diagram)
* [The mermaid source code appears as-is (not read)?](#the-mermaid-source-code-appears-as-is-not-read)
* [Using another theme than material ?](#using-another-theme-than-material-)
* [Using superfences, but no diagram is displayed?](#using-superfences-but-no-diagram-is-displayed)
* [Is mkdocs' version up to date (>= 1.1) ?](#is-mkdocs-version-up-to-date--11-)
* [Is the javascript library properly called?](#is-the-javascript-library-properly-called)
- [Troubleshooting: other issues](#troubleshooting-other-issues)
* [Rich text diagrams, or links are not displayed properly?](#rich-text-diagrams-or-links-are-not-displayed-properly)
* [With pymdownx.details, diagrams in collapsed elements are not displayed?](#with-pymdownxdetails-diagrams-in-collapsed-elements-are-not-displayed)
- [Using the mermaid2.dumps() function](#using-the-mermaid2dumps-function)

<!-- tocstop -->

Expand Down Expand Up @@ -96,12 +97,25 @@ It also inserts a call to the
mermaid.initialize(...)
</script>

To interpret that code it inserts a call to the Mermaid library:
```javascript
<script src="https://unpkg.com/mermaid/dist/mermaid.min.js">
To interpret that code it inserts a call to the Mermaid library.

> **From version 1.0 of mkdocs-mermaid2:**
E.g. for version 10.0.2:
```html
<script type="module">
import mermaid from "https://unpkg.com/[email protected]/dist/mermaid.esm.min.mjs"
</script>
```

Or for an earlier version of the library:
```html
<script src="https://unpkg.com/[email protected]/dist/mermaid.min.js">
</script>
```



The user's browser will then read this code and render it on the fly.

> No svg/png images are harmed during the rendering of that graph.
Expand Down Expand Up @@ -158,13 +172,17 @@ You may specify a different version of the Mermaid library, like so:
plugins:
- search
- mermaid2:
version: 8.6.4
version: 10.0.2
```

> **From version 1.0.0 of Mermaid**
If you select a version of the Mermaid library lower than 10.0.0.,
the plugin will adapt the call to the script accordingly
(`<SCRIPT>...</SCRIPT>`).


### Explicit declaration of the Mermaid library
> If you use a version of the plugin >= 0.4, the basic steps are sufficient.
> Changes since version 1.1.0
You _may_ specify the mermaid library explicitly, as long as it is
call mermaid (independently of extension):
Expand All @@ -174,15 +192,31 @@ extra_javascript:
- https://unpkg.com/[email protected]/dist/mermaid.min.js
```

For the latest version:
> This will work **only** for versions of the Mermaid javascript
> library < 10.0.0.

Of course, you may also declare a local file:

```yaml
extra_javascript:
- https://unpkg.com/mermaid/dist/mermaid.min.js
- js/mermaidloader.js
```

Where `js` is a subdirectory of the document directory (`docs`).

If you are using a local javascript file, it is up to you to make it work,
with a version of the Mermaid library > 10 e.g.:

```yaml
import mermaid from "https://unpkg.com/[email protected]/dist/mermaid.esm.min.mjs"
mermaid.initialize()
```

No explicit call to `mermaid.initialize()` is required, since it is called
from inside the plugin.


> **Note for plugin version < 0.4:** You **must*** include the mermaid.min.js (local or remotely) in your `mkdocs.yml`. If you want to be on the safe side, you may want to specify a version that you know is working for you, e.g. `https://unpkg.com/[email protected]/dist/mermaid.min.js`



Expand Down Expand Up @@ -609,13 +643,12 @@ Or, if you cloned this repo:
> an error.
In order to work, the proper javascript library must called from
the html page.

The configuration file (`mkdocs.yml`) should contain the following line:

extra_javascript:
- https://unpkg.com/mermaid/dist/mermaid.min.js
the html page (this is done automatically).
If necessary check the link used in the HTML page generated, e.g.:

```HTML
<script type="module">import mermaid from "https://unpkg.com/[email protected]/dist/mermaid.esm.min.mjs"</script>
```
Every diagram should start with a valid preamble, e.g. `graph TD`.
Expand Down
75 changes: 64 additions & 11 deletions mermaid2/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import os


from mkdocs.plugins import BasePlugin
from mkdocs.config.config_options import Type as PluginType
from bs4 import BeautifulSoup
Expand All @@ -16,12 +17,23 @@
# Constants and utilities
# ------------------------
# the default (recommended) mermaid lib
MERMAID_LIB_VERSION = '8.8.0'
MERMAID_LIB = "https://unpkg.com/mermaid@%s/dist/mermaid.min.js"
MERMAID_LIB_VERSION = '10.0.2'
# MERMAID_LIB = "https://unpkg.com/mermaid@%s/dist/mermaid.min.js"
MERMAID_LIB_PRE_10 = "https://unpkg.com/mermaid@%s/dist/mermaid.min.js"
MERMAID_LIB = "https://unpkg.com/mermaid@%s/dist/mermaid.esm.min.mjs"


MERMAID_CODE_PRE_10 = '<script src="%s">\n'
MERMAID_CODE = '<script type="module">import mermaid from "%s"</script>\n'



# Two conditions for activating custom fences:
SUPERFENCES_EXTENSION = 'pymdownx.superfences'
CUSTOM_FENCE_FN = 'fence_mermaid_custom'



# ------------------------
# Plugin
# ------------------------
Expand Down Expand Up @@ -55,6 +67,29 @@ def mermaid_args(self):
The arguments for mermaid.
"""
return self._mermaid_args

@property
def mermaid_version(self) -> str:
"""
The version of mermaid
This information comes from the YAML file parameter,
or, if empty, from MERMAID_LIB_VERSION.
"""
version = self.config['version']
assert version, "No correct version of mermaid is provided!"
return version

@property
def mermaid_major_version(self) -> int:
"""
Major version of mermaid (e.g. 8. 9, 10) as int
"""
major = self.mermaid_version.split('.')[0]
try:
return int(major)
except:
ValueError("Mermaid version provided has incorrect format")


@property
def extra_mermaid_lib(self) -> str:
Expand All @@ -72,16 +107,31 @@ def extra_mermaid_lib(self) -> str:
@property
def mermaid_lib(self) -> str:
"""
Provides the actual mermaid library used
Provides the url of mermaid library according to version
(distinction between version < 10 and after)
"""
if not hasattr(self, '_mermaid_lib'):
mermaid_version = self.config['version']
lib = self.extra_mermaid_lib or MERMAID_LIB % mermaid_version
if not url_exists(lib):
if self.mermaid_major_version < 10:
mermaid_lib = MERMAID_LIB_PRE_10 % self.mermaid_version
else:
# newer versions
mermaid_lib = MERMAID_LIB % self.mermaid_version
# make checks
if not url_exists(mermaid_lib):
raise FileNotFoundError("Cannot find Mermaid library: %s" %
lib)
self._mermaid_lib = lib
mermaid_lib)
self._mermaid_lib = mermaid_lib
return self._mermaid_lib

@property
def mermaid_script(self) -> str:
"""
Provides the mermaid script to be inserted into the code
"""
if self.mermaid_major_version < 10:
return MERMAID_CODE_PRE_10 % self.mermaid_lib
else:
return MERMAID_CODE % self.mermaid_lib

@property
def activate_custom_loader(self) -> bool:
Expand Down Expand Up @@ -192,12 +242,15 @@ def on_post_page(self, output_content, config, page, **kwargs):
info("Page '%s': found %s diagrams, adding scripts" %
(page_name, mermaids))
if not self.extra_mermaid_lib:
# if no extra library mentioned specify it
new_tag = soup.new_tag("script", src=self.mermaid_lib)
# if no extra library mentioned,
# add the <SCRIPT> tag needed for mermaid
info("Adding call to script for version"
f"{self.mermaid_version}.")
new_tag = BeautifulSoup(self.mermaid_script, 'html.parser')
soup.body.append(new_tag)
# info(new_tag)
# initialization command
new_tag = soup.new_tag("script")
# initialization command
if self.activate_custom_loader:
# if the superfences extension is present, use the specific loader
self.mermaid_args['startOnLoad'] = False
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from setuptools import setup, find_packages


VERSION = '0.6.0'
VERSION = '1.0.0-alpha'

def readme():
"""print long description"""
Expand Down
23 changes: 23 additions & 0 deletions test/simple_pre_10/docs/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Mermaid test (simple)

## Mermaid usual
This is a test of Mermaid:

```mermaid
graph TD
hello --> world
world --> world2
```

> If you don't see a graph here, it's broken.


## Normal fences
This is usual fenced code (with no highlighting)

```python
for page in pages:
page.read()
```

31 changes: 31 additions & 0 deletions test/simple_pre_10/docs/js/extra.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// js/extra.js
function myMermaidCallbackFunction(id) {
var d = new Date();
var now = d.toLocaleTimeString();
console.log('Hello, this is myMermaidCallbackFunction', id, now);
}


// import uml from "./uml"

// (() => {
// const onReady = function(fn) {
// if (document.addEventListener) {
// document.addEventListener("DOMContentLoaded", fn)
// document.addEventListener("DOMContentSwitch", fn)
// } else {
// document.attachEvent("onreadystatechange", () => {
// if (document.readyState === "interactive") {
// fn()
// }
// })
// }
// }

// onReady(() => {

// if (typeof mermaid !== "undefined") {
// uml("mermaid")
// }
// })
// })()
Loading

0 comments on commit e17764d

Please sign in to comment.