collab/mermaid/docs/config/usage.mdblame
View source
6dd74de1> **Warning**
6dd74de2>
6dd74de3> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
6dd74de4>
6dd74de5> ## Please edit the corresponding file in [/packages/mermaid/src/docs/config/usage.md](../../packages/mermaid/src/docs/config/usage.md).
6dd74de6
6dd74de7# Usage
6dd74de8
6dd74de9Mermaid is a JavaScript tool that makes use of a Markdown based syntax to render customizable diagrams, charts and visualizations.
6dd74de10
6dd74de11Diagrams can be re-rendered/modified by modifying their descriptions.
6dd74de12
6dd74de13### CDN
6dd74de14
6dd74de15<https://www.jsdelivr.com/package/npm/mermaid>
6dd74de16
6dd74de17Please note that you can switch versions through the dropdown box at the top right.
6dd74de18
6dd74de19## Using mermaid
6dd74de20
6dd74de21For the majority of users, Using the [Live Editor](https://mermaid.live/) would be sufficient, however you may also opt to deploy mermaid as a dependency or using the [Mermaid API](./setup/README.md).
6dd74de22
6dd74de23We have compiled some Video [Tutorials](../ecosystem/tutorials.md) on how to use the Mermaid Live Editor.
6dd74de24
6dd74de25### Installing and Hosting Mermaid on a Webpage
6dd74de26
6dd74de27**Using the npm package:**
6dd74de28
6dd74de29Requirements:
6dd74de30
6dd74de31- Node >= 16
6dd74de32
6dd74de33```bash
6dd74de34# NPM
6dd74de35npm install mermaid
6dd74de36# Yarn
6dd74de37yarn add mermaid
6dd74de38# PNPM
6dd74de39pnpm add mermaid
6dd74de40```
6dd74de41
6dd74de42**Hosting mermaid on a web page:**
6dd74de43
6dd74de44> Note: This topic is explored in greater depth in the [User Guide for Beginners](../intro/getting-started.md)
6dd74de45
6dd74de46The easiest way to integrate mermaid on a web page requires two elements:
6dd74de47
6dd74de48- A graph definition, inside `<pre>` tags labeled `class=mermaid`.
6dd74de49
6dd74de50Example:
6dd74de51
6dd74de52```html
6dd74de53<pre class="mermaid">
6dd74de54 graph LR
6dd74de55 A --- B
6dd74de56 B-->C[fa:fa-ban forbidden]
6dd74de57 B-->D(fa:fa-spinner);
6dd74de58</pre>
6dd74de59```
6dd74de60
6dd74de61- The mermaid js script. Added using a `script` tag as an ESM import.
6dd74de62
6dd74de63Example:
6dd74de64
6dd74de65```html
6dd74de66<script type="module">
6dd74de67 import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
6dd74de68</script>
6dd74de69```
6dd74de70
6dd74de71**Following these directions, mermaid starts at page load and (when the page has loaded) it will locate the graph definitions inside the `pre` tags with `class="mermaid"` and return diagrams in SVG form, following given definitions.**
6dd74de72
6dd74de73## Simple full example:
6dd74de74
6dd74de75```html
6dd74de76<!doctype html>
6dd74de77<html lang="en">
6dd74de78 <body>
6dd74de79 <pre class="mermaid">
6dd74de80 graph LR
6dd74de81 A --- B
6dd74de82 B-->C[fa:fa-ban forbidden]
6dd74de83 B-->D(fa:fa-spinner);
6dd74de84 </pre>
6dd74de85 <script type="module">
6dd74de86 import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
6dd74de87 </script>
6dd74de88 </body>
6dd74de89</html>
6dd74de90```
6dd74de91
6dd74de92## Notes:
6dd74de93
6dd74de94An id attribute is also added to mermaid tags without one.
6dd74de95
6dd74de96Mermaid can load multiple diagrams, in the same page.
6dd74de97
6dd74de98> Try it out, save this code as HTML and load it using any browser.
6dd74de99> (Except Internet Explorer, please don't use Internet Explorer.)
6dd74de100
6dd74de101## Tiny Mermaid
6dd74de102
6dd74de103We offer a smaller version of Mermaid that's approximately half the size of the full library. This tiny version doesn't support Mindmap Diagrams, Architecture Diagrams, KaTeX rendering, or lazy loading.
6dd74de104
6dd74de105If you need a more lightweight version without these features, you can use [Mermaid Tiny](https://github.com/mermaid-js/mermaid/tree/develop/packages/tiny).
6dd74de106
6dd74de107## Enabling Click Event and Tags in Nodes
6dd74de108
6dd74de109A `securityLevel` configuration has to first be cleared. `securityLevel` sets the level of trust for the parsed diagrams and limits click functionality. This was introduced in version 8.2 as a security improvement, aimed at preventing malicious use.
6dd74de110
6dd74de111**It is the site owner's responsibility to discriminate between trustworthy and untrustworthy user-bases and we encourage the use of discretion.**
6dd74de112
6dd74de113## securityLevel
6dd74de114
6dd74de115| Parameter | Description | Type | Required | Values |
6dd74de116| ------------- | --------------------------------- | ------ | -------- | ------------------------------------------ |
6dd74de117| securityLevel | Level of trust for parsed diagram | String | Optional | 'sandbox', 'strict', 'loose', 'antiscript' |
6dd74de118
6dd74de119Values:
6dd74de120
6dd74de121- **strict**: (**default**) HTML tags in the text are encoded and click functionality is disabled.
6dd74de122- **antiscript**: HTML tags in text are allowed (only script elements are removed) and click functionality is enabled.
6dd74de123- **loose**: HTML tags in text are allowed and click functionality is enabled.
6dd74de124- **sandbox**: With this security level, all rendering takes place in a sandboxed iframe. This prevents any JavaScript from running in the context. This may hinder interactive functionality of the diagram, like scripts, popups in the sequence diagram, links to other tabs or targets, etc.
6dd74de125
6dd74de126> **Note**
6dd74de127> This changes the default behaviour of mermaid so that after upgrade to 8.2, unless the `securityLevel` is not changed, tags in flowcharts are encoded as tags and clicking is disabled.
6dd74de128> **sandbox** security level is still in the beta version.
6dd74de129
6dd74de130**If you are taking responsibility for the diagram source security you can set the `securityLevel` to a value of your choosing. This allows clicks and tags are allowed.**
6dd74de131
6dd74de132**To change `securityLevel`, you have to call `mermaid.initialize`:**
6dd74de133
6dd74de134```javascript
6dd74de135mermaid.initialize({
6dd74de136 securityLevel: 'loose',
6dd74de137});
6dd74de138```
6dd74de139
6dd74de140### Labels out of bounds
6dd74de141
6dd74de142If you use dynamically loaded fonts that are loaded through CSS, such as fonts, mermaid should wait for the whole page to load (dom + assets, particularly the fonts file).
6dd74de143
6dd74de144```javascript
6dd74de145$(document).ready(function () {
6dd74de146 mermaid.initialize();
6dd74de147});
6dd74de148```
6dd74de149
6dd74de150Not 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.
6dd74de151
6dd74de152If 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.
6dd74de153
6dd74de154```css
6dd74de155pre.mermaid {
6dd74de156 font-family: 'trebuchet ms', verdana, arial;
6dd74de157}
6dd74de158```
6dd74de159
6dd74de160### Using `mermaid.run`
6dd74de161
6dd74de162mermaid.run was added in v10 and is the preferred way of handling more complex integration.
6dd74de163By default, `mermaid.run` will be called when the document is ready, rendering all elements with `class="mermaid"`.
6dd74de164
6dd74de165You can customize that behavior by calling `await mermaid.run(<config>)`.
6dd74de166
6dd74de167`mermaid.initialize({startOnLoad: false})` will prevent `mermaid.run` from being called automatically after load.
6dd74de168
6dd74de169Render all elements with querySelector ".someOtherClass"
6dd74de170
6dd74de171```js
6dd74de172mermaid.initialize({ startOnLoad: false });
6dd74de173await mermaid.run({
6dd74de174 querySelector: '.someOtherClass',
6dd74de175});
6dd74de176```
6dd74de177
6dd74de178Render all elements passed as an array
6dd74de179
6dd74de180```js
6dd74de181mermaid.initialize({ startOnLoad: false });
6dd74de182await mermaid.run({
6dd74de183 nodes: [document.getElementById('someId'), document.getElementById('anotherId')],
6dd74de184});
6dd74de185await mermaid.run({
6dd74de186 nodes: document.querySelectorAll('.yetAnotherClass'),
6dd74de187});
6dd74de188```
6dd74de189
6dd74de190Render all `.mermaid` elements while suppressing any error
6dd74de191
6dd74de192```js
6dd74de193mermaid.initialize({ startOnLoad: false });
6dd74de194await mermaid.run({
6dd74de195 suppressErrors: true,
6dd74de196});
6dd74de197```
6dd74de198
6dd74de199### Calling `mermaid.init` - Deprecated
6dd74de200
6dd74de201> **Warning**
6dd74de202> mermaid.init is deprecated in v10 and will be removed in a future release. Please use mermaid.run instead.
6dd74de203
6dd74de204By default, `mermaid.init` will be called when the document is ready, finding all elements with
6dd74de205`class="mermaid"`. If you are adding content after mermaid is loaded, or otherwise need
6dd74de206finer-grained control of this behavior, you can call `init` yourself with:
6dd74de207
6dd74de208- a configuration object
6dd74de209- some nodes, as
6dd74de210 - a node
6dd74de211 - an array-like of nodes
6dd74de212 - or W3C selector that will find your nodes
6dd74de213
6dd74de214Example:
6dd74de215
6dd74de216```javascript
6dd74de217mermaid.init({ noteMargin: 10 }, '.someOtherClass');
6dd74de218```
6dd74de219
6dd74de220Or with no config object, and a jQuery selection:
6dd74de221
6dd74de222```javascript
6dd74de223mermaid.init(undefined, $('#someId .yetAnotherClass'));
6dd74de224```
6dd74de225
6dd74de226## Usage with webpack
6dd74de227
6dd74de228mermaid fully supports webpack. Here is a [working demo](https://github.com/mermaidjs/mermaid-webpack-demo).
6dd74de229
6dd74de230## API usage
6dd74de231
6dd74de232The main idea of the API is to be able to call a render function with the graph definition 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.
6dd74de233
6dd74de234The example below shows an example of how this could be used. The example just logs the resulting SVG to the JavaScript console.
6dd74de235
6dd74de236```html
6dd74de237<script type="module">
6dd74de238 import mermaid from './mermaid.esm.mjs';
6dd74de239 mermaid.initialize({ startOnLoad: false });
6dd74de240
6dd74de241 // Example of using the render function
6dd74de242 const drawDiagram = async function () {
6dd74de243 element = document.querySelector('#graphDiv');
6dd74de244 const graphDefinition = 'graph TB\na-->b';
6dd74de245 const { svg } = await mermaid.render('graphDiv', graphDefinition);
6dd74de246 element.innerHTML = svg;
6dd74de247 };
6dd74de248
6dd74de249 await drawDiagram();
6dd74de250</script>
6dd74de251```
6dd74de252
6dd74de253To determine the type of diagram present in a given text, you can utilize the `mermaid.detectType` function, as demonstrated in the example below.
6dd74de254
6dd74de255```html
6dd74de256<script type="module">
6dd74de257 import mermaid from './mermaid.esm.mjs';
6dd74de258 const graphDefinition = `sequenceDiagram
6dd74de259 Pumbaa->>Timon:I ate like a pig.
6dd74de260 Timon->>Pumbaa:Pumbaa, you ARE a pig.`;
6dd74de261 try {
6dd74de262 const type = mermaid.detectType(graphDefinition);
6dd74de263 console.log(type); // 'sequence'
6dd74de264 } catch (error) {
6dd74de265 // UnknownDiagramError
6dd74de266 }
6dd74de267</script>
6dd74de268```
6dd74de269
6dd74de270### Binding events
6dd74de271
6dd74de272Sometimes the generated graph also has defined interactions like tooltip and click events. When using the API one must
6dd74de273add those events after the graph has been inserted into the DOM.
6dd74de274
6dd74de275The example code below is an extract of what mermaid does when using the API. The example shows how it is possible to
6dd74de276bind events to an SVG when using the API for rendering.
6dd74de277
6dd74de278```javascript
6dd74de279// Example of using the bindFunctions
6dd74de280const drawDiagram = async function () {
6dd74de281 element = document.querySelector('#graphDiv');
6dd74de282 const graphDefinition = 'graph TB\na-->b';
6dd74de283 const { svg, bindFunctions } = await mermaid.render('graphDiv', graphDefinition);
6dd74de284 element.innerHTML = svg;
6dd74de285 // This can also be written as `bindFunctions?.(element);` using the `?` shorthand.
6dd74de286 if (bindFunctions) {
6dd74de287 bindFunctions(element);
6dd74de288 }
6dd74de289};
6dd74de290```
6dd74de291
6dd74de2921. The graph is generated using the render call.
6dd74de2932. After generation the render function calls the provided callback function, in this case it's called insertSvg.
6dd74de2943. 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.
6dd74de2954. Insert the SVG code into the DOM for presentation.
6dd74de2965. Call the binding function that binds the events.
6dd74de297
6dd74de298## Example of a marked renderer
6dd74de299
6dd74de300This is the renderer used for transforming the documentation from Markdown to html with mermaid diagrams in the html.
6dd74de301
6dd74de302```javascript
6dd74de303const renderer = new marked.Renderer();
6dd74de304renderer.code = function (code, language) {
6dd74de305 if (code.match(/^sequenceDiagram/) || code.match(/^graph/)) {
6dd74de306 return '<pre class="mermaid">' + code + '</pre>';
6dd74de307 } else {
6dd74de308 return '<pre><code>' + code + '</code></pre>';
6dd74de309 }
6dd74de310};
6dd74de311```
6dd74de312
6dd74de313Another example in CoffeeScript that also includes the mermaid script tag in the generated markup.
6dd74de314
6dd74de315```coffee
6dd74de316marked = require 'marked'
6dd74de317
6dd74de318module.exports = (options) ->
6dd74de319 hasMermaid = false
6dd74de320 renderer = new marked.Renderer()
6dd74de321 renderer.defaultCode = renderer.code
6dd74de322 renderer.code = (code, language) ->
6dd74de323 if language is 'mermaid'
6dd74de324 html = ''
6dd74de325 if not hasMermaid
6dd74de326 hasMermaid = true
6dd74de327 html += '<script src="'+options.mermaidPath+'"></script>'
6dd74de328 html + '<pre class="mermaid">'+code+'</pre>'
6dd74de329 else
6dd74de330 @defaultCode(code, language)
6dd74de331
6dd74de332 renderer
6dd74de333```
6dd74de334
6dd74de335## Advanced usage
6dd74de336
6dd74de337### Syntax validation without rendering
6dd74de338
6dd74de339The `mermaid.parse(text, parseOptions)` function validates graph definitions without rendering a graph.
6dd74de340
6dd74de341The function `mermaid.parse(text, parseOptions)`, takes a text string as an argument and returns `{ diagramType: string }` if the definition follows mermaid's syntax.
6dd74de342
6dd74de343If the definition is invalid, the function returns `false` if `parseOptions.suppressErrors` is set to `true`. Otherwise, it throws an error.
6dd74de344
6dd74de345The parseError function will be called when the parse function throws an error. It will not be called if `parseOptions.suppressErrors` is set to `true`.
6dd74de346
6dd74de347It is possible to override this function in order to handle the error in an application-specific way.
6dd74de348
6dd74de349The code-example below in meta code illustrates how this could work:
6dd74de350
6dd74de351```javascript
6dd74de352mermaid.parseError = function (err, hash) {
6dd74de353 displayErrorInGui(err);
6dd74de354};
6dd74de355
6dd74de356const textFieldUpdated = async function () {
6dd74de357 const textStr = getTextFromFormField('code');
6dd74de358
6dd74de359 if (await mermaid.parse(textStr)) {
6dd74de360 reRender(textStr);
6dd74de361 }
6dd74de362};
6dd74de363
6dd74de364bindEventHandler('change', 'code', textFieldUpdated);
6dd74de365```
6dd74de366
6dd74de367## Configuration
6dd74de368
6dd74de369You can pass the required configuration to the `mermaid.initialize` call. This is the preferred way of configuring mermaid.
6dd74de370The list of configuration objects are described [in the mermaidAPI documentation](./setup/README.md).
6dd74de371
6dd74de372```html
6dd74de373<script type="module">
6dd74de374 import mermaid from './mermaid.esm.mjs';
6dd74de375 let config = { startOnLoad: true, htmlLabels: true, flowchart: { useMaxWidth: false } };
6dd74de376 mermaid.initialize(config);
6dd74de377</script>
6dd74de378```
6dd74de379
6dd74de380> **Note**
6dd74de381> This is the preferred way of configuring mermaid.
6dd74de382
6dd74de383### The following methods are deprecated and are kept only for backwards compatibility.
6dd74de384
6dd74de385## Using the mermaid object
6dd74de386
6dd74de387It is possible to set some configuration via the mermaid object. The two parameters that are supported using this
6dd74de388approach are:
6dd74de389
6dd74de390- mermaid.startOnLoad
6dd74de391- mermaid.htmlLabels
6dd74de392
6dd74de393```javascript
6dd74de394mermaid.startOnLoad = true;
6dd74de395```
6dd74de396
6dd74de397> **Warning**
6dd74de398> 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.
6dd74de399
6dd74de400<!---
6dd74de401cspell:locale en,en-gb
6dd74de402cspell:ignore pumbaa
6dd74de403--->