Update documents to compatible jekyll-rtd-theme

This commit is contained in:
saowang
2020-08-21 01:01:06 +08:00
parent f63b58edd9
commit 9e8c6aed4d
67 changed files with 435 additions and 295 deletions

View File

@@ -0,0 +1,217 @@
---
sort: 4
title: Directives
---
# Version 8.6.0 Changes
## [New Mermaid Live-Editor Beta](https://mermaid-js.github.io/docs/mermaid-live-editor-beta/#/edit/eyJjb2RlIjoiJSV7aW5pdDoge1widGhlbWVcIjogXCJmb3Jlc3RcIiwgXCJsb2dMZXZlbFwiOiAxIH19JSVcbmdyYXBoIFREXG4gIEFbQ2hyaXN0bWFzXSAtLT58R2V0IG1vbmV5fCBCKEdvIHNob3BwaW5nKVxuICBCIC0tPiBDe0xldCBtZSB0aGlua31cbiAgQyAtLT58T25lfCBEW0xhcHRvcF1cbiAgQyAtLT58VHdvfCBFW2lQaG9uZV1cbiAgQyAtLT58VGhyZWV8IEZbZmE6ZmEtY2FyIENhcl1cblx0XHQiLCJtZXJtYWlkIjp7InRoZW1lIjoiZGFyayJ9fQ)
## [CDN](https://unpkg.com/mermaid/)
With version 8.6.0 comes the release of directives for mermaid, a new system for modifying configurations, with the aim of establishing centralized, sane defaults and simple implementation.
`directives` allow for a diagram specific overriding of `config`, as it has been discussed in [Configurations](./Setup.md).
This allows site users to input modifications to `config` alongside diagram definitions, when creating diagrams on a private webpage that supports mermaid.
**A likely application for this is in the creation of diagrams/charts inside company/organizational webpages, that rely on mermaid for diagram and chart rendering.**
the `init` directive is the main method of configuration for Site and Current Levels.
The three levels of are Configuration, Global, Site and Current.
| Level of Configuration | Description |
| --- | --- |
| Global Configuration| Default Mermaid Configurations|
| Site Configuration| Configurations made by site owner|
| Current Configuration| Configurations made by Implementors|
# Limits to Modifying Configurations
**secure Array**
| Parameter | Description |Type | Required | Values|
| --- | --- | --- | --- | --- |
| secure | Array of parameters excluded from init directive| Array | Required | Any parameters|
The modifiable parts of the Configuration are limited by the secure array, which is an array of immutable parameters, this array can be expanded by site owners.
**Notes**: secure arrays work like nesting dolls, with the Global Configurations secure array being the default and immutable list of immutable parameters, or the smallest doll, to which site owners may add to, but implementors may not modify it.
# Secure Arrays
Site owners can add to the **secure** array using this command:
mermaidAPI.initialize( { startOnLoad: true, secure: ['parameter1', 'parameter2'] } );
default values for the `secure array` consists of: ['secure', 'securityLevel', 'startOnLoad', 'maxTextSize']. These default values are immutable.
Implementors can only modify configurations using directives, but cannot change the `secure` array.
# Modifying Configurations and directives:
The Two types of directives: are `init` or `initialize` and `wrap`.
```note
All directives are enclosed in `%%{ }%%.`
```
Older versions of mermaid will not parse directives because `%%` will comment out the directive. This makes the update backward compatible.
# Init
`init`, or `initialize`: the init or initialize directive gives the user the ability to overwrite and change the values for configuration parameters, with respect to the secure array that is in effect.
| Parameter | Description |Type | Required | Values|
| --- | --- | --- | --- | --- |
| init | modifies configurations| Directive| Optional | Any parameters not included in the secure array|
```note
init would be an argument-directive: `%%{init: { **insert argument here**}}%%`
The json object that is passed as {**argument** } must be valid, quoted json or it will be ignored.
**for example**:
`%%{init: {"theme": default, "logLevel": 1 }}%%`
Configurations that are passed through init cannot change the parameters in secure arrays of higher levels. In the event of a conflict, mermaid will give priority to secure arrays and parse the request, without changing the values of the parameters in conflict.
When deployed within code, init is called before the graph/diagram description.
```
**for example**:
```
%%{init: {"theme": "default", "logLevel": 1 }}%%
graph LR
a-->b
b-->c
c-->d
d-->e
e-->f
f-->g
g-->
```
# Wrap
| Parameter | Description |Type | Required | Values|
| --- | --- | --- | --- | --- |
| wrap | a callable text-wrap function| Directive| Optional | %%{wrap}%%|
```note
Wrap is a function that is currently only deployable for sequence diagrams.
wrap respects manually added <br\> so if the user wants to break up their text, they have full control over those breaks by adding their own <br\> tags.
It is a non-argument directive and can be executed thusly:
`%%{wrap}%%` .
```
**an example of text wrapping in a sequence diagram**:
![Image showing wrapped text](../assets/img/wrapped%20text.png)
# Resetting Configurations:
There are two more functions in the mermaidAPI that can be called by site owners: **reset** and **globalReset**.
**reset**: resets the configuration to whatever the last configuration was. This can be done to undo more recent changes to the last mermaidAPI.initialize({...}) configuration.
**globalReset** will reset both the current configuration AND the site configuration back to the global defaults.
**Notes**: both reset and globalReset are only available to site owners, as such implementors would have to edit their configs with init.
# Additional Utils to mermaid
**memoize**: simple caching for computationally expensive functions. It reduces the rendering time for computationally intensive diagrams by about 90%.
**assignWithDepth** - this is an improvement on previous functions with config.js and Object.assign. The purpose of this function is to provide a sane mechanism for merging objects, similar to object.assign, but with depth.
Example of **assignWithDepth**:
![Image showing assignWithDepth](../assets/img/assignWithDepth.png)
Example of **object.Assign**:
![Image showing object.assign without depth](../assets/img/object.assign%20without%20depth.png)
**calculateTextDimensions, calculateTextWidth,** and **calculateTextHeight** - for measuring text dimensions, width and height.
**Notes**:For more information on usage, parameters, and return info for these new functions take a look at the jsdocs for them in the utils package.
# New API Requests Introduced in Version 8.6.0
## setSiteConfig
| Function | Description | Type | Values |Parameters|Returns|
| --------- | ------------------- | ------- | ------------------ | ------------------ | ------------------ |
| setSiteConfig|Sets the siteConfig to desired values | Put Request | Any Values, except ones in secure array|conf|siteConfig|
```note
Sets the siteConfig. The siteConfig is a protected configuration for repeat use. Calls to reset() will reset
the currentConfig to siteConfig. Calls to reset(configApi.defaultConfig) will reset siteConfig and currentConfig
to the defaultConfig
Note: currentConfig is set in this function
Default value: At default, will mirror Global Config
```
## getSiteConfig
| Function | Description | Type | Values |
| --------- | ------------------- | ------- | ------------------ |
| setSiteConfig|Returns the current siteConfig base configuration | Get Request | Returns Any Values in siteConfig|
```note
Returns any values in siteConfig.
```
## setConfig
| Function | Description | Type | Values |Parameters|Returns|
| --------- | ------------------- | ------- | ------------------ |----------|-------|
| setSiteConfig|Sets the siteConfig to desired values | Put Request| Any Values, those in secure array|conf|currentConfig merged with the sanitized conf|
```note
Sets the currentConfig. The parameter conf is sanitized based on the siteConfig.secure keys. Any
values found in conf with key found in siteConfig.secure will be replaced with the corresponding
siteConfig value.
```
## getConfig
| Function | Description | Type | Return Values |
| --------- | ------------------- | ------- | ------------------ |
| getConfig |Obtains the currentConfig | Get Request | Any Values from currentConfig|
```note
Returns any values in currentConfig.
```
## sanitize
| Function | Description | Type | Values |
| --------- | ------------------- | ------- | ------------------ |
| sanitize |Sets the siteConfig to desired values. | Put Request(?) |None|
```note
modifies options in-place
Ensures options parameter does not attempt to override siteConfig secure keys.
```
## reset
| Function | Description | Type | Required | Values |Parameter|
| --------- | -------------------| ------- | -------- | ------------------ |---------|
| reset|Resets currentConfig to conf| Put Request | Required | None| conf|
## conf
| Parameter | Description |Type | Required | Values|
| --- | --- | --- | --- | --- |
| conf| base set of values, which currentConfig coul be reset to.| Dictionary | Required | Any Values, with respect to the secure Array|
```note
default: current siteConfig (optional, default `getSiteConfig()`)
```
## For more information, read [Setup](https://mermaid-js.github.io/mermaid/#/Setup).

View File

@@ -0,0 +1,6 @@
---
sort: 2
---
# Getting Started
{% include list.liquid %}

View File

@@ -0,0 +1,206 @@
---
sort: 3
title: Configurations
---
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
## mermaidAPI
This is the api to be used when optionally handling the integration with the web page, instead of using the default integration provided by mermaid.js.
The core of this api is the [**render**][1] function which, given a graph
definition as text, renders the graph/diagram and returns an svg element for the graph.
It is is then up to the user of the API to make use of the svg, either insert it somewhere in the page or do something completely different.
In addition to the render function, a number of behavioral configuration options are available.
## setSiteConfig
## setSiteConfig
| Function | Description | Type | Values |
| ------------- | ------------------------------------- | ----------- | --------------------------------------- |
| setSiteConfig | Sets the siteConfig to desired values | Put Request | Any Values, except ones in secure array |
**Notes:**
Sets the siteConfig. The siteConfig is a protected configuration for repeat use. Calls to reset() will reset
the currentConfig to siteConfig. Calls to reset(configApi.defaultConfig) will reset siteConfig and currentConfig
to the defaultConfig
Note: currentConfig is set in this function
\*Default value: At default, will mirror Global Config\*\*
### Parameters
- `conf` the base currentConfig to use as siteConfig
Returns **any** the siteConfig
## getSiteConfig
## getSiteConfig
| Function | Description | Type | Values |
| ------------- | ------------------------------------------------- | ----------- | --------------------------------- |
| setSiteConfig | Returns the current siteConfig base configuration | Get Request | Returns Any Values in siteConfig |
**Notes**:
Returns **any** values in siteConfig.
Returns **any**
## setConfig
## setConfig
| Function | Description | Type | Values |
| ------------- | ------------------------------------- | ----------- | --------------------------------------- |
| setSiteConfig | Sets the siteConfig to desired values | Put Request | Any Values, except ones in secure array |
**Notes**:
Sets the currentConfig. The parameter conf is sanitized based on the siteConfig.secure keys. Any
values found in conf with key found in siteConfig.secure will be replaced with the corresponding
siteConfig value.
### Parameters
- `conf` the potential currentConfig
Returns **any** the currentConfig merged with the sanitized conf
## getConfig
## getConfig
| Function | Description | Type | Return Values |
| --------- | ------------------------- | ----------- | ----------------------------- |
| getConfig | Obtains the currentConfig | Get Request | Any Values from currentConfig |
**Notes**:
Returns **any** the currentConfig
Returns **any** the currentConfig
## sanitize
## sanitize
| Function | Description | Type | Values |
| -------- | -------------------------------------- | ----------- | ------ |
| sanitize | Sets the siteConfig to desired values. | Put Request | None |
Ensures options parameter does not attempt to override siteConfig secure keys
Note: modifies options in-place
### Parameters
- `options` the potential setConfig parameter
## reset
## reset
| Function | Description | Type | Required | Values |
| -------- | ---------------------------- | ----------- | -------- | ------ |
| reset | Resets currentConfig to conf | Put Request | Required | None |
| Parameter | Description | Type | Required | Values |
| --------- | ------------------------------------------------------------- | ---------- | -------- | -------------------------------------------- |
| conf | base set of values, which currentConfig coul be **reset** to. | Dictionary | Required | Any Values, with respect to the secure Array |
\*Notes :
(default: current siteConfig ) (optional, default `getSiteConfig()`)
### Parameters
- `conf` the base currentConfig to reset to (default: current siteConfig ) (optional, default `getSiteConfig()`)
## render
Function that renders an svg with a graph from a chart definition. Usage example below.
```js
mermaidAPI.initialize({
startOnLoad:true
});
$(function(){
const graphDefinition = 'graph TB\na-->b';
const cb = function(svgGraph){
console.log(svgGraph);
};
mermaidAPI.render('id1',graphDefinition,cb);
});
```
### Parameters
- `id` the id of the element to be rendered
- `_txt` the graph definition
- `cb` callback which is called after rendering is finished with the svg code as inparam.
- `container` selector to element in which a div with the graph temporarily will be inserted. In one is
provided a hidden div will be inserted in the body of the page instead. The element will be removed when rendering is
completed.
## mermaidAPI configuration defaults
```html
<script>
var config = {
theme:'default',
logLevel:'fatal',
securityLevel:'strict',
startOnLoad:true,
arrowMarkerAbsolute:false,
er:{
diagramPadding:20,
layoutDirection:'TB',
minEntityWidth:100,
minEntityHeight:75,
entityPadding:15,
stroke:'gray',
fill:'honeydew',
fontSize:12,
useMaxWidth:true,
},
flowchart:{
diagramPadding:8,
htmlLabels:true,
curve:'linear',
},
sequence:{
diagramMarginX:50,
diagramMarginY:10,
actorMargin:50,
width:150,
height:65,
boxMargin:10,
boxTextMargin:5,
noteMargin:10,
messageMargin:35,
messageAlign:'center',
mirrorActors:true,
bottomMarginAdj:1,
useMaxWidth:true,
rightAngles:false,
showSequenceNumbers:false,
},
gantt:{
titleTopMargin:25,
barHeight:20,
barGap:4,
topPadding:50,
leftPadding:75,
gridLineStartPadding:35,
fontSize:11,
fontFamily:'"Open-Sans", "sans-serif"',
numberSectionStyles:4,
axisFormat:'%Y-%m-%d',
}
};
mermaid.initialize(config);
</script>
```
[1]: Setup.md?id=render

View File

@@ -0,0 +1,7 @@
---
sort: 6
---
# mermaid CLI
mermaid CLI has been moved to [mermaid-cli](https://github.com/mermaid-js/mermaid-cli). Please read its documentation instead.

View File

@@ -0,0 +1,26 @@
---
sort: 7
title: Advanced usage
---
# Advanced n00b mermaid (Coming soon..)
## splitting mermaid code from html
A more condensed html code can be achieved by embedding the mermaid code in its own .js file, which is referenced like so:
```
stuff stuff
</div>
</body>
</html>
```
The actual mermaid file could for example look like this:
```
mermaid content...
```
---
## mermaid configuration options
...

View File

@@ -0,0 +1,246 @@
---
sort: 1
title: Getting started - easier
---
# A basic mermaid User-Guide for Beginners
Creating diagrams and charts using mermaid code is simple.
The code is turned into a diagram in the web page with the use of a mermaid renderer.
The mermaid renderer is a piece of javascript that parses mermaid definitions, when called.
This then renders a diagram based on that code in SVG, alternatively it
Most web browsers, such as Firefox, Chrome and Safari, can render mermaid, Internet Explorer however cannot.
## For beginners, there are four relatively easy ways you can use mermaid:
1. Using the mermaid [live editor](https://mermaid-js.github.io/mermaid-live-editor/). For some popular video tutorials on the live editor go to [Overview](./n00b-overview.md).
2. Using one of the many [mermaid plugins](https://mermaid-js.github.io/mermaid/#/integrations).
3. Hosting mermaid on a webpage, with an absolute link.
4. Downloading mermaid and hosting it on your Web Page.
**Notes**: More in depth information can be found on [Usage](./usage.md).
.
# Following any of these examples, you can get started with creating your own diagrams using mermaid code.
## 1. The mermaid live editor:
A great way to get started with mermaid is to visit [The mermaid live editor](https://mermaidjs.github.io/mermaid-live-editor).
In the `Code` section one can write or edit raw mermaid code, and instantly `Preview` the rendered result on the panel beside it.
**This is a great way to learn how to define a mermaid diagram.**
For some popular video tutorials on the live editor go to [Overview](./n00b-overview.md).
![Flowchart](../assets/img/n00b-liveEditor.png)
**Notes:**
You can also click "Copy Markdown" to copy the markdown code for the diagram, that can then be pasted directly into your documentation.
![Flowchart](../assets/img/liveEditorOptions.png)
The `Mermaid configuration` is for controlling mermaid behaviour. An easy introduction to mermaid configuration is found in the [Advanced usage](n00b-advanced.md) section. A complete configuration reference cataloguing default values is found on the [mermaidAPI](https://mermaid-js.github.io/mermaid/#/Setup) page.
## 2. Using mermaid plugins:
Thanks to the growing popularity of mermaid, many plugins already exist which incorporate a mermaid renderer. An extensive list can be found [here](./integrations.md).
One example in the list is the [Atlassian Confluence mermaid plugin](https://marketplace.atlassian.com/apps/1214124/mermaid-plugin-for-confluence?hosting=server&tab=overview)
When the mermaid plugin is installed on a Confluence server, one can insert a mermaid object into any Confluence page.
### Here is a step by step process for using the mermaid-Confluence plugin:
---
- In a Confluence page, Add Other macros.
![Flowchart](../assets/img/n00b-Confluence1.png)
---
- Search for mermaid.
![Flowchart](../assets/img/n00b-Confluence2.png)
---
- The mermaid object appears. Paste your mermaid code into it.
![Flowchart](../assets/img/n00b-Confluence3.png)
---
- Save the page and the diagram appears.
![Flowchart](../../assets/img/n00b-Confluence4.png)
---
## The following are two ways of hosting mermaid on a webpage.
**This is covered in greater detail in the [Usage section](https://mermaid-js.github.io/mermaid/#/usage)**
## 3. Using the Mermaid API: The quick and dirty way of deploying mermaid
This method can be used with any common web server. Apache, IIS, nginx, node express [...], you pick your favourite.
We do not need to install anything on the server, apart from a program (like Notepad++) that can generate an html file, which is then deployed by a web browser (such as Firefox, Chrome, Safari, but not Internet Explorer).
So if you want to really simplify things when testing this out, don't use a web server at all but just create an HTML file locally and drag it into your browser window. The browser will do the work of rendering the mermaid diagrams according to the descriptions you've given!
### Note that all this is written in the html `<body>` section of the web page.
When writing the html file, we give the web browser three instructions inside the html code:
a. A reference for fetching the online mermaid renderer, which is written in Javascript.
b. The mermaid code for the diagram we want to create.
c. The `mermaid.initialize()` API call to start the rendering process.
## This is what needs to go into the html file (and all of them are important), for the mermaidAPI to render the diagrams:
### a. A reference to the address of the `mermaid.js` or the `mermaid.min.js` file has to be contained in a `<script src>` tag like so:
```
<body>
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
</body>
```
### b. The embedded mermaid diagram definition needs to be contained inside a `<div>` tag that signifies that it is a mermaid diagram:
```
<body>
Here is a mermaid diagram:
<div class="mermaid">
graph TD
A[Client] --> B[Load Balancer]
B --> C[Server01]
B --> D[Server02]
</div>
</body>
```
**Notes**: every mermaid chart/graph/diagram definition, has to have separate `<div>` tags.
### c. The `mermaid.initialize()` API call
`mermaid.initialize()` calls take all the definitions contained in `<div class="mermaid">` tags it can find in the html body and starts to render them one by one. It is called this way:
```
<body>
<script>mermaid.initialize({startOnLoad:true});</script>
</body>
```
**Notes**: It is good practice to keep the `mermaid.initialize()` API call right next the `mermaid.min.js` `script` tag.
`startOnLoad` is a parameter that can optionally be changed to false, this would then prevent mermaid from immediately rendering upon loading.
### If the three steps mentioned are followed you will end up with something like this:
```
<html>
<body>
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
<script>mermaid.initialize({startOnLoad:true});</script>
Here is one mermaid diagram:
<div class="mermaid">
graph TD
A[Client] --> B[Load Balancer]
B --> C[Server1]
B --> D[Server2]
</div>
And here is another:
<div class="mermaid">
graph TD
A[Client] -->|tcp_123| B(Load Balancer)
B -->|tcp_456| C[Server1]
B -->|tcp_456| D[Server2]
</div>
</body>
</html>
```
**Notes**: This has to be saved in an `HTML` file and opened with a browser.
---
## 4. Calling mermaid from a relative link.
This method is similar to 3, if only a little more involved. The difference may be very subtle even, but it offers its own advantages, mainly in speed.
1. install node v10 or 12, which would have npm
2. download yarn using npm by entering the command below:
npm install -g yarn
3. After yarn installs, enter the following command:
yarn add mermaid
4. After downloading mermaid, you can then open the mermaid file youve downloaded and go to the `dist` folder.
5. Find the `mermaid.min.js` file,
a. select the file.
b. press the shift key and right click on it
c. select copy as path from the options.
6. Paste it within the `script` tag as the `src`.
```
<script src="Paste the mermaid.min.js file address here"></script>
<script>mermaid.initialize({startOnLoad:true});</script>
```
7. It should look something like this
```
<script src="C:\Users\myPC\mermaid\dist\mermaid.js"></script>
<script>mermaid.initialize({startOnLoad:true});</script>
```
8. Add the graph and diagram definitions as you would in number 3.
a. be mindful of the `div` tags.
9. Save, load/edit your HTML file to your liking.
**Note** placing the HTML file on the same folder the `mermaid` file you've downloaded is a good practice and allows you to shorten the address on the `src` section.
**As seen here, in this full example:**
```
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div class="mermaid">
graph LR
A --- B
B-->C[fa:fa-ban forbidden]
B-->D(fa:fa-spinner);
</div>
<div class="mermaid">
graph TD
A[Client] --> B[Load Balancer]
B --> C[Server1]
B --> D[Server2]
</div>
<script src="C:\Users\MyPC\mermaid\dist\mermaid.js"></script>
<script>mermaid.initialize({startOnLoad:true});</script>
</body>
</html>
```
**Three additional comments from Knut Sveidqvist, creator of mermaid:**
- In early versions of mermaid, the `<script src>` tag was invoked in the `<head>` part of the web page. Nowdays we can place it directly in `<body>` as seen above. However, older parts of the documentation frequently reflects the previous way which still works.
- We initialize the mermaid rendering with `mermaid.initialize()` directly in the html code. In principle this could be done through placing `mermaid.initialize()` inside of `mermaid.min.js`. We would then eliminate the need for this explicit line in the html. However, there are use cases where we do want to separate the two steps. Sometimes we want full control over when we start looking for `<div>`tags inside the web page with `mermaid.initialize()`, for example when we think that all `<div>` tags may not have been loaded by the time `mermaid.min.js` runs.
- In the third method, `mermaid.min.js` is called using an absolute path. Even worse, the example includes the mermaid version number which of course will change as time goes by. However, the example makes it easy to understand what is going on - even though it is perhaps doomed in a way we do not want in a production environment. When going from testing mermaid out to getting serious with it, I would suggest one of the following approaches for calling `mermaid.min.js`:
1. If you do not enter a specific version, you automatically get the latest one.
2. If you really need a specific version, hard code it (this is rare but it happens).
3. If you need to know the current mermaid version, replace a mermaid code block with the word `info` and the version will be returned like [this](https://mermaid-js.github.io/mermaid-live-editor/#/edit/eyJjb2RlIjoiaW5mb1xuXG4iLCJtZXJtYWlkIjp7InRoZW1lIjoiZGVmYXVsdCJ9fQ==)

View File

@@ -0,0 +1,637 @@
---
sort: 5
title: Theming
---
# Version 8.7.0: Theme Configuration
With Version 8.7.0 Mermaid comes out with a system for dynamic and integrated configuration of the diagram themes. The objective of this is to increase the customizability of mermaid and the ease of Styling, with the customization of themes through the `%%init%%` directive and `initialize` calls.
Themes follow and build upon the Levels of Configuration and employ `directives` to modify and create custom configurations, as they were introduced in Version [8.6.0](./8.6.0_docs.md).
**These Theming Configurations, similar to directives, will also be made applicable in the Live-Editor, to maximize customizability.
## Site-wide Themes
Site-wide themes are still declared via `initialize` by site owners.
Example of `Initalize` call setting `theme` to `base`:
```
mermaidAPI.initialize({
'securityLevel': 'loose', 'theme': 'base'
});
```
**Notes**: Only site owners can use the `mermaidAPI.initialize` call, to set values. Site-Users will have to use `%%init%%` to modify or create the theme for their diagrams.
## Themes at the Local or Current Level
When Generating a diagram using on a webpage that supports mermaid. It is also possible to override site-wide theme settings locally, for a specific diagram, using directives, as long as it is not prohibited by the `secure` array.
```
%%{init: {'theme':'base'}}%%
graph TD
a --> b
```
Here is an example of how `%%init%%` can set the theme to 'base', this assumes that `themeVariables` are set to default:
```mermaid
%%{init: {'theme':'base'}}%%
graph TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
B --> G[/Another/]
C ==>|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]
subgraph section
C
D
E
F
G
end
```
# Making a Custom Theme with `themeVariables`
The easiest way to make a custom theme is to start with the base theme, and just modify theme variables through `themeVariables`, via `%%init%%`.
| Parameter | Description | Type | Required | Objects contained |
| -------------- | ------------------------------------------------------------------ | ----- | -------- | ---------------------------------- |
| themeVariables | Array containing objects, modifiable with the `%%init%%` directive | Array | Required | primaryColor, lineColor, textColor |
## Here is an example of overriding `primaryColor` through `themeVariables` and giving everything a different look, using `%%init%%`.
```
%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#ff0000'}}}%%
graph TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
B --> G[/Another/]
C ==>|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]
subgraph section
C
D
E
F
G
end
```
```mermaid
%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#00ff00'}}}%%
graph TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
B --> G[/Another/]
C ==>|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]
subgraph section
C
D
E
F
G
end
```
**Notes:
Leaving it empty will set all variable values to default.
## Color and Color Calculation:
Color definitions have certain interactions in mermaid, this is in order to ensure visibility for diagrams. mermaid will adjust some variables automatically, when colors are changed in order to compensate and maintain readability.
**The Default Value Column** to the right of the Variable coloumn will denote the Variable paired/associated with the Variable on the left and the nature of this pairing or association. If it for instance says primaryColor it means that it gets primaryColor as default value. If it says "based on primaryColor" it means that it is calculated/ derived from primaryColor. This calculation can be primary color inversion, a change of hue, darkening or lightening by 10%, etc.
You can create your own themes, by changing any of the given variables below. If you are using a dark background, set dark mode to true to adjust the colors. It is possible to override the calculations using the variable names below, with `%%init%%` if you wish to style it differently.
## Theme Variables Reference Table
```note
Variables that are unique to some diagrams can be affected by changes in Theme Variables
```
| Variable | Default/Base/Factor value | Calc | Description |
| -------------------- | ------------------------------ | ---- | -------------------------------------------------------------------------------------------------------------------------------- |
| darkMode | false | | Boolean Value that dictates how to calculate colors. "true" will activate darkmode. |
| background | #f4f4f4 | | Used to calculate color for items that should either be background colored or contrasting to the background. |
| primaryColor | #fff4dd | | Color to be used as background in nodes, other colors will be derived from this |
| fontFamily | "trebuchet ms", verdana, arial | | |
| fontSize | 16px | | Font Size, in pixels |
| secondaryColor | based on primaryColor | * | |
| tertiaryColor | based on primaryColor | * | |
| primaryBorderColor | based on primaryColor | * | Color to be used as border in nodes using primaryColor |
| primaryTextColor | based on darkMode #ddd/#333 | * | Color to be used as text color in nodesusing primaryColor |
| secondaryBorderColor | based on secondaryColor | * | Color to be used as border in nodes using secondaryColor |
| secondaryTextColor | based on secondaryColor | * | Color to be used as text color in nodesusing secondaryColor |
| tertiaryBorderColor | based on tertiaryColor | * | Color to be used as border in nodes using tertiaryColor |
| tertiaryTextColor | based on tertiaryColor | * | Color to be used as text color in nodesusing tertiaryColor |
| noteBkgColor | #fff5ad | | Color used as background in notes |
| noteTextColor | #333 | | Text color in note rectangless. |
| noteBorderColor | based on noteBkgColor | * | Border color in note rectangless. |
| lineColor | based on background | * | |
| textColor | based on primaryTextColor | * | Text in diagram over the background for instance text on labels and on signals in sequence diagram or the title in gantt diagram |
| mainBkg | based on primaryColor | * | Background in flowchart objects like rects/circles, class diagram classes, sequence diagram etc |
| errorBkgColor | tertiaryColor | * | Color for syntax error message |
| errorTextColor | tertiaryTextColor | * | Color for syntax error message |
# What follows are Variables, specific to different diagrams and charts.
## Some Theme Variables serve as, or affect the Default Values for Specific Diagram Variables, unless changed using `%%init%%` .
## Flowchart
| Variable | Default/ Associated Value | Calc | Description |
| -------------------- | ------------------------------ | ---- | -------------------------------------------------------------------------------------------------------------------------------- |
| nodeBorder | primaryBorderColor | * | Node Border Color |
| clusterBkg | tertiaryColor | * | Background in subgraphs |
| clusterBorder | tertiaryBorderColor | * | Cluster Border Color |
| defaultLinkColor | lineColor | * | Link Color |
| titleColor | tertiaryTextColor | * | Title Color |
| edgeLabelBackground | based on secondaryColor | * | |
| nodeTextColor | primaryTextColor | * | Color for text inside Nodes. |
# sequence diagram
| name | Default value | Calc | Description |
| --------------------- | ----------------------- | ---- | ----------- |
| actorBorder | primaryBorderColor | * | Actor Border Color |
| actorBkg | mainBkg | * | Actor Background Color |
| actorTextColor | primaryTextColor | * | Actor Text Color |
| actorLineColor | grey | * | Actor Line Color |
| labelBoxBkgColor | actorBkg | * | Label Box Background Color |
| signalColor | textColor | * | Signal Color |
| signalTextColor | textColor | * | Signal Text Color |
| labelBoxBorderColor | actorBorder | * | Label Box Border Color |
| labelTextColor | actorTextColor | * | Label Text Color |
| loopTextColor | actorTextColor | * | Loop ext Color |
| activationBorderColor | based on secondaryColor | * | Activation Border Color |
| activationBkgColor | secondaryColor | * | Activation Background Color |
| sequenceNumberColor | based on lineColor | * | Sequence Number Color |
# state colors
| name | Default value | Calc | Description |
| ------------- | ---------------- | ---- | ------------------------------------------- |
| labelColor | primaryTextColor | * | |
| altBackground | tertiaryColor | * | Used for background in deep composite states |
# class colors
| name | Default value | Calc | Description |
| --------- | ------------- | ---- | ---------------------- |
| classText | textColor | * | Color of Text in class diagrams |
# User journey colors
| name | Default value | Calc | Description |
| --------- | ------------------------ | ---- | --------------------------------------- |
| fillType0 | primaryColor | * | Fill for 1st section in journey diagram |
| fillType1 | secondaryColor | * | Fill for 2nd section in journey diagram |
| fillType2 | based on primaryColor | * | Fill for 3rd section in journey diagram |
| fillType3 | based on secondaryColor | * | Fill for 4th section in journey diagram |
| fillType4 | based on primaryColor | * | Fill for 5th section in journey diagram |
| fillType5 | based on secondaryColor | * | Fill for 6th section in journey diagram |
| fillType6 | based on primaryColor | * | Fill for 7th section in journey diagram |
| fillType7 | based on secondaryColor | * | Fill for 8th section in journey diagram |
**Notes: Values are meant to create an alternating look.
# Here is an example of overriding `primaryColor` and giving everything a different look, using `%%init%%`.
```
%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#ff0000'}}}%%
graph TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
B --> G[/Another/]
C ==>|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]
subgraph section
C
D
E
F
G
end
```
```mermaid
%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#ff0000'}}}%%
graph TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
B --> G[/Another/]
C ==>|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]
subgraph section
C
D
E
F
G
end
```
**This got a bit too dark and bit too colorful. With some easy steps this can be fixed:
* Make the primary color a little lighter
* set the teriary color to a redish shade as well
* make the edge label background differ from the subgraph by setting the edgeLabelBackground
```
%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#ffcccc', 'edgeLabelBackground':'#ffffee', 'tertiaryColor': '#fff0f0'}}}%%
graph TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
B --> G[/Another/]
C ==>|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]
subgraph section
C
D
E
F
G
end
```
```mermaid
%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#ffcccc', 'edgeLabelBackground':'#ffffee', 'tertiaryColor': '#fff0f0'}}}%%
graph TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
B --> G[/Another/]
C ==>|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]
subgraph section
C
D
E
F
G
end
```
The Theming Engine does not admit color codes and will only accept proper color values. Color Names is not supported so for instance, the color value 'red' will not work, but '#ff0000' will work.
# Common theming activities
## How to change the color of the arrows
# Examples:
When adjusting a theme it might be helpful to look at how your preferred theme goes with the diagrams, to evaluate whether everything is visible and looks good.
In the following examples, the directive `init` is used, with the `theme` being declared as `base`. For more information on using directives, read the documentation for [Version 8.6.0](/8.6.0_docs.md)
### Flowchart
```
%%{init: {'securityLevel': 'loose', 'theme':'base'}}%%
graph TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
B --> G[/Another/]
C ==>|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]
subgraph section
C
D
E
F
G
end
```
```mermaid
%%{init: {'securityLevel': 'loose', 'theme':'base'}}%%
graph TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
B --> G[/Another/]
C ==>|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]
subgraph section
C
D
E
F
G
end
```
### Flowchart (beta)
```
mermaid
%%{init: {'securityLevel': 'loose', 'theme':'base'}}%%
flowchart TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
B --> G[Another]
C ==>|One| D[Laptop]
C x--x|Two| E[iPhone]
C o--o|Three| F[fa:fa-car Car]
subgraph section
C
D
E
F
G
end
```
### Sequence diagram
```mermaid
%%{init: {'securityLevel': 'loose', 'theme':'base'}}%%
sequenceDiagram
autonumber
par Action 1
Alice->>John: Hello John, how are you?
and Action 2
Alice->>Bob: Hello Bob, how are you?
end
Alice->>+John: Hello John, how are you?
Alice->>+John: John, can you hear me?
John-->>-Alice: Hi Alice, I can hear you!
Note right of John: John is perceptive
John-->>-Alice: I feel great!
loop Every minute
John-->Alice: Great!
end
```
### class diagram
```mermaid
%%{init: {'securityLevel': 'loose', 'theme':'base'}}%%
classDiagram
Animal "1" <|-- Duck
Animal <|-- Fish
Animal <--o Zebra
Animal : +int age
Animal : +String gender
Animal: +isMammal()
Animal: +mate()
class Duck{
+String beakColor
+swim()
+quack()
}
class Fish{
-int sizeInFeet
-canEat()
}
class Zebra{
+bool is_wild
+run()
}
```
### Gantt
```
gantt
dateFormat :YYYY-MM-DD
title Adding GANTT diagram functionality to mermaid
excludes :excludes the named dates/days from being included in a charted task..
section A section
Completed task :done, des1, 2014-01-06,2014-01-08
Active task :active, des2, 2014-01-09, 3d
Future task : des3, after des2, 5d
Future task2 : des4, after des3, 5d
section Critical tasks
Completed task in the critical line :crit, done, 2014-01-06,24h
Implement parser and jison :crit, done, after des1, 2d
Create tests for parser :crit, active, 3d
Future task in critical line :crit, 5d
Create tests for renderer :2d
Add to mermaid :1d
section Documentation
Describe gantt syntax :active, a1, after des1, 3d
Add gantt diagram to demo page :after a1 , 20h
Add another diagram to demo page :doc1, after a1 , 48h
section Last section
Describe gantt syntax :after doc1, 3d
Add gantt diagram to demo page :20h
Add another diagram to demo page :48h
```
```mermaid
gantt
dateFormat :YYYY-MM-DD
title Adding GANTT diagram functionality to mermaid
excludes :excludes the named dates/days from being included in a charted task..
section A section
Completed task :done, des1, 2014-01-06,2014-01-08
Active task :active, des2, 2014-01-09, 3d
Future task : des3, after des2, 5d
Future task2 : des4, after des3, 5d
section Critical tasks
Completed task in the critical line :crit, done, 2014-01-06,24h
Implement parser and jison :crit, done, after des1, 2d
Create tests for parser :crit, active, 3d
Future task in critical line :crit, 5d
Create tests for renderer :2d
Add to mermaid :1d
section Documentation
Describe gantt syntax :active, a1, after des1, 3d
Add gantt diagram to demo page :after a1 , 20h
Add another diagram to demo page :doc1, after a1 , 48h
section Last section
Describe gantt syntax :after doc1, 3d
Add gantt diagram to demo page :20h
Add another diagram to demo page :48h
```
### State diagram
```
mermaid
%%{init: {'securityLevel': 'loose', 'theme':'base'}}%%
stateDiagram
[*] --> Active
state Active {
[*] --> NumLockOff
NumLockOff --> NumLockOn : EvNumLockPressed
NumLockOn --> NumLockOff : EvNumLockPressed
--
[*] --> CapsLockOff
CapsLockOff --> CapsLockOn : EvCapsLockPressed
CapsLockOn --> CapsLockOff : EvCapsLockPressed
--
[*] --> ScrollLockOff
ScrollLockOff --> ScrollLockOn : EvCapsLockPressed
ScrollLockOn --> ScrollLockOff : EvCapsLockPressed
}
state SomethingElse {
A --> B
B --> A
}
Active --> SomethingElse
note right of SomethingElse : This is the note to the right.
SomethingElse --> [*]
```
```mermaid
%%{init: {'securityLevel': 'loose', 'theme':'base'}}%%
stateDiagram
[*] --> Active
state Active {
[*] --> NumLockOff
NumLockOff --> NumLockOn : EvNumLockPressed
NumLockOn --> NumLockOff : EvNumLockPressed
--
[*] --> CapsLockOff
CapsLockOff --> CapsLockOn : EvCapsLockPressed
CapsLockOn --> CapsLockOff : EvCapsLockPressed
--
[*] --> ScrollLockOff
ScrollLockOff --> ScrollLockOn : EvCapsLockPressed
ScrollLockOn --> ScrollLockOff : EvCapsLockPressed
}
state SomethingElse {
A --> B
B --> A
}
Active --> SomethingElse
note right of SomethingElse : This is the note to the right.
SomethingElse --> [*]
```
### State diagram (beta)
```
%%{init: {'securityLevel': 'loose', 'theme':'base'}}%%
stateDiagram-v2
[*] --> Active
state Active {
[*] --> NumLockOff
NumLockOff --> NumLockOn : EvNumLockPressed
NumLockOn --> NumLockOff : EvNumLockPressed
--
[*] --> CapsLockOff
CapsLockOff --> CapsLockOn : EvCapsLockPressed
CapsLockOn --> CapsLockOff : EvCapsLockPressed
--
[*] --> ScrollLockOff
ScrollLockOff --> ScrollLockOn : EvCapsLockPressed
ScrollLockOn --> ScrollLockOff : EvCapsLockPressed
}
state SomethingElse {
A --> B
B --> A
}
Active --> SomethingElse2
note right of SomethingElse2 : This is the note to the right.
SomethingElse2 --> [*]
```
```mermaid
%%{init: {'securityLevel': 'loose', 'theme':'base'}}%%
stateDiagram-v2
[*] --> Active
state Active {
[*] --> NumLockOff
NumLockOff --> NumLockOn : EvNumLockPressed
NumLockOn --> NumLockOff : EvNumLockPressed
--
[*] --> CapsLockOff
CapsLockOff --> CapsLockOn : EvCapsLockPressed
CapsLockOn --> CapsLockOff : EvCapsLockPressed
--
[*] --> ScrollLockOff
ScrollLockOff --> ScrollLockOn : EvCapsLockPressed
ScrollLockOn --> ScrollLockOff : EvCapsLockPressed
}
state SomethingElse {
A --> B
B --> A
}
Active --> SomethingElse2
note right of SomethingElse2 : This is the note to the right.
SomethingElse2 --> [*]
```
### Entity Relations diagram
```
erDiagram
CUSTOMER }|..|{ DELIVERY-ADDRESS : has
CUSTOMER ||--o{ ORDER : places
CUSTOMER ||--o{ INVOICE : "liable for"
DELIVERY-ADDRESS ||--o{ ORDER : receives
INVOICE ||--|{ ORDER : covers
ORDER ||--|{ ORDER-ITEM : includes
PRODUCT-CATEGORY ||--|{ PRODUCT : contains
PRODUCT ||--o{ ORDER-ITEM : "ordered in"
```
```mermaid
erDiagram
CUSTOMER }|..|{ DELIVERY-ADDRESS : has
CUSTOMER ||--o{ ORDER : places
CUSTOMER ||--o{ INVOICE : "liable for"
DELIVERY-ADDRESS ||--o{ ORDER : receives
INVOICE ||--|{ ORDER : covers
ORDER ||--|{ ORDER-ITEM : includes
PRODUCT-CATEGORY ||--|{ PRODUCT : contains
PRODUCT ||--o{ ORDER-ITEM : "ordered in"
```
### User journey diagram
```
journey
title My working day
section Go to work
Make tea: 5: Me
Go upstairs: 3: Me
Do work: 1: Me, Cat
section Go home
Go downstairs: 5: Me
Sit down: 5: Me
```
```mermaid
journey
title My working day
section Go to work
Make tea: 5: Me
Go upstairs: 3: Me
Do work: 1: Me, Cat
section Go home
Go downstairs: 5: Me
Sit down: 5: Me
```

View File

@@ -0,0 +1,412 @@
---
sort: 2
title: API-Usage
---
# Usage
mermaid is a javascript tool that makes use of a markdown based syntax to render customizable diagrams and charts, for greater speed and ease.
mermaid was made to help Documentation catch up with Development, in quickly changing projects.
### CDN
[https://unpkg.com/mermaid/](https://unpkg.com/mermaid/)
Please note that you can switch versions through the dropdown box at the top right.
## Using mermaid
For the majority of beginners, using the live editor or suppoting mermaid on a webpage would cover their uses for mermaid.
## Installing and Hosting mermaid on a webpage
### Using the npm package
```
1.You will need to insall node v10 or 12, which would have npm.
2. download yarn using npm.
3. enter the following command:
yarn add mermaid
4. At this point, you can add mermaid as a dev dependency using this command:
yarn add --dev mermaid
5. Alternatively, you can also deploy mermaid using the script tag in an HTML file with mermaid diagram descriptions.
as is shown in the example below
```
## Hosting mermaid on a web page.
```note
This topic explored in greater depth in the [User Guide for Beginners](./n00b-gettingStarted.md)
```
The easiest way to integrate mermaid on a web page requires three elements:
1. Inclusion of the mermaid address in the html page using a `script` tag, in the `src` section.Example:
`<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>`
2. The `mermaidAPI` call, in a separate `script` tag. Example:
`<script>mermaid.initialize({startOnLoad:true});</script>`
3. A graph definition, inside `<div>` tags labeled `class=mermaid`. Example:
```html
<div class="mermaid">
graph LR
A --- B
B-->C[fa:fa-ban forbidden]
B-->D(fa:fa-spinner);
</div>
```
**If these things are in place mermaid starts at the page load event and when fired (when the page has loaded) it will
locate the graph definitions inside the `div` tags with `class="mermaid"` on the page and transform them to svg charts or diagrams.**
## Simple full example:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div class="mermaid">
graph LR
A --- B
B-->C[fa:fa-ban forbidden]
B-->D(fa:fa-spinner);
</div>
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
<script>mermaid.initialize({startOnLoad:true});</script>
</body>
</html>
```
## Notes:
An id attribute is also added to mermaid tags without one.
Mermaid can load multiple diagrams, in the same page.
### Try it out, save this code as HTML and load it using any browser.(Except Internet Explorer, please don't use Internet Explorer.)
## To enable click event and tags in nodes
A `securityLevel` configuration has to first be cleared, `securityLevel` sets the level of trust for the parsed diagrams and limits click functionality. This was introduce in version 8.2 as a security improvement, aimed at preventing malicious use.
**It is the site owner's responsibility to discriminate between trustworthy and untrustworthy user-bases and we encourage the use of discretion.**
## securityLevel
| Parameter | Description | Type | Required | Values |
| ------------- | --------------------------------- | ------ | -------- | ------------------------- |
| securitylevel | Level of trust for parsed diagram | String | Required | Strict, Loose, antiscript |
\*\*Notes:
- **strict**: (**default**) tags in text are encoded, click functionality is disabeled
- **loose**: tags in text are allowed, click functionality is enabled
- **antiscript**: html tags in text are allowed, (only script element is removed), click functionality is enabled
```note
This changes the default behaviour of mermaid so that after upgrade to 8.2, if the `securityLevel` is not configured, tags in flowcharts are encoded as tags and clicking is prohibited.
```
**If you are taking resposibility for the diagram source security you can set the `securityLevel` to a value of your choosing . By doing this clicks and tags are allowed.**
## To chage `securityLevel` with `mermaidAPI.initialize`:
```javascript
mermaidAPI.initialize({
securityLevel: 'loose'
});
```
### Labels out of bounds
If you use dynamically loaded fonts that are loaded through CSS, such as Google fonts, mermaid should wait for the
whole page to load (dom + assets, particularly the fonts file).
```javascript
$(document).load(function() {
mermaid.initialize();
});
```
or
```javascript
$(document).ready(function() {
mermaid.initialize();
});
```
Not doing so will most likely result in mermaid rendering graphs that have labels out of bounds. The default integration in mermaid uses the window.load event to start rendering.
If your page has other fonts in its body those might be used instead of the mermaid font. Specifying the font in your styling is a workaround for this.
```
div.mermaid {
font-family: 'trebuchet ms', verdana, arial;
}
```
# This likely requires a `script.js` file, separate from the `HTML`.
### Calling `mermaid.init`
By default, `mermaid.init` will be called when the document is ready, finding all elements with
`class="mermaid"`. If you are adding content after mermaid is loaded, or otherwise need
finer-grained control of this behavior, you can call `init` yourself with:
- a configuration object
- some nodes, as
- a node
- an array-like of nodes
- or W3C selector that will find your nodes
Example:
```javascript
mermaid.init({noteMargin: 10}, ".someOtherClass");
```
Or with no config object, and a jQuery selection:
```javascript
mermaid.init(undefined, $("#someId .yetAnotherClass"));
```
```warning
This type of integration is deprecated. Instead the preferred way of handling more complex integration is to use the mermaidAPI instead.
```
## Usage with webpack
mermaid fully supports webpack. Here is a [working demo](https://github.com/mermaidjs/mermaid-webpack-demo).
## API usage
The main idea of the API is to be able to call a render function with the graph defintion as a string. The render function
will render the graph and call a callback with the resulting svg code. With this approach it is up to the site creator to
fetch the graph definition from the site (perhaps from a textarea), render it and place the graph somewhere in the site.
The example below show an outline of how this could be used. The example just logs the resulting svg to the javascript console.
```html
<script src="mermaid.js"></script>
<script>
mermaid.mermaidAPI.initialize({
startOnLoad:false
});
$(function(){
// Example of using the API
var element = document.querySelector("#graphDiv");
var insertSvg = function(svgCode, bindFunctions){
element.innerHTML = svgCode;
};
var graphDefinition = 'graph TB\na-->b';
var graph = mermaid.mermaidAPI.render('graphDiv', graphDefinition, insertSvg);
});
</script>
```
### Binding events
Sometimes the generated graph also has defined interactions like tooltip and click events. When using the API one must
add those events after the graph has been inserted into the DOM.
The example code below is an extract of what mermaid does when using the API. The example shows how it is possible to
bind events to an svg when using the API for rendering.
```javascript
var insertSvg = function(svgCode, bindFunctions) {
element.innerHTML = svgCode;
if(typeof callback !== 'undefined'){
callback(id);
}
bindFunctions(element);
};
var id = 'theGraph';
mermaidAPI.render(id,txt,insertSvg, element);
```
1. The graph is generated using the render call.
2. After generation the render function calls the provided callback function, in this case it's called insertSvg.
3. The callback function is called with two parameters, the svg code of the generated graph and a function. This function binds events to the svg **after** it is inserted into the DOM.
4. Insert the svg code into the DOM for presentation.
5. Call the binding function that binds the events.
## Example of a marked renderer
This is the renderer used for transforming the documentation from markdown to html with mermaid diagrams in the html.
```javascript
var renderer = new marked.Renderer();
renderer.code = function (code, language) {
if(code.match(/^sequenceDiagram/)||code.match(/^graph/)){
return '<div class="mermaid">'+code+'</div>';
}
else{
return '<pre><code>'+code+'</code></pre>';
}
};
```
Another example in coffeescript that also includes the mermaid script tag in the generated markup.
```js
marked = require 'marked'
module.exports = (options) ->
hasMermaid = false
renderer = new marked.Renderer()
renderer.defaultCode = renderer.code
renderer.code = (code, language) ->
if language is 'mermaid'
html = ''
if not hasMermaid
hasMermaid = true
html += '<script src="'+options.mermaidPath+'"></script>'
html + '<div class="mermaid">'+code+'</div>'
else
@defaultCode(code, language)
renderer
```
## Advanced usage
**Error handling**
When the parser encounters invalid syntax the **mermaid.parseError** function is called. It is possible to override this
function in order to handle the error in an application-specific way.
**Parsing text without rendering**
It is also possible to validate the syntax before rendering in order to streamline the user experience. The function
**mermaid.parse(txt)** takes a text string as an argument and returns true if the text is syntactically correct and
false if it is not. The parseError function will be called when the parse function returns false.
The code-example below in meta code illustrates how this could work:
```javascript
mermaid.parseError = function(err,hash){
displayErrorInGui(err);
};
var textFieldUpdated = function(){
var textStr = getTextFromFormField('code');
if(mermaid.parse(textStr)){
reRender(textStr)
}
};
bindEventHandler('change', 'code', textFieldUpdated);
```
## Configuration
Mermaid takes a number of options which lets you tweak the rendering of the diagrams. Currently there are three ways of
setting the options in mermaid.
1. Instantiation of the configuration using the initialize call
2. *Using the global mermaid object* - deprecated
3. *using the global mermaid_config object* - deprecated
4. Instantiation of the configuration using the **mermaid.init** call
The list above has two ways too many of doing this. Three are deprecated and will eventually be removed. The list of
configuration objects are described [in the mermaidAPI documentation](mermaidAPI.html).
## Using the `mermaidAPI.initialize`/`mermaid.initialize` call
The future proof way of setting the configuration is by using the initialization call to mermaid or mermaidAPI depending
on what kind of integration you use.
```html
<script src="../dist/mermaid.js"></script>
<script>
var config = {
startOnLoad:true,
flowchart:{
useMaxWidth:false,
htmlLabels:true
}
};
mermaid.initialize(config);
</script>
```
```tip
This is the preferred way of configuring mermaid.
```
## Using the mermaid object
Is it possible to set some configuration via the mermaid object. The two parameters that are supported using this
approach are:
* mermaid.startOnLoad
* mermaid.htmlLabels
```js
mermaid.startOnLoad = true;
```
```warning
This way of setting the configuration is deprecated. Instead the preferred way is to use the initialize method. This functionality is only kept for backwards compatibility.
```
## Using the mermaid_config
It is possible to set some configuration via the mermaid object. The two parameters that are supported using this
approach are:
* mermaid_config.startOnLoad
* mermaid_config.htmlLabels
```javascript
mermaid_config.startOnLoad = true;
```
```warning
This way of setting the configuration is deprecated. Instead the preferred way is to use the initialize method. This functionality is only kept for backwards compatibility.
```
## Using the mermaid.init call
#
Is it possible to set some configuration via the mermaid object. The two parameters that are supported using this
approach are:
* mermaid_config.startOnLoad
* mermaid_config.htmlLabels
```
mermaid_config.startOnLoad = true;
```
```warning
This way of setting the configuration is deprecated. Instead the preferred way is to use the initialize method. This functionality is only kept for backwards compatibility.
```