13.2 KB404 lines
Blame
1> **Warning**
2>
3> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
4>
5> ## Please edit the corresponding file in [/packages/mermaid/src/docs/config/usage.md](../../packages/mermaid/src/docs/config/usage.md).
6
7# Usage
8
9Mermaid is a JavaScript tool that makes use of a Markdown based syntax to render customizable diagrams, charts and visualizations.
10
11Diagrams can be re-rendered/modified by modifying their descriptions.
12
13### CDN
14
15<https://www.jsdelivr.com/package/npm/mermaid>
16
17Please note that you can switch versions through the dropdown box at the top right.
18
19## Using mermaid
20
21For 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).
22
23We have compiled some Video [Tutorials](../ecosystem/tutorials.md) on how to use the Mermaid Live Editor.
24
25### Installing and Hosting Mermaid on a Webpage
26
27**Using the npm package:**
28
29Requirements:
30
31- Node >= 16
32
33```bash
34# NPM
35npm install mermaid
36# Yarn
37yarn add mermaid
38# PNPM
39pnpm add mermaid
40```
41
42**Hosting mermaid on a web page:**
43
44> Note: This topic is explored in greater depth in the [User Guide for Beginners](../intro/getting-started.md)
45
46The easiest way to integrate mermaid on a web page requires two elements:
47
48- A graph definition, inside `<pre>` tags labeled `class=mermaid`.
49
50Example:
51
52```html
53<pre class="mermaid">
54 graph LR
55 A --- B
56 B-->C[fa:fa-ban forbidden]
57 B-->D(fa:fa-spinner);
58</pre>
59```
60
61- The mermaid js script. Added using a `script` tag as an ESM import.
62
63Example:
64
65```html
66<script type="module">
67 import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
68</script>
69```
70
71**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.**
72
73## Simple full example:
74
75```html
76<!doctype html>
77<html lang="en">
78 <body>
79 <pre class="mermaid">
80 graph LR
81 A --- B
82 B-->C[fa:fa-ban forbidden]
83 B-->D(fa:fa-spinner);
84 </pre>
85 <script type="module">
86 import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
87 </script>
88 </body>
89</html>
90```
91
92## Notes:
93
94An id attribute is also added to mermaid tags without one.
95
96Mermaid can load multiple diagrams, in the same page.
97
98> Try it out, save this code as HTML and load it using any browser.
99> (Except Internet Explorer, please don't use Internet Explorer.)
100
101## Tiny Mermaid
102
103We 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.
104
105If you need a more lightweight version without these features, you can use [Mermaid Tiny](https://github.com/mermaid-js/mermaid/tree/develop/packages/tiny).
106
107## Enabling Click Event and Tags in Nodes
108
109A `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.
110
111**It is the site owner's responsibility to discriminate between trustworthy and untrustworthy user-bases and we encourage the use of discretion.**
112
113## securityLevel
114
115| Parameter | Description | Type | Required | Values |
116| ------------- | --------------------------------- | ------ | -------- | ------------------------------------------ |
117| securityLevel | Level of trust for parsed diagram | String | Optional | 'sandbox', 'strict', 'loose', 'antiscript' |
118
119Values:
120
121- **strict**: (**default**) HTML tags in the text are encoded and click functionality is disabled.
122- **antiscript**: HTML tags in text are allowed (only script elements are removed) and click functionality is enabled.
123- **loose**: HTML tags in text are allowed and click functionality is enabled.
124- **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.
125
126> **Note**
127> 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.
128> **sandbox** security level is still in the beta version.
129
130**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.**
131
132**To change `securityLevel`, you have to call `mermaid.initialize`:**
133
134```javascript
135mermaid.initialize({
136 securityLevel: 'loose',
137});
138```
139
140### Labels out of bounds
141
142If 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).
143
144```javascript
145$(document).ready(function () {
146 mermaid.initialize();
147});
148```
149
150Not 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.
151
152If 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.
153
154```css
155pre.mermaid {
156 font-family: 'trebuchet ms', verdana, arial;
157}
158```
159
160### Using `mermaid.run`
161
162mermaid.run was added in v10 and is the preferred way of handling more complex integration.
163By default, `mermaid.run` will be called when the document is ready, rendering all elements with `class="mermaid"`.
164
165You can customize that behavior by calling `await mermaid.run(<config>)`.
166
167`mermaid.initialize({startOnLoad: false})` will prevent `mermaid.run` from being called automatically after load.
168
169Render all elements with querySelector ".someOtherClass"
170
171```js
172mermaid.initialize({ startOnLoad: false });
173await mermaid.run({
174 querySelector: '.someOtherClass',
175});
176```
177
178Render all elements passed as an array
179
180```js
181mermaid.initialize({ startOnLoad: false });
182await mermaid.run({
183 nodes: [document.getElementById('someId'), document.getElementById('anotherId')],
184});
185await mermaid.run({
186 nodes: document.querySelectorAll('.yetAnotherClass'),
187});
188```
189
190Render all `.mermaid` elements while suppressing any error
191
192```js
193mermaid.initialize({ startOnLoad: false });
194await mermaid.run({
195 suppressErrors: true,
196});
197```
198
199### Calling `mermaid.init` - Deprecated
200
201> **Warning**
202> mermaid.init is deprecated in v10 and will be removed in a future release. Please use mermaid.run instead.
203
204By default, `mermaid.init` will be called when the document is ready, finding all elements with
205`class="mermaid"`. If you are adding content after mermaid is loaded, or otherwise need
206finer-grained control of this behavior, you can call `init` yourself with:
207
208- a configuration object
209- some nodes, as
210 - a node
211 - an array-like of nodes
212 - or W3C selector that will find your nodes
213
214Example:
215
216```javascript
217mermaid.init({ noteMargin: 10 }, '.someOtherClass');
218```
219
220Or with no config object, and a jQuery selection:
221
222```javascript
223mermaid.init(undefined, $('#someId .yetAnotherClass'));
224```
225
226## Usage with webpack
227
228mermaid fully supports webpack. Here is a [working demo](https://github.com/mermaidjs/mermaid-webpack-demo).
229
230## API usage
231
232The 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.
233
234The example below shows an example of how this could be used. The example just logs the resulting SVG to the JavaScript console.
235
236```html
237<script type="module">
238 import mermaid from './mermaid.esm.mjs';
239 mermaid.initialize({ startOnLoad: false });
240
241 // Example of using the render function
242 const drawDiagram = async function () {
243 element = document.querySelector('#graphDiv');
244 const graphDefinition = 'graph TB\na-->b';
245 const { svg } = await mermaid.render('graphDiv', graphDefinition);
246 element.innerHTML = svg;
247 };
248
249 await drawDiagram();
250</script>
251```
252
253To determine the type of diagram present in a given text, you can utilize the `mermaid.detectType` function, as demonstrated in the example below.
254
255```html
256<script type="module">
257 import mermaid from './mermaid.esm.mjs';
258 const graphDefinition = `sequenceDiagram
259 Pumbaa->>Timon:I ate like a pig.
260 Timon->>Pumbaa:Pumbaa, you ARE a pig.`;
261 try {
262 const type = mermaid.detectType(graphDefinition);
263 console.log(type); // 'sequence'
264 } catch (error) {
265 // UnknownDiagramError
266 }
267</script>
268```
269
270### Binding events
271
272Sometimes the generated graph also has defined interactions like tooltip and click events. When using the API one must
273add those events after the graph has been inserted into the DOM.
274
275The example code below is an extract of what mermaid does when using the API. The example shows how it is possible to
276bind events to an SVG when using the API for rendering.
277
278```javascript
279// Example of using the bindFunctions
280const drawDiagram = async function () {
281 element = document.querySelector('#graphDiv');
282 const graphDefinition = 'graph TB\na-->b';
283 const { svg, bindFunctions } = await mermaid.render('graphDiv', graphDefinition);
284 element.innerHTML = svg;
285 // This can also be written as `bindFunctions?.(element);` using the `?` shorthand.
286 if (bindFunctions) {
287 bindFunctions(element);
288 }
289};
290```
291
2921. The graph is generated using the render call.
2932. After generation the render function calls the provided callback function, in this case it's called insertSvg.
2943. 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.
2954. Insert the SVG code into the DOM for presentation.
2965. Call the binding function that binds the events.
297
298## Example of a marked renderer
299
300This is the renderer used for transforming the documentation from Markdown to html with mermaid diagrams in the html.
301
302```javascript
303const renderer = new marked.Renderer();
304renderer.code = function (code, language) {
305 if (code.match(/^sequenceDiagram/) || code.match(/^graph/)) {
306 return '<pre class="mermaid">' + code + '</pre>';
307 } else {
308 return '<pre><code>' + code + '</code></pre>';
309 }
310};
311```
312
313Another example in CoffeeScript that also includes the mermaid script tag in the generated markup.
314
315```coffee
316marked = require 'marked'
317
318module.exports = (options) ->
319 hasMermaid = false
320 renderer = new marked.Renderer()
321 renderer.defaultCode = renderer.code
322 renderer.code = (code, language) ->
323 if language is 'mermaid'
324 html = ''
325 if not hasMermaid
326 hasMermaid = true
327 html += '<script src="'+options.mermaidPath+'"></script>'
328 html + '<pre class="mermaid">'+code+'</pre>'
329 else
330 @defaultCode(code, language)
331
332 renderer
333```
334
335## Advanced usage
336
337### Syntax validation without rendering
338
339The `mermaid.parse(text, parseOptions)` function validates graph definitions without rendering a graph.
340
341The function `mermaid.parse(text, parseOptions)`, takes a text string as an argument and returns `{ diagramType: string }` if the definition follows mermaid's syntax.
342
343If the definition is invalid, the function returns `false` if `parseOptions.suppressErrors` is set to `true`. Otherwise, it throws an error.
344
345The parseError function will be called when the parse function throws an error. It will not be called if `parseOptions.suppressErrors` is set to `true`.
346
347It is possible to override this function in order to handle the error in an application-specific way.
348
349The code-example below in meta code illustrates how this could work:
350
351```javascript
352mermaid.parseError = function (err, hash) {
353 displayErrorInGui(err);
354};
355
356const textFieldUpdated = async function () {
357 const textStr = getTextFromFormField('code');
358
359 if (await mermaid.parse(textStr)) {
360 reRender(textStr);
361 }
362};
363
364bindEventHandler('change', 'code', textFieldUpdated);
365```
366
367## Configuration
368
369You can pass the required configuration to the `mermaid.initialize` call. This is the preferred way of configuring mermaid.
370The list of configuration objects are described [in the mermaidAPI documentation](./setup/README.md).
371
372```html
373<script type="module">
374 import mermaid from './mermaid.esm.mjs';
375 let config = { startOnLoad: true, htmlLabels: true, flowchart: { useMaxWidth: false } };
376 mermaid.initialize(config);
377</script>
378```
379
380> **Note**
381> This is the preferred way of configuring mermaid.
382
383### The following methods are deprecated and are kept only for backwards compatibility.
384
385## Using the mermaid object
386
387It is possible to set some configuration via the mermaid object. The two parameters that are supported using this
388approach are:
389
390- mermaid.startOnLoad
391- mermaid.htmlLabels
392
393```javascript
394mermaid.startOnLoad = true;
395```
396
397> **Warning**
398> 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.
399
400<!---
401cspell:locale en,en-gb
402cspell:ignore pumbaa
403--->
404