Merge branch 'develop' into UpdateClassMemberHandling

This commit is contained in:
Justin Greywolf 2023-06-28 08:26:33 -07:00
commit 3718274a1c
108 changed files with 2935 additions and 1755 deletions

View File

@ -53,8 +53,17 @@ body:
Please fill out the info below.
Note that you only need to fill out the relevant section
value: |-
- Mermaid version:
- Mermaid version:
- Browser and Version: [Chrome, Edge, Firefox]
- type: textarea
attributes:
label: Suggested Solutions
description: >
If applicable, suggest solutions that could resolve the bug.
It would help maintainers/contributors to not waste time looking for the solution. Even pointing the line causing the bug would be great!
placeholder: |-
- Variable `parser` in file <filepath> is not initialised ...
- Add a new type for ...
- type: textarea
attributes:
label: Additional Context

View File

@ -33,7 +33,7 @@ jobs:
# Otherwise (e.g. if running from fork), we run on a single container only
if: ${{ ( env.CYPRESS_RECORD_KEY != '' ) || ( matrix.containers == 1 ) }}
with:
start: pnpm run dev
start: pnpm run dev:coverage
wait-on: 'http://localhost:9000'
# Disable recording if we don't have an API key
# e.g. if this action was run from a fork
@ -41,7 +41,16 @@ jobs:
parallel: ${{ secrets.CYPRESS_RECORD_KEY != '' }}
env:
CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}
VITEST_COVERAGE: true
- name: Upload Coverage to Codecov
uses: codecov/codecov-action@v3
if: steps.cypress.conclusion == 'success'
with:
files: coverage/cypress/lcov.info
flags: e2e
name: mermaid-codecov
fail_ci_if_error: true
verbose: true
- name: Upload Artifacts
uses: actions/upload-artifact@v3
if: ${{ failure() && steps.cypress.conclusion == 'failure' }}

View File

@ -31,7 +31,7 @@ jobs:
- name: Run Unit Tests
run: |
pnpm run ci --coverage
pnpm test:coverage
- name: Run ganttDb tests using California timezone
env:
@ -39,13 +39,19 @@ jobs:
# since some days have 25 hours instead of 24.
TZ: America/Los_Angeles
run: |
pnpm exec vitest run ./packages/mermaid/src/diagrams/gantt/ganttDb.spec.ts
pnpm exec vitest run ./packages/mermaid/src/diagrams/gantt/ganttDb.spec.ts --coverage
- name: Upload Coverage to Coveralls
# it feels a bit weird to use @master, but that's what the docs use
# (coveralls also doesn't publish a @v1 we can use)
# https://github.com/marketplace/actions/coveralls-github-action
uses: coverallsapp/github-action@master
- name: Upload Coverage to Codecov
uses: codecov/codecov-action@v3
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
flag-name: unit
files: ./coverage/vitest/lcov.info
flags: unit
name: mermaid-codecov
fail_ci_if_error: true
verbose: true
# Coveralls is throwing 500. Disabled for now.
# - name: Upload Coverage to Coveralls
# uses: coverallsapp/github-action@v2
# with:
# github-token: ${{ secrets.GITHUB_TOKEN }}
# flag-name: unit

4
.gitignore vendored
View File

@ -3,8 +3,10 @@
node_modules/
coverage/
.idea/
.pnpm-store/
dist
v8-compile-cache-0
yarn-error.log
.npmrc
@ -39,3 +41,5 @@ stats/
**/user-avatars/*
**/contributor-names.json
.pnpm-store
.nyc_output

View File

@ -9,3 +9,9 @@ https://twitter.com/mermaidjs_
# Don't check files that are generated during the build via `pnpm docs:code`
packages/mermaid/src/docs/config/setup/*
# Ignore localhost
http://localhost:3333/
# Ignore slack invite
https://join.slack.com/

View File

@ -6,3 +6,4 @@ coverage
pnpm-lock.yaml
stats
packages/mermaid/src/docs/.vitepress/components.d.ts
.nyc_output

View File

@ -6,10 +6,12 @@ import { readFileSync } from 'fs';
import typescript from '@rollup/plugin-typescript';
import { visualizer } from 'rollup-plugin-visualizer';
import type { TemplateType } from 'rollup-plugin-visualizer/dist/plugin/template-types.js';
import istanbul from 'vite-plugin-istanbul';
const visualize = process.argv.includes('--visualize');
const watch = process.argv.includes('--watch');
const mermaidOnly = process.argv.includes('--mermaid');
const coverage = process.env.VITE_COVERAGE === 'true';
const __dirname = fileURLToPath(new URL('.', import.meta.url));
const sourcemap = false;
@ -121,6 +123,12 @@ export const getBuildConfig = ({ minify, core, watch, entryName }: BuildOptions)
jisonPlugin(),
// @ts-expect-error According to the type definitions, rollup plugins are incompatible with vite
typescript({ compilerOptions: { declaration: false } }),
istanbul({
exclude: ['node_modules', 'test/', '__mocks__'],
extension: ['.js', '.ts'],
requireEnv: true,
forceBuildInstrument: coverage,
}),
...visualizerOptions(packageName, core),
],
};

View File

@ -1,8 +1,6 @@
// @ts-ignore No typings for jison
import jison from 'jison';
export const transformJison = (src: string): string => {
// @ts-ignore No typings for jison
const parser = new jison.Generator(src, {
moduleType: 'js',
'token-stack': true,

16
CITATION.cff Normal file
View File

@ -0,0 +1,16 @@
cff-version: 1.2.0
title: 'Mermaid: Generate diagrams from markdown-like text'
message: >-
If you use this software, please cite it using the metadata from this file.
type: software
authors:
- family-names: Sveidqvist
given-names: Knut
- name: 'Contributors to Mermaid'
repository-code: 'https://github.com/mermaid-js/mermaid'
date-released: 2014-12-02
url: 'https://mermaid.js.org/'
abstract: >-
JavaScript based diagramming and charting tool that renders Markdown-inspired
text definitions to create and modify diagrams dynamically.
license: MIT

View File

@ -1,14 +1,10 @@
# Contributing
So you want to help? That's great!
Please read in detail about how to contribute documentation and code on the [Mermaid documentation site.](https://mermaid-js.github.io/mermaid/#/development)
![Happy people jumping with excitement](https://media.giphy.com/media/BlVnrxJgTGsUw/giphy.gif)
---
Here are a few things to know to get you started on the right path.
Below link will help you making a copy of the repository in your local system.
https://docs.github.com/en/get-started/quickstart/fork-a-repo
# Mermaid contribution cheat-sheet
## Requirements
@ -18,163 +14,58 @@ https://docs.github.com/en/get-started/quickstart/fork-a-repo
## Development Installation
If you don't have direct access to push to mermaid repositories, make a fork first. Then clone. Or clone directly from mermaid-js:
```bash
git clone git@github.com:mermaid-js/mermaid.git
cd mermaid
```
Install required packages:
```bash
# npx is required for first install as volta support for pnpm is not added yet.
npx pnpm install
pnpm test
```
## Committing code
### Docker
We make all changes via pull requests. As we have many pull requests from developers new to mermaid, the current approach is to have _knsv, Knut Sveidqvist_ as a main reviewer of changes and merging pull requests. More precisely like this:
- Large changes reviewed by knsv or other developer asked to review by knsv
- Smaller low-risk changes like dependencies, documentation, etc. can be merged by active collaborators
- Documentation (updates to the `package/mermaid/src/docs` folder is also allowed via direct commits)
To commit code, create a branch, let it start with the type like feature or bug followed by the issue number for reference and some describing text.
One example:
`feature/945_state_diagrams`
Another:
`bug/123_nasty_bug_branch`
## Committing documentation
Less strict here, it is OK to commit directly in the `develop` branch if you are a collaborator.
The documentation is written in **Markdown**. For more information about Markdown [see the GitHub Markdown help page](https://help.github.com/en/github/writing-on-github/basic-writing-and-formatting-syntax).
### Documentation source files are in [`/packages/mermaid/src/docs`](packages/mermaid/src/docs)
The source files for the project documentation are located in the [`/packages/mermaid/src/docs`](packages/mermaid/src/docs) directory. This is where you should make changes.
The files under `/packages/mermaid/src/docs` are processed to generate the published documentation, and the resulting files are put into the `/docs` directory.
After editing files in the [`/packages/mermaid/src/docs`](packages/mermaid/src/docs) directory, be sure to run `pnpm install` and `pnpm run --filter mermaid docs:build` locally to build the `/docs` directory.
```mermaid
flowchart LR
classDef default fill:#fff,color:black,stroke:black
source["files in /packages/mermaid/src/docs\n(changes should be done here)"] -- automatic processing\nto generate the final documentation--> published["files in /docs\ndisplayed on the official documentation site"]
If you are using docker and docker-compose, you have self-documented `run` bash script, which is a convenient alias for docker-compose commands:
```bash
./run install # npx pnpm install
./run test # pnpm test
```
You can use `note`, `tip`, `warning` and `danger` in triple backticks to add a note, tip, warning or danger box.
Do not use vitepress specific markdown syntax `::: warning` as it will not be processed correctly.
## Testing
````
```note
Note content
```bash
# Run unit test
pnpm test
# Run unit test in watch mode
pnpm test:watch
# Run E2E test
pnpm e2e
# Debug E2E tests
pnpm dev
pnpm cypress:open # in another terminal
```
```tip
Tip content
## Branch name format:
```text
[feature | bug | chore | docs]/[issue number]_[short description using dashes ('-') or underscores ('_') instead of spaces]
```
```warning
Warning content
```
eg: `feature/2945_state-diagram-new-arrow-florbs`, `bug/1123_fix_random_ugly_red_text`
```danger
Danger content
```
## Documentation
````
Documentation is necessary for all non bugfix/refactoring changes.
Only make changes to files are in [`/packages/mermaid/src/docs`](packages/mermaid/src/docs)
**_DO NOT CHANGE FILES IN `/docs`_**
### The official documentation site
**[The mermaid documentation site](https://mermaid-js.github.io/mermaid/) is powered by [Vitepress](https://vitepress.vuejs.org/), a simple documentation site generator.**
If you want to preview the whole documentation site on your machine:
```sh
cd packages/mermaid
pnpm i
pnpm docs:dev
```
You can now build and serve the documentation site:
```sh
pnpm docs:serve
```
## Branching
Going forward we will use a git flow inspired approach to branching. So development is done in develop, to do the development in the develop.
Once development is done we branch a release branch from develop for testing.
Once the release happens we merge the release branch to master and kill the release branch.
This means... **branch off your pull request from develop**
## Content of a pull request
A new feature has been born. Great! But without the steps below it might just ... fade away ...
### **Add unit tests for the parsing part**
This is important so that, if someone else does a change to the grammar that does not know about this great feature, gets notified early on when that change breaks the parser. Another important aspect is that without proper parsing tests refactoring is pretty much impossible.
### **Add e2e tests**
This tests the rendering and visual appearance of the diagram. This ensures that the rendering of that feature in the e2e will be reviewed in the release process going forward. Less chance that it breaks!
To start working with the e2e tests, run `pnpm run dev` to start the dev server, after that start cypress by running `pnpm exec cypress open` in the mermaid folder.
The rendering tests are very straightforward to create. There is a function imgSnapshotTest. This function takes a diagram in text form, the mermaid options and renders that diagram in cypress.
When running in ci it will take a snapshot of the rendered diagram and compare it with the snapshot from last build and flag for review it if it differs.
This is what a rendering test looks like:
```javascript
it('should render forks and joins', () => {
imgSnapshotTest(
`
stateDiagram
state fork_state &lt;&lt;fork&gt;&gt;
[*] --> fork_state
fork_state --> State2
fork_state --> State3
state join_state &lt;&lt;join&gt;&gt;
State2 --> join_state
State3 --> join_state
join_state --> State4
State4 --> [*]
`,
{ logLevel: 0 }
);
cy.get('svg');
});
```
### **Add documentation for it**
Finally, if it is not in the documentation, no one will know about it and then **no one will use it**. Wouldn't that be sad? With all the effort that was put into the feature?
The source files for documentation are in `/packages/mermaid/src/docs` and are written in markdown. Just pick the right section and start typing. See the [Committing Documentation](#committing-documentation) section for more about how the documentation is generated.
#### Adding to or changing the documentation organization
If you want to add a new section or change the organization (structure), then you need to make sure to **change the side navigation** in `mermaid/src/docs/.vitepress/config.js`.
When changes are committed and then released, they become part of the `master` branch and become part of the published documentation on https://mermaid-js.github.io/mermaid/
## Last words
Don't get daunted if it is hard in the beginning. We have a great community with only encouraging words. So if you get stuck, ask for help and hints in the slack forum. If you want to show off something good, show it off there.
[Join our slack community if you want closer contact!](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE)
![A superhero wishing you good luck](https://media.giphy.com/media/l49JHz7kJvl6MCj3G/giphy.gif)

View File

@ -27,7 +27,7 @@ Generate diagrams from markdown-like text.
[![NPM](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid)
[![Build CI Status](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml/badge.svg)](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml)
[![npm minified gzipped bundle size](https://img.shields.io/bundlephobia/minzip/mermaid)](https://bundlephobia.com/package/mermaid)
[![Coverage Status](https://coveralls.io/repos/github/mermaid-js/mermaid/badge.svg?branch=master)](https://coveralls.io/github/mermaid-js/mermaid?branch=master)
[![Coverage Status](https://codecov.io/github/mermaid-js/mermaid/branch/develop/graph/badge.svg)](https://app.codecov.io/github/mermaid-js/mermaid/tree/develop)
[![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid)
[![NPM Downloads](https://img.shields.io/npm/dm/mermaid)](https://www.npmjs.com/package/mermaid)
[![Join our Slack!](https://img.shields.io/static/v1?message=join%20chat&color=9cf&logo=slack&label=slack)](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE)
@ -386,7 +386,7 @@ Update version number in `package.json`.
npm publish
```
The above command generates files into the `dist` folder and publishes them to npmjs.org.
The above command generates files into the `dist` folder and publishes them to <https://www.npmjs.com>.
## Related projects
@ -402,7 +402,7 @@ Detailed information about how to contribute can be found in the [contribution g
## Security and safe diagrams
For public sites, it can be precarious to retrieve text from users on the internet, storing that content for presentation in a browser at a later stage. The reason is that the user content can contain embedded malicious scripts that will run when the data is presented. For Mermaid this is a risk, specially as mermaid diagrams contain many characters that are used in html which makes the standard sanitation unusable as it also breaks the diagrams. We still make an effort to sanitise the incoming code and keep refining the process but it is hard to guarantee that there are no loop holes.
For public sites, it can be precarious to retrieve text from users on the internet, storing that content for presentation in a browser at a later stage. The reason is that the user content can contain embedded malicious scripts that will run when the data is presented. For Mermaid this is a risk, specially as mermaid diagrams contain many characters that are used in html which makes the standard sanitation unusable as it also breaks the diagrams. We still make an effort to sanitize the incoming code and keep refining the process but it is hard to guarantee that there are no loop holes.
As an extra level of security for sites with external users we are happy to introduce a new security level in which the diagram is rendered in a sandboxed iframe preventing javascript in the code from being executed. This is a great step forward for better security.
@ -410,7 +410,7 @@ _Unfortunately you can not have a cake and eat it at the same time which in this
## Reporting vulnerabilities
To report a vulnerability, please e-mail security@mermaid.live with a description of the issue, the steps you took to create the issue, affected versions, and if known, mitigations for the issue.
To report a vulnerability, please e-mail <security@mermaid.live> with a description of the issue, the steps you took to create the issue, affected versions, and if known, mitigations for the issue.
## Appreciation

View File

@ -27,7 +27,7 @@ Mermaid
[![NPM](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid)
[![Build CI Status](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml/badge.svg)](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml)
[![npm minified gzipped bundle size](https://img.shields.io/bundlephobia/minzip/mermaid)](https://bundlephobia.com/package/mermaid)
[![Coverage Status](https://coveralls.io/repos/github/mermaid-js/mermaid/badge.svg?branch=master)](https://coveralls.io/github/mermaid-js/mermaid?branch=master)
[![Coverage Status](https://codecov.io/github/mermaid-js/mermaid/branch/develop/graph/badge.svg)](https://app.codecov.io/github/mermaid-js/mermaid/tree/develop)
[![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid)
[![NPM Downloads](https://img.shields.io/npm/dm/mermaid)](https://www.npmjs.com/package/mermaid)
[![Join our Slack!](https://img.shields.io/static/v1?message=join%20chat&color=9cf&logo=slack&label=slack)](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE)
@ -322,7 +322,7 @@ Rel(SystemC, customerA, "Sends e-mails to")
npm publish
```
以上的命令会将文件打包到 `dist` 目录并发布至 npmjs.org.
以上的命令会将文件打包到 `dist` 目录并发布至 <https://www.npmjs.com>.
## 相关项目

View File

@ -1,4 +1,3 @@
// @ts-nocheck TODO: Fix TS
import { MockedD3 } from '../packages/mermaid/src/tests/MockedD3.js';
export const select = function () {

View File

@ -43,8 +43,10 @@
"edgechromium",
"elems",
"elkjs",
"elle",
"faber",
"flatmap",
"foswiki",
"ftplugin",
"gantt",
"gitea",
@ -54,6 +56,7 @@
"graphviz",
"grav",
"greywolf",
"gzipped",
"huynh",
"huynhicode",
"inkdrop",
@ -87,6 +90,7 @@
"mkdocs",
"mmorel",
"mult",
"neurodiverse",
"nextra",
"orlandoni",
"pathe",
@ -117,6 +121,7 @@
"stopx",
"stopy",
"stylis",
"subhash-halder",
"substate",
"sveidqvist",
"swimm",
@ -131,6 +136,7 @@
"ugge",
"unist",
"unocss",
"upvoting",
"valign",
"verdana",
"viewports",

6
codecov.yaml Normal file
View File

@ -0,0 +1,6 @@
comment:
layout: 'reach, diff, flags, files'
behavior: default
require_changes: false # if true: only post the comment if coverage changes
require_base: no # [yes :: must have a base report to post]
require_head: yes # [yes :: must have a head report to post]

View File

@ -2,12 +2,14 @@
const { defineConfig } = require('cypress');
const { addMatchImageSnapshotPlugin } = require('cypress-image-snapshot/plugin');
const coverage = require('@cypress/code-coverage/task');
module.exports = defineConfig({
projectId: 'n2sma2',
e2e: {
specPattern: 'cypress/integration/**/*.{js,jsx,ts,tsx}',
setupNodeEvents(on, config) {
coverage(on, config);
addMatchImageSnapshotPlugin(on, config);
// copy any needed variables from process.env to config.env
config.env.useAppli = process.env.USE_APPLI ? true : false;

View File

@ -172,7 +172,7 @@ describe('Flowchart v2', () => {
);
});
it('52: handle nested subgraphs in several levels', () => {
it('52: handle nested subgraphs in several levels.', () => {
imgSnapshotTest(
`flowchart TB
b-->B

View File

@ -1,13 +0,0 @@
import { imgSnapshotTest } from '../../helpers/util.js';
describe('Sequencediagram', () => {
it('should render a simple info diagrams', () => {
imgSnapshotTest(
`
info
showInfo
`,
{}
);
});
});

View File

@ -0,0 +1,11 @@
import { imgSnapshotTest } from '../../helpers/util.js';
describe('info diagram', () => {
it('should handle an info definition', () => {
imgSnapshotTest(`info`);
});
it('should handle an info definition with showInfo', () => {
imgSnapshotTest(`info showInfo`);
});
});

View File

@ -1,23 +0,0 @@
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet" />
</head>
<body>
<h1>info below</h1>
<pre class="mermaid">
info
</pre>
<script type="module">
import mermaid from './mermaid.esm.mjs';
mermaid.initialize({
theme: 'forest',
// themeCSS: '.node rect { fill: red; }',
logLevel: 3,
flowchart: { curve: 'linear' },
gantt: { axisFormat: '%m/%d/%Y' },
sequence: { actorMargin: 50 },
// sequenceDiagram: { actorMargin: 300 } // deprecated
});
</script>
</body>
</html>

View File

@ -13,8 +13,8 @@
// https://on.cypress.io/configuration
// ***********************************************************
import '@cypress/code-coverage/support';
import '@applitools/eyes-cypress/commands';
// Import commands.js using ES2015 syntax:
import './commands';

View File

@ -1505,6 +1505,34 @@
</pre>
<hr />
<pre class="mermaid">
graph TD
A([Start]) ==> B[Step 1]
B ==> C{Flow 1}
C -- Choice 1.1 --> D[Step 2.1]
C -- Choice 1.3 --> I[Step 2.3]
C == Choice 1.2 ==> E[Step 2.2]
D --> F{Flow 2}
E ==> F{Flow 2}
F{Flow 2} == Choice 2.1 ==> H[Feedback node]
H[Feedback node] ==> B[Step 1]
F{Flow 2} == Choice 2.2 ==> G((Finish))
linkStyle 0,1,4,6,7,8,9 stroke:gold, stroke-width:4px
classDef active_node fill:#0CF,stroke:#09F,stroke-width:6px
classDef unactive_node fill:#e0e0e0,stroke:#bdbdbd,stroke-width:3px
classDef bugged_node fill:#F88,stroke:#F22,stroke-width:3px
classDef start_node,finish_node fill:#3B1,stroke:#391,stroke-width:8px
class A start_node;
class B,C,E,F,H active_node;
class D unactive_node;
class G finish_node;
class I bugged_node
</pre>
<hr />
<h1 id="link-clicked">Anchor for "link-clicked" test</h1>
<script type="module">

View File

@ -45,6 +45,9 @@
<li>
<h2><a href="./git.html">Git</a></h2>
</li>
<li>
<h2><a href="./info.html">Info</a></h2>
</li>
<li>
<h2><a href="./journey.html">Journey</a></h2>
</li>
@ -66,6 +69,9 @@
<li>
<h2><a href="./state.html">State</a></h2>
</li>
<li>
<h2><a href="./timeline.html">Timeline</a></h2>
</li>
<li>
<h2><a href="./zenuml.html">ZenUML</a></h2>
</li>

35
demos/info.html Normal file
View File

@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Mermaid Quick Test Page</title>
<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgo=" />
<style>
div.mermaid {
font-family: 'Courier New', Courier, monospace !important;
}
</style>
</head>
<body>
<h1>Info diagram demos</h1>
<pre class="mermaid">
info
</pre>
<hr />
<pre class="mermaid">
info showInfo
</pre>
<script type="module">
import mermaid from './mermaid.esm.mjs';
mermaid.initialize({
theme: 'forest',
logLevel: 3,
securityLevel: 'loose',
});
</script>
</body>
</html>

9
docker-compose.yml Normal file
View File

@ -0,0 +1,9 @@
version: '3.9'
services:
mermaid:
image: node:20.3.1-alpine3.18
stdin_open: true
tty: true
working_dir: /mermaid
volumes:
- ./:/mermaid

View File

@ -4,7 +4,17 @@
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/community/development.md](../../packages/mermaid/src/docs/community/development.md).
# Development and Contribution 🙌
# Contributing to Mermaid
## Contents
- [Technical Requirements and Setup](#technical-requirements-and-setup)
- [Contributing Code](#contributing-code)
- [Contributing Documentation](#contributing-documentation)
- [Questions or Suggestions?](#questions-or-suggestions)
- [Last Words](#last-words)
---
So you want to help? That's great!
@ -12,72 +22,167 @@ So you want to help? That's great!
Here are a few things to get you started on the right path.
**The Docs Structure is dictated by [.vitepress/config.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/docs/.vitepress/config.ts)**.
## Technical Requirements and Setup
**Note: Commits and Pull Requests should be directed to the develop branch.**
### Technical Requirements
## Branching
These are the tools we use for working with the code and documentation.
Mermaid uses a [Git Flow](https://guides.github.com/introduction/flow/)inspired approach to branching. So development is done in the `develop` branch.
- [volta](https://volta.sh/) to manage node versions.
- [Node.js](https://nodejs.org/en/). `volta install node`
- [pnpm](https://pnpm.io/) package manager. `volta install pnpm`
- [npx](https://docs.npmjs.com/cli/v8/commands/npx) the packaged executor in npm. This is needed [to install pnpm.](#2-install-pnpm)
Once development is done we branch a `release` branch from `develop` for testing.
Follow [the setup steps below](#setup) to install them and verify they are working
Once the release happens we merge the `release` branch with `master` and kill the `release` branch.
### Setup
This means that **you should branch off your pull request from develop** and direct all Pull Requests to it.
Follow these steps to set up the environment you need to work on code and/or documentation.
#### 1. Fork and clone the repository
In GitHub, you first _fork_ a repository when you are going to make changes and submit pull requests.
Then you _clone_ a copy to your local development machine (e.g. where you code) to make a copy with all the files to work with.
[Here is a GitHub document that gives an overview of the process.](https://docs.github.com/en/get-started/quickstart/fork-a-repo)
#### 2. Install pnpm
Once you have cloned the repository onto your development machine, change into the `mermaid` project folder so that you can install `pnpm`. You will need `npx` to install pnpm because volta doesn't support it yet.
Ex:
```bash
# Change into the mermaid directory (the top level director of the mermaid project repository)
cd mermaid
# npx is required for first install because volta does not support pnpm yet
npx pnpm install
```
#### 3. Verify Everything Is Working
Once you have installed pnpm, you can run the `test` script to verify that pnpm is working _and_ that the repository has been cloned correctly:
```bash
pnpm test
```
The `test` script and others are in the top-level `package.json` file.
All tests should run successfully without any errors or failures. (You might see _lint_ or _formatting_ warnings; those are ok during this step.)
### Docker
If you are using docker and docker-compose, you have self-documented `run` bash script, which is a convenient alias for docker-compose commands:
```bash
./run install # npx pnpm install
./run test # pnpm test
```
## Contributing Code
We make all changes via Pull Requests. As we have many Pull Requests from developers new to mermaid, we have put in place a process, wherein _knsv, Knut Sveidqvist_ is the primary reviewer of changes and merging pull requests. The process is as follows:
The basic steps for contributing code are:
- Large changes reviewed by knsv or other developer asked to review by knsv
- Smaller, low-risk changes like dependencies, documentation, etc. can be merged by active collaborators
- Documentation (we encourage updates to the `/packages/mermaid/src/docs` folder; you can submit them via direct commits)
```mermaid-example
graph LR
git[1. Checkout a git branch] --> codeTest[2. Write tests and code] --> doc[3. Update documentation] --> submit[4. Submit a PR] --> review[5. Review and merge]
```
When you commit code, create a branch with the following naming convention:
```mermaid
graph LR
git[1. Checkout a git branch] --> codeTest[2. Write tests and code] --> doc[3. Update documentation] --> submit[4. Submit a PR] --> review[5. Review and merge]
```
Start with the type, such as **feature** or **bug**, followed by the issue number for reference, and a text that describes the issue.
1. **Create** and checkout a git branch and work on your code in the branch
2. Write and update **tests** (unit and perhaps even integration (e2e) tests) (If you do TDD/BDD, the order might be different.)
3. **Let users know** that things have changed or been added in the documents! This is often overlooked, but _critical_
4. **Submit** your code as a _pull request_.
5. Maintainers will **review** your code. If there are no changes necessary, the PR will be merged. Otherwise, make the requested changes and repeat.
**One example:**
### 1. Checkout a git branch
`feature/945_state_diagrams`
Mermaid uses a [Git Flow](https://guides.github.com/introduction/flow/)inspired approach to branching.
**Another example:**
Development is done in the `develop` branch.
`bug/123_nasty_bug_branch`
Once development is done we create a `release/vX.X.X` branch from `develop` for testing.
## Contributing to Documentation
Once the release happens we add a tag to the `release` branch and merge it with `master`. The live product and on-line documentation are what is in the `master` branch.
If it is not in the documentation, it's like it never happened. Wouldn't that be sad? With all the effort that was put into the feature?
**All new work should be based on the `develop` branch.**
The docs are located in the `src/docs` folder and are written in Markdown. Just pick the right section and start typing. If you want to propose changes to the structure of the documentation, such as adding a new section or a new file you do that via **[.vitepress/config.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/docs/.vitepress/config.ts)**.
**When you are ready to do work, always, ALWAYS:**
> **All the documents displayed in the GitHub.io page are listed in [.vitepress/config.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/docs/.vitepress/config.ts)**.
1. Make sure you have the most up-to-date version of the `develop` branch. (fetch or pull to update it)
2. Check out the `develop` branch
3. Create a new branch for your work. Please name the branch following our naming convention below.
The contents of <https://mermaid-js.github.io/mermaid/> are based on the docs from the `master` branch. Updates committed to the `master` branch are reflected in the [Mermaid Docs](https://mermaid-js.github.io/mermaid/) once released.
We use the follow naming convention for branches:
## How to Contribute to Documentation
```text
[feature | bug | chore | docs]/[issue number]_[short description using dashes ('-') or underscores ('_') instead of spaces]
```
We are a little less strict here, it is OK to commit directly in the `develop` branch if you are a collaborator.
- The first part is the **type** of change: a feature, bug, chore, or documentation change ('docs')
- followed by a _slash_ (which helps to group like types together in many git tools)
- followed by the **issue number**
- followed by an _underscore_ ('\_')
- followed by a short text description (but use dashes ('-') or underscores ('\_') instead of spaces)
The documentation is located in the `src/docs` directory and organized according to relevant subfolder.
If your work is specific to a single diagram type, it is a good idea to put the diagram type at the start of the description. This will help us keep release notes organized: it will help us keep changes for a diagram type together.
The `docs` folder will be automatically generated when committing to `src/docs` and should not be edited manually.
**Ex: A new feature described in issue 2945 that adds a new arrow type called 'florbs' to state diagrams**
We encourage contributions to the documentation at [mermaid-js/mermaid/src/docs](https://github.com/mermaid-js/mermaid/tree/develop/packages/mermaid/src/docs). We publish documentation using GitHub Pages with [Docsify](https://www.youtube.com/watch?v=TV88lp7egMw&t=3s)
`feature/2945_state-diagram-new-arrow-florbs`
### Add Unit Tests for Parsing
**Ex: A bug described in issue 1123 that causes random ugly red text in multiple diagram types**
`bug/1123_fix_random_ugly_red_text`
This is important so that, if someone that does not know about this great feature suggests a change to the grammar, they get notified early on when that change breaks the parser. Another important aspect is that, without proper parsing, tests refactoring is pretty much impossible.
### 2. Write Tests
### Add E2E Tests
Tests ensure that each function, module, or part of code does what it says it will do. This is critically
important when other changes are made to ensure that existing code is not broken (no regression).
This tests the rendering and visual appearance of the diagrams. This ensures that the rendering of that feature in the e2e will be reviewed in the release process going forward. Less chance that it breaks!
Just as important, the tests act as _specifications:_ they specify what the code does (or should do).
Whenever someone is new to a section of code, they should be able to read the tests to get a thorough understanding of what it does and why.
If you are fixing a bug, you should add tests to ensure that your code has actually fixed the bug, to specify/describe what the code is doing, and to ensure the bug doesn't happen again.
(If there had been a test for the situation, the bug never would have happened in the first place.)
You may need to change existing tests if they were inaccurate.
If you are adding a feature, you will definitely need to add tests. Depending on the size of your feature, you may need to add integration tests.
#### Unit Tests
Unit tests are tests that test a single function or module. They are the easiest to write and the fastest to run.
Unit tests are mandatory all code except the renderers. (The renderers are tested with integration tests.)
We use [Vitest](https://vitest.dev) to run unit tests.
You can use the following command to run the unit tests:
```sh
pnpm test
```
When writing new tests, it's easier to have the tests automatically run as you make changes. You can do this by running the following command:
```sh
pnpm test:watch
```
#### Integration/End-to-End (e2e) tests
These test the rendering and visual appearance of the diagrams.
This ensures that the rendering of that feature in the e2e will be reviewed in the release process going forward. Less chance that it breaks!
To start working with the e2e tests:
1. Run `pnpm run dev` to start the dev server
2. Start **Cypress** by running `pnpm exec cypress open` in the **mermaid** folder.
1. Run `pnpm dev` to start the dev server
2. Start **Cypress** by running `pnpm cypress:open`.
The rendering tests are very straightforward to create. There is a function `imgSnapshotTest`, which takes a diagram in text form and the mermaid options, and it renders that diagram in Cypress.
@ -107,30 +212,162 @@ it('should render forks and joins', () => {
});
```
### Any Questions or Suggestions?
**_\[TODO - running the tests against what is expected in development. ]_**
After logging in at [GitHub.com](https://www.github.com), open or append to an issue [using the GitHub issue tracker of the mermaid-js repository](https://github.com/mermaid-js/mermaid/issues?q=is%3Aissue+is%3Aopen+label%3A%22Area%3A+Documentation%22).
**_\[TODO - how to generate new screenshots]_**
....
### How to Contribute a Suggestion
### 3. Update Documentation
If the users have no way to know that things have changed, then you haven't really _fixed_ anything for the users; you've just added to making Mermaid feel broken.
Likewise, if users don't know that there is a new feature that you've implemented, it will forever remain unknown and unused.
The documentation has to be updated to users know that things have changed and added!
We know it can sometimes be hard to code _and_ write user documentation.
Our documentation is managed in `packages/mermaid/src/docs`. Details on how to edit is in the [Contributing Documentation](#contributing-documentation) section.
Create another issue specifically for the documentation.\
You will need to help with the PR, but definitely ask for help if you feel stuck.
When it feels hard to write stuff out, explaining it to someone and having that person ask you clarifying questions can often be 80% of the work!
When in doubt, write up and submit what you can. It can be clarified and refined later. (With documentation, something is better than nothing!)
### 4. Submit your pull request
**\[TODO - PR titles should start with (fix | feat | ....)]**
We make all changes via Pull Requests (PRs). As we have many Pull Requests from developers new to Mermaid, we have put in place a process wherein _knsv, Knut Sveidqvist_ is in charge of the final release process and the active maintainers are in charge of reviewing and merging most PRs.
- PRs will be reviewed by active maintainers, who will provide feedback and request changes as needed.
- The maintainers will request a review from knsv, if necessary.
- Once the PR is approved, the maintainers will merge the PR into the `develop` branch.
- When a release is ready, the `release/x.x.x` branch will be created, extensively tested and knsv will be in charge of the release process.
**Reminder: Pull Requests should be submitted to the develop branch.**
## Contributing Documentation
**_\[TODO: This section is still a WIP. It still needs MAJOR revision.]_**
If it is not in the documentation, it's like it never happened. Wouldn't that be sad? With all the effort that was put into the feature?
The docs are located in the `packages/mermaid/src/docs` folder and are written in Markdown. Just pick the right section and start typing.
The contents of [mermaid.js.org](https://mermaid.js.org/) are based on the docs from the `master` branch.
Updates committed to the `master` branch are reflected in the [Mermaid Docs](https://mermaid.js.org/) once published.
### How to Contribute to Documentation
We are a little less strict here, it is OK to commit directly in the `develop` branch if you are a collaborator.
The documentation is located in the `packages/mermaid/src/docs` directory and organized according to relevant subfolder.
The `docs` folder will be automatically generated when committing to `packages/mermaid/src/docs` and **should not** be edited manually.
```mermaid-example
flowchart LR
classDef default fill:#fff,color:black,stroke:black
source["files in /packages/mermaid/src/docs\n(changes should be done here)"] -- automatic processing\nto generate the final documentation--> published["files in /docs\ndisplayed on the official documentation site"]
```
```mermaid
flowchart LR
classDef default fill:#fff,color:black,stroke:black
source["files in /packages/mermaid/src/docs\n(changes should be done here)"] -- automatic processing\nto generate the final documentation--> published["files in /docs\ndisplayed on the official documentation site"]
```
You can use `note`, `tip`, `warning` and `danger` in triple backticks to add a note, tip, warning or danger box.
Do not use vitepress specific markdown syntax `::: warning` as it will not be processed correctly.
````
```note
Note content
```
```tip
Tip content
```
```warning
Warning content
```
```danger
Danger content
```
````
> **Note**
> If the change is _only_ to the documentation, you can get your changes published to the site quicker by making a PR to the `master` branch.
We encourage contributions to the documentation at [packages/mermaid/src/docs in the _develop_ branch](https://github.com/mermaid-js/mermaid/tree/develop/packages/mermaid/src/docs).
**_DO NOT CHANGE FILES IN `/docs`_**
### The official documentation site
**[The mermaid documentation site](https://mermaid.js.org/) is powered by [Vitepress](https://vitepress.vuejs.org/).**
To run the documentation site locally:
1. Run `pnpm --filter mermaid run docs:dev` to start the dev server. (Or `pnpm docs:dev` inside the `packages/mermaid` directory.)
2. Open <http://localhost:3333/> in your browser.
Markdown is used to format the text, for more information about Markdown [see the GitHub Markdown help page](https://help.github.com/en/github/writing-on-github/basic-writing-and-formatting-syntax).
To edit Docs on your computer:
1. Find the Markdown file (.md) to edit in the [packages/mermaid/src/docs](https://github.com/mermaid-js/mermaid/tree/develop/packages/mermaid/src/docs) directory in the `develop` branch.
2. Create a fork of the develop branch.
_\[TODO: need to keep this in sync with [check out a git branch in Contributing Code above](#1-checkout-a-git-branch) ]_
1. Create a fork of the develop branch to work on.
2. Find the Markdown file (.md) to edit in the `packages/mermaid/src/docs` directory.
3. Make changes or add new documentation.
4. Commit changes to your fork and push it to GitHub.
4. Commit changes to your branch and push it to GitHub (which should create a new branch).
5. Create a Pull Request of your fork.
To edit Docs on GitHub:
1. Login to [GitHub.com](https://www.github.com).
2. Navigate to [packages/mermaid/src/docs](https://github.com/mermaid-js/mermaid/tree/develop/packages/mermaid/src/docs).
2. Navigate to [packages/mermaid/src/docs](https://github.com/mermaid-js/mermaid/tree/develop/packages/mermaid/src/docs) in the mermaid-js repository.
3. To edit a file, click the pencil icon at the top-right of the file contents panel.
4. Describe what you changed in the **Propose file change** section, located at the bottom of the page.
5. Submit your changes by clicking the button **Propose file change** at the bottom (by automatic creation of a fork and a new branch).
6. Create a Pull Request of your newly forked branch by clicking the green **Create Pull Request** button.
6. Visit the Actions tab in Github, `https://github.com/<Your Username>/mermaid/actions` and enable the actions for your fork. This will ensure that the documentation is built and updated in your fork.
7. Create a Pull Request of your newly forked branch by clicking the green **Create Pull Request** button.
### Documentation organization: Sidebar navigation
If you want to propose changes to how the documentation is _organized_, such as adding a new section or re-arranging or renaming a section, you must update the **sidebar navigation.**
The sidebar navigation is defined in [the vitepress configuration file config.ts](../.vitepress/config.ts).
## Questions or Suggestions?
#### First search to see if someone has already asked (and hopefully been answered) or suggested the same thing.
- Search in Discussions
- Search in open Issues
- Search in closed Issues
If you find an open issue or discussion thread that is similar to your question but isn't answered, you can let us know that you are also interested in it.
Use the GitHub reactions to add a thumbs-up to the issue or discussion thread.
This helps the team know the relative interest in something and helps them set priorities and assignments.
Feel free to add to the discussion on the issue or topic.
If you can't find anything that already addresses your question or suggestion, _open a new issue:_
Log in to [GitHub.com](https://www.github.com), open or append to an issue [using the GitHub issue tracker of the mermaid-js repository](https://github.com/mermaid-js/mermaid/issues?q=is%3Aissue+is%3Aopen+label%3A%22Area%3A+Documentation%22).
### How to Contribute a Suggestion
## Last Words

View File

@ -69,6 +69,6 @@ In fact one can pick up the syntax for it quite easily from the examples given a
## Mermaid is for everyone.
Video [Tutorials](https://mermaid-js.github.io/mermaid/#/../config/Tutorials) are also available for the mermaid [live editor](https://mermaid.live/).
Video [Tutorials](https://mermaid.js.org/config/Tutorials.html) are also available for the mermaid [live editor](https://mermaid.live/).
Alternatively you can use Mermaid [Plug-Ins](https://mermaid-js.github.io/mermaid/#/./integrations), with tools you already use, like Google Docs.

View File

@ -26,6 +26,10 @@ The definitions that can be generated the Live-Editor are also backwards-compati
[Eddie Jaoude: Can you code your diagrams?](https://www.youtube.com/watch?v=9HZzKkAqrX8)
## Mermaid with OpenAI
[Elle Neal: Mind Mapping with AI: An Accessible Approach for Neurodiverse Learners Tutorial:](https://medium.com/@elle.neal_71064/mind-mapping-with-ai-an-accessible-approach-for-neurodiverse-learners-1a74767359ff), [Demo:](https://databutton.com/v/jk9vrghc)
## Mermaid with HTML
Examples are provided in [Getting Started](../intro/n00b-gettingStarted.md)

View File

@ -8,11 +8,11 @@
## Directives
Directives gives a diagram author the capability to alter the appearance of a diagram before rendering by changing the applied configuration.
Directives give a diagram author the capability to alter the appearance of a diagram before rendering by changing the applied configuration.
The significance of having directives is that you have them available while writing the diagram, and can modify the default global and diagram specific configurations. So, directives are applied on top of the default configurations. The beauty of directives is that you can use them to alter configuration settings for a specific diagram, i.e. at an individual level.
The significance of having directives is that you have them available while writing the diagram, and can modify the default global and diagram-specific configurations. So, directives are applied on top of the default configuration. The beauty of directives is that you can use them to alter configuration settings for a specific diagram, i.e. at an individual level.
While directives allow you to change most of the default configuration settings, there are some that are not available, that too for security reasons. Also, you do have the _option to define the set of configurations_ that you would allow to be available to the diagram author for overriding with help of directives.
While directives allow you to change most of the default configuration settings, there are some that are not available, for security reasons. Also, you have the _option to define the set of configurations_ that you wish to allow diagram authors to override with directives.
## Types of Directives options
@ -20,29 +20,29 @@ Mermaid basically supports two types of configuration options to be overridden b
1. _General/Top Level configurations_ : These are the configurations that are available and applied to all the diagram. **Some of the most important top-level** configurations are:
- theme
- fontFamily
- logLevel
- securityLevel
- startOnLoad
- secure
- theme
- fontFamily
- logLevel
- securityLevel
- startOnLoad
- secure
2. _Diagram specific configurations_ : These are the configurations that are available and applied to a specific diagram. For each diagram there are specific configuration that will alter how that particular diagram looks and behaves.
For example, `mirrorActors` is a configuration that is specific to the `SequenceDiagram` and alter whether the actors are mirrored or not. So this config is available only for the `SequenceDiagram` type.
2. _Diagram-specific configurations_ : These are the configurations that are available and applied to a specific diagram. For each diagram there are specific configuration that will alter how that particular diagram looks and behaves.
For example, `mirrorActors` is a configuration that is specific to the `SequenceDiagram` and alters whether the actors are mirrored or not. So this config is available only for the `SequenceDiagram` type.
**NOTE:** These options listed here are not all the configuration options. To get hold of all the configuration options, please refer to the [defaultConfig.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/defaultConfig.ts) in the source code.
**NOTE:** Not all configuration options are listed here. To get hold of all the configuration options, please refer to the [defaultConfig.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/defaultConfig.ts) in the source code.
> **Note**
> We plan to publish a complete list of top-level configurations & all the diagram specific configurations, with their possible values in the docs soon.
> We plan to publish a complete list of top-level configurations & diagram-specific configurations with their possible values in the docs soon.
## Declaring directives
Now that we have defined the types of configurations that are available, we can learn how to declare directives.
A directive always starts and end `%%` sign with directive text in between, like `%% {directive_text} %%`.
A directive always starts and ends with `%%` signs with directive text in between, like `%% {directive_text} %%`.
Here the structure of a directive text is like a nested key-value pair map or a JSON object with root being _init_. Where all the general configurations are defined in the top level, and all the diagram specific configurations are defined one level deeper with diagram type as key/root for that section.
Following code snippet shows the structure of a directive:
The following code snippet shows the structure of a directive:
%%{
init: {
@ -61,14 +61,14 @@ Following code snippet shows the structure of a directive:
You can also define the directives in a single line, like this:
%%{init: { **insert argument here**}}%%
%%{init: { **insert configuration options here** } }%%
For example, the following code snippet:
%%{init: { "sequence": { "mirrorActors":false }}}%%
**Notes:**
The json object that is passed as {**argument** } must be valid key value pairs and encased in quotation marks or it will be ignored.
The JSON object that is passed as {**argument**} must be valid key value pairs and encased in quotation marks or it will be ignored.
Valid Key Value pairs can be found in config.
Example with a simple graph:
@ -87,7 +87,7 @@ A-->B
Here the directive declaration will set the `logLevel` to `debug` and the `theme` to `dark` for a rendered mermaid diagram, changing the appearance of the diagram itself.
Note: You can use 'init' or 'initialize' as both acceptable as init directives. Also note that `%%init%%` and `%%initialize%%` directives will be grouped together after they are parsed. This means:
Note: You can use 'init' or 'initialize' as both are acceptable as init directives. Also note that `%%init%%` and `%%initialize%%` directives will be grouped together after they are parsed.
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'forest' } }%%
@ -101,7 +101,7 @@ Note: You can use 'init' or 'initialize' as both acceptable as init directives.
...
```
parsing the above generates a single `%%init%%` JSON object below, combining the two directives and carrying over the last value given for `loglevel`:
For example, parsing the above generates a single `%%init%%` JSON object below, combining the two directives and carrying over the last value given for `loglevel`:
```json
{
@ -115,16 +115,15 @@ This will then be sent to `mermaid.initialize(...)` for rendering.
## Directive Examples
More directive examples for diagram specific configuration overrides
Now that the concept of directives has been explained, Let us see some more examples for directives usage:
Now that the concept of directives has been explained, let us see some more examples of directive usage:
### Changing Theme via directive
### Changing theme via directive
The following code snippet changes theme to forest:
The following code snippet changes `theme` to `forest`:
`%%{init: { "theme": "forest" } }%%`
Possible themes value are: `default`,`base`, `dark`, `forest` and `neutral`.
Possible theme values are: `default`,`base`, `dark`, `forest` and `neutral`.
Default Value is `default`.
Example:
@ -155,7 +154,7 @@ A --> C[End]
### Changing fontFamily via directive
The following code snippet changes fontFamily to rebuchet MS, Verdana, Arial, Sans-Serif:
The following code snippet changes fontFamily to Trebuchet MS, Verdana, Arial, Sans-Serif:
`%%{init: { "fontFamily": "Trebuchet MS, Verdana, Arial, Sans-Serif" } }%%`
@ -187,11 +186,11 @@ A --> C[End]
### Changing logLevel via directive
The following code snippet changes logLevel to 2:
The following code snippet changes `logLevel` to `2`:
`%%{init: { "logLevel": 2 } }%%`
Possible logLevel values are:
Possible `logLevel` values are:
- `1` for _debug_,
- `2` for _info_
@ -234,14 +233,14 @@ Some common flowchart configurations are:
- _diagramPadding_: number
- _useMaxWidth_: number
For complete list of flowchart configurations, see [defaultConfig.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/defaultConfig.ts) in the source code.
_Soon we plan to publish a complete list all diagram specific configurations updated in the docs_
For a complete list of flowchart configurations, see [defaultConfig.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/defaultConfig.ts) in the source code.
_Soon we plan to publish a complete list of all diagram-specific configurations updated in the docs._
The following code snippet changes flowchart config:
`%%{init: { "flowchart": { "htmlLabels": true, "curve": "linear" } } }%%`
Here were are overriding only the flowchart config, and not the general config, where HtmlLabels is set to true and curve is set to linear.
Here we are overriding only the flowchart config, and not the general config, setting `htmlLabels` to `true` and `curve` to `linear`.
```mermaid-example
%%{init: { "flowchart": { "htmlLabels": true, "curve": "linear" } } }%%
@ -267,7 +266,7 @@ A --> C[End]
### Changing Sequence diagram config via directive
Some common sequence configurations are:
Some common sequence diagram configurations are:
- _width_: number
- _height_: number
@ -278,8 +277,8 @@ Some common sequence configurations are:
- _showSequenceNumbers_: boolean
- _wrap_: boolean
For complete list of sequence diagram configurations, see _defaultConfig.ts_ in the source code.
_Soon we plan to publish a complete list all diagram specific configurations updated in the docs_
For a complete list of sequence diagram configurations, see [defaultConfig.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/defaultConfig.ts) in the source code.
_Soon we plan to publish a complete list of all diagram-specific configurations updated in the docs._
So, `wrap` by default has a value of `false` for sequence diagrams.
@ -289,7 +288,7 @@ Let us see an example:
sequenceDiagram
Alice->Bob: Hello Bob, how are you?
Bob->Alice: Fine, How did you mother like the book I suggested? And did you catch with the new book about alien invasion?
Bob->Alice: Fine, how did you mother like the book I suggested? And did you catch the new book about alien invasion?
Alice->Bob: Good.
Bob->Alice: Cool
```
@ -298,7 +297,7 @@ Bob->Alice: Cool
sequenceDiagram
Alice->Bob: Hello Bob, how are you?
Bob->Alice: Fine, How did you mother like the book I suggested? And did you catch with the new book about alien invasion?
Bob->Alice: Fine, how did you mother like the book I suggested? And did you catch the new book about alien invasion?
Alice->Bob: Good.
Bob->Alice: Cool
```
@ -309,13 +308,13 @@ The following code snippet changes sequence diagram config for `wrap` to `true`:
`%%{init: { "sequence": { "wrap": true} } }%%`
Using in the diagram above, the wrap will be enabled.
By applying that snippet to the diagram above, `wrap` will be enabled:
```mermaid-example
%%{init: { "sequence": { "wrap": true, "width":300 } } }%%
sequenceDiagram
Alice->Bob: Hello Bob, how are you?
Bob->Alice: Fine, How did you mother like the book I suggested? And did you catch with the new book about alien invasion?
Bob->Alice: Fine, how did you mother like the book I suggested? And did you catch the new book about alien invasion?
Alice->Bob: Good.
Bob->Alice: Cool
```
@ -324,7 +323,7 @@ Bob->Alice: Cool
%%{init: { "sequence": { "wrap": true, "width":300 } } }%%
sequenceDiagram
Alice->Bob: Hello Bob, how are you?
Bob->Alice: Fine, How did you mother like the book I suggested? And did you catch with the new book about alien invasion?
Bob->Alice: Fine, how did you mother like the book I suggested? And did you catch the new book about alien invasion?
Alice->Bob: Good.
Bob->Alice: Cool
```

View File

@ -39,7 +39,7 @@ bindFunctions?.(div); // To call bindFunctions only if it's present.
#### Defined in
[mermaidAPI.ts:98](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L98)
[mermaidAPI.ts:97](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L97)
---
@ -51,4 +51,4 @@ The svg code for the rendered graph.
#### Defined in
[mermaidAPI.ts:88](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L88)
[mermaidAPI.ts:87](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L87)

View File

@ -25,7 +25,7 @@ Renames and re-exports [mermaidAPI](mermaidAPI.md#mermaidapi)
#### Defined in
[mermaidAPI.ts:82](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L82)
[mermaidAPI.ts:81](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L81)
## Variables
@ -96,7 +96,7 @@ mermaid.initialize(config);
#### Defined in
[mermaidAPI.ts:670](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L670)
[mermaidAPI.ts:663](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L663)
## Functions
@ -127,7 +127,7 @@ Return the last node appended
#### Defined in
[mermaidAPI.ts:309](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L309)
[mermaidAPI.ts:308](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L308)
---
@ -153,7 +153,7 @@ the cleaned up svgCode
#### Defined in
[mermaidAPI.ts:257](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L257)
[mermaidAPI.ts:256](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L256)
---
@ -179,7 +179,7 @@ the string with all the user styles
#### Defined in
[mermaidAPI.ts:186](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L186)
[mermaidAPI.ts:185](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L185)
---
@ -202,7 +202,7 @@ the string with all the user styles
#### Defined in
[mermaidAPI.ts:234](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L234)
[mermaidAPI.ts:233](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L233)
---
@ -229,7 +229,7 @@ with an enclosing block that has each of the cssClasses followed by !important;
#### Defined in
[mermaidAPI.ts:170](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L170)
[mermaidAPI.ts:169](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L169)
---
@ -249,7 +249,7 @@ with an enclosing block that has each of the cssClasses followed by !important;
#### Defined in
[mermaidAPI.ts:156](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L156)
[mermaidAPI.ts:155](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L155)
---
@ -269,7 +269,7 @@ with an enclosing block that has each of the cssClasses followed by !important;
#### Defined in
[mermaidAPI.ts:127](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L127)
[mermaidAPI.ts:126](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L126)
---
@ -295,7 +295,7 @@ Put the svgCode into an iFrame. Return the iFrame code
#### Defined in
[mermaidAPI.ts:288](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L288)
[mermaidAPI.ts:287](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L287)
---
@ -320,4 +320,4 @@ Remove any existing elements from the given document
#### Defined in
[mermaidAPI.ts:359](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L359)
[mermaidAPI.ts:358](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L358)

View File

@ -6,6 +6,20 @@
# Integrations
## Recommendations
### File Extension
Applications that support mermaid files [SHOULD](https://datatracker.ietf.org/doc/html/rfc2119#section-3) use `.mermaid` or `.mmd` file extensions.
### MIME Type
The recommended [MIME type](https://www.iana.org/assignments/media-types/media-types.xhtml) for mermaid media is `text/vnd.mermaid`.
[IANA](https://www.iana.org/) recognition pending.
---
The following list is a compilation of different integrations and plugins that allow the rendering of mermaid definitions within other applications.
They also serve as proof of concept, for the variety of things that can be built with mermaid.
@ -52,7 +66,7 @@ They also serve as proof of concept, for the variety of things that can be built
## Blogs
- [Wordpress](https://wordpress.org)
- [WordPress](https://wordpress.org)
- [WordPress Markdown Editor](https://wordpress.org/plugins/wp-githuber-md)
- [WP-ReliableMD](https://wordpress.org/plugins/wp-reliablemd/)
- [Hexo](https://hexo.io)
@ -70,7 +84,7 @@ They also serve as proof of concept, for the variety of things that can be built
- [Plugin for Mermaid.js](https://github.com/eFrane/vuepress-plugin-mermaidjs)
- [Grav CMS](https://getgrav.org/)
- [Mermaid Diagrams](https://github.com/DanielFlaum/grav-plugin-mermaid-diagrams)
- [Gitlab Markdown Adapter](https://github.com/Goutte/grav-plugin-gitlab-markdown-adapter)
- [GitLab Markdown Adapter](https://github.com/Goutte/grav-plugin-gitlab-markdown-adapter)
## Communication
@ -90,7 +104,7 @@ They also serve as proof of concept, for the variety of things that can be built
- [Flex Diagrams Extension](https://www.mediawiki.org/wiki/Extension:Flex_Diagrams)
- [Semantic Media Wiki](https://semantic-mediawiki.org)
- [Mermaid Plugin](https://github.com/SemanticMediaWiki/Mermaid)
- [FosWiki](https://foswiki.org)
- [Foswiki](https://foswiki.org)
- [Mermaid Plugin](https://foswiki.org/Extensions/MermaidPlugin)
- [DokuWiki](https://dokuwiki.org)
- [Mermaid Plugin](https://www.dokuwiki.org/plugin:mermaid)
@ -147,6 +161,8 @@ They also serve as proof of concept, for the variety of things that can be built
- [Nano Mermaid](https://github.com/Yash-Singh1/nano-mermaid)
- [CKEditor](https://github.com/ckeditor/ckeditor5)
- [CKEditor 5 Mermaid plugin](https://github.com/ckeditor/ckeditor5-mermaid)
- [Standard Notes](https://standardnotes.com/)
- [sn-mermaid](https://github.com/nienow/sn-mermaid)
## Document Generation
@ -158,7 +174,7 @@ They also serve as proof of concept, for the variety of things that can be built
- [rehype-mermaidjs](https://github.com/remcohaszing/rehype-mermaidjs)
- [Gatsby](https://www.gatsbyjs.com/)
- [gatsby-remark-mermaid](https://github.com/remcohaszing/gatsby-remark-mermaid)
- [jSDoc](https://jsdoc.app/)
- [JSDoc](https://jsdoc.app/)
- [jsdoc-mermaid](https://github.com/Jellyvision/jsdoc-mermaid)
- [MkDocs](https://www.mkdocs.org)
- [mkdocs-mermaid2-plugin](https://github.com/fralau/mkdocs-mermaid2-plugin)

View File

@ -6,8 +6,8 @@
# Announcements
## [Bad documentation is bad for developers](https://www.mermaidchart.com/blog/posts/bad-documentation-is-bad-for-developers)
## [subhash-halder contributed quadrant charts so you can show your manager what to select - just like the strategy consultants at BCG do](https://www.mermaidchart.com/blog/posts/subhash-halder-contributed-quadrant-charts-so-you-can-show-your-manager-what-to-select-just-like-the-strategy-consultants-at-bcg-do/)
26 April 2023 · 11 mins
8 June 2023 · 7 mins
Documentation tends to be bad because companies and projects dont fully realize the costs of bad documentation.
A quadrant chart is a useful diagram that helps users visualize data and identify patterns in a data set.

View File

@ -6,6 +6,12 @@
# Blog
## [subhash-halder contributed quadrant charts so you can show your manager what to select - just like the strategy consultants at BCG do](https://www.mermaidchart.com/blog/posts/subhash-halder-contributed-quadrant-charts-so-you-can-show-your-manager-what-to-select-just-like-the-strategy-consultants-at-bcg-do/)
8 June 2023 · 7 mins
A quadrant chart is a useful diagram that helps users visualize data and identify patterns in a data set.
## [Bad documentation is bad for developers](https://www.mermaidchart.com/blog/posts/bad-documentation-is-bad-for-developers)
26 April 2023 · 11 mins

View File

@ -32,6 +32,9 @@ flowchart LR
> **Note**
> The id is what is displayed in the box.
> **💡 Tip**
> Instead of `flowchart` one can also use `graph`.
### A node with text
It is also possible to set text in the box that differs from the id. If this is done several times, it is the last text
@ -785,7 +788,10 @@ This feature is applicable to node labels, edge labels, and subgraph labels.
## Interaction
It is possible to bind a click event to a node, the click can lead to either a javascript callback or to a link which will be opened in a new browser tab. **Note**: This functionality is disabled when using `securityLevel='strict'` and enabled when using `securityLevel='loose'`.
It is possible to bind a click event to a node, the click can lead to either a javascript callback or to a link which will be opened in a new browser tab.
> **Note**
> This functionality is disabled when using `securityLevel='strict'` and enabled when using `securityLevel='loose'`.
click nodeId callback
click nodeId call callback()
@ -913,6 +919,10 @@ In the example below the style defined in the linkStyle statement will belong to
linkStyle 3 stroke:#ff3,stroke-width:4px,color:red;
It is also possible to add style to multiple links in a single statement, by separating link numbers with commas:
linkStyle 1,2,7 color:blue;
### Styling line curves
It is possible to style the type of curve used for lines between items, if the default method does not meet your needs.
@ -951,10 +961,14 @@ flowchart LR
More convenient than defining the style every time is to define a class of styles and attach this class to the nodes that
should have a different look.
a class definition looks like the example below:
A class definition looks like the example below:
classDef className fill:#f9f,stroke:#333,stroke-width:4px;
Also, it is possible to define style to multiple classes in one statement:
classDef firstClassName,secondClassName font-size:12pt;
Attachment of a class to a node is done as per below:
class nodeId1 className;
@ -1077,7 +1091,8 @@ You can change the renderer to elk by adding this directive:
%%{init: {"flowchart": {"defaultRenderer": "elk"}} }%%
Note that the site needs to use mermaid version 9.4+ for this to work and have this featured enabled in the lazy-loading configuration.
> **Note**
> Note that the site needs to use mermaid version 9.4+ for this to work and have this featured enabled in the lazy-loading configuration.
### Width

View File

@ -152,7 +152,7 @@ quadrantChart
y-axis Not Important --> "Important ❤"
quadrant-1 Plan
quadrant-2 Do
quadrant-3 Deligate
quadrant-3 Delegate
quadrant-4 Delete
```
@ -163,6 +163,6 @@ quadrantChart
y-axis Not Important --> "Important ❤"
quadrant-1 Plan
quadrant-2 Do
quadrant-3 Deligate
quadrant-3 Delegate
quadrant-4 Delete
```

View File

@ -137,7 +137,7 @@ timeline
section Stone Age
7600 BC : Britain's oldest known house was built in Orkney, Scotland
6000 BC : Sea levels rise and Britain becomes an island.<br> The people who live here are hunter-gatherers.
section Broze Age
section Bronze Age
2300 BC : People arrive from Europe and settle in Britain. <br>They bring farming and metalworking.
: New styles of pottery and ways of burying the dead appear.
2200 BC : The last major building works are completed at Stonehenge.<br> People now bury their dead in stone circles.
@ -151,7 +151,7 @@ timeline
section Stone Age
7600 BC : Britain's oldest known house was built in Orkney, Scotland
6000 BC : Sea levels rise and Britain becomes an island.<br> The people who live here are hunter-gatherers.
section Broze Age
section Bronze Age
2300 BC : People arrive from Europe and settle in Britain. <br>They bring farming and metalworking.
: New styles of pottery and ways of burying the dead appear.
2200 BC : The last major building works are completed at Stonehenge.<br> People now bury their dead in stone circles.
@ -257,9 +257,11 @@ let us look at same example, where we have disabled the multiColor option.
### Customizing Color scheme
You can customize the color scheme using the `cScale0` to `cScale11` theme variables. Mermaid allows you to set unique colors for up-to 12 sections, where `cScale0` variable will drive the value of the first section or time-period, `cScale1` will drive the value of the second section and so on.
You can customize the color scheme using the `cScale0` to `cScale11` theme variables, which will change the background colors. Mermaid allows you to set unique colors for up-to 12 sections, where `cScale0` variable will drive the value of the first section or time-period, `cScale1` will drive the value of the second section and so on.
In case you have more than 12 sections, the color scheme will start to repeat.
If you also want to change the foreground color of a section, you can do so use theme variables corresponding `cScaleLabel0` to `cScaleLabel11` variables.
NOTE: Default values for these theme variables are picked from the selected theme. If you want to override the default values, you can use the `initialize` call to add your custom theme variable values.
Example:
@ -268,9 +270,9 @@ Now let's override the default values for the `cScale0` to `cScale2` variables:
```mermaid-example
%%{init: { 'logLevel': 'debug', 'theme': 'default' , 'themeVariables': {
'cScale0': '#ff0000',
'cScale0': '#ff0000', 'cScaleLabel0': '#ffffff',
'cScale1': '#00ff00',
'cScale2': '#0000ff'
'cScale2': '#0000ff', 'cScaleLabel2': '#ffffff'
} } }%%
timeline
title History of Social Media Platform
@ -286,9 +288,9 @@ Now let's override the default values for the `cScale0` to `cScale2` variables:
```mermaid
%%{init: { 'logLevel': 'debug', 'theme': 'default' , 'themeVariables': {
'cScale0': '#ff0000',
'cScale0': '#ff0000', 'cScaleLabel0': '#ffffff',
'cScale1': '#00ff00',
'cScale2': '#0000ff'
'cScale2': '#0000ff', 'cScaleLabel2': '#ffffff'
} } }%%
timeline
title History of Social Media Platform

View File

@ -4,7 +4,7 @@
"version": "10.2.3",
"description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.",
"type": "module",
"packageManager": "pnpm@8.5.1",
"packageManager": "pnpm@8.6.5",
"keywords": [
"diagram",
"markdown",
@ -22,6 +22,7 @@
"build:watch": "pnpm build:vite --watch",
"build": "pnpm run -r clean && pnpm build:types && pnpm build:vite",
"dev": "concurrently \"pnpm build:vite --watch\" \"ts-node-esm .vite/server.ts\"",
"dev:coverage": "pnpm coverage:cypress:clean && VITE_COVERAGE=true pnpm dev",
"release": "pnpm build",
"lint": "eslint --cache --cache-strategy content --ignore-path .gitignore . && pnpm lint:jison && prettier --cache --check .",
"lint:fix": "eslint --cache --cache-strategy content --fix --ignore-path .gitignore . && prettier --write . && ts-node-esm scripts/fixCSpell.ts",
@ -30,6 +31,10 @@
"cypress": "cypress run",
"cypress:open": "cypress open",
"e2e": "start-server-and-test dev http://localhost:9000/ cypress",
"coverage:cypress:clean": "rimraf .nyc_output coverage/cypress",
"e2e:coverage": "pnpm coverage:cypress:clean && VITE_COVERAGE=true pnpm e2e",
"coverage:merge": "ts-node-esm scripts/coverage.ts",
"coverage": "pnpm test:coverage --run && pnpm e2e:coverage && pnpm coverage:merge",
"ci": "vitest run",
"test": "pnpm lint && vitest run",
"test:watch": "vitest --watch",
@ -55,11 +60,12 @@
]
},
"devDependencies": {
"@applitools/eyes-cypress": "^3.32.0",
"@applitools/eyes-cypress": "^3.33.1",
"@commitlint/cli": "^17.6.1",
"@commitlint/config-conventional": "^17.6.1",
"@cspell/eslint-plugin": "^6.31.1",
"@rollup/plugin-typescript": "^11.1.0",
"@cypress/code-coverage": "^3.10.7",
"@rollup/plugin-typescript": "^11.1.1",
"@types/cors": "^2.8.13",
"@types/eslint": "^8.37.0",
"@types/express": "^4.17.17",
@ -72,48 +78,53 @@
"@types/rollup-plugin-visualizer": "^4.2.1",
"@typescript-eslint/eslint-plugin": "^5.59.0",
"@typescript-eslint/parser": "^5.59.0",
"@vitest/coverage-c8": "^0.31.0",
"@vitest/spy": "^0.31.0",
"@vitest/ui": "^0.31.0",
"@vitest/coverage-istanbul": "^0.32.2",
"@vitest/spy": "^0.32.2",
"@vitest/ui": "^0.32.2",
"concurrently": "^8.0.1",
"cors": "^2.8.5",
"coveralls": "^3.1.1",
"cypress": "^12.10.0",
"cypress-image-snapshot": "^4.0.1",
"esbuild": "^0.17.18",
"esbuild": "^0.18.0",
"eslint": "^8.39.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-cypress": "^2.13.2",
"eslint-plugin-html": "^7.1.0",
"eslint-plugin-jest": "^27.2.1",
"eslint-plugin-jsdoc": "^43.0.7",
"eslint-plugin-jsdoc": "^46.0.0",
"eslint-plugin-json": "^3.1.0",
"eslint-plugin-lodash": "^7.4.0",
"eslint-plugin-markdown": "^3.0.0",
"eslint-plugin-no-only-tests": "^3.1.0",
"eslint-plugin-tsdoc": "^0.2.17",
"eslint-plugin-unicorn": "^46.0.0",
"eslint-plugin-unicorn": "^47.0.0",
"express": "^4.18.2",
"globby": "^13.1.4",
"husky": "^8.0.3",
"jest": "^29.5.0",
"jison": "^0.4.18",
"js-yaml": "^4.1.0",
"jsdom": "^21.1.1",
"jsdom": "^22.0.0",
"lint-staged": "^13.2.1",
"nyc": "^15.1.0",
"path-browserify": "^1.0.1",
"pnpm": "^8.3.1",
"prettier": "^2.8.8",
"prettier-plugin-jsdoc": "^0.4.2",
"rimraf": "^5.0.0",
"rollup-plugin-visualizer": "^5.9.0",
"rollup-plugin-visualizer": "^5.9.2",
"start-server-and-test": "^2.0.0",
"ts-node": "^10.9.1",
"typescript": "^5.0.4",
"vite": "^4.3.1",
"vitest": "^0.31.0"
"typescript": "^5.1.3",
"vite": "^4.3.9",
"vite-plugin-istanbul": "^4.1.0",
"vitest": "^0.32.2"
},
"volta": {
"node": "18.16.0"
"node": "18.16.1"
},
"nyc": {
"report-dir": "coverage/cypress"
}
}

View File

@ -52,9 +52,6 @@
"rimraf": "^5.0.0",
"mermaid": "workspace:*"
},
"resolutions": {
"d3": "^7.0.0"
},
"files": [
"dist"
],

View File

@ -3,7 +3,7 @@ import type { ExternalDiagramDefinition } from 'mermaid';
const id = 'example-diagram';
const detector = (txt: string) => {
return txt.match(/^\s*example-diagram/) !== null;
return /^\s*example-diagram/.test(txt);
};
const loader = async () => {

View File

@ -1,10 +1,9 @@
import type { ExternalDiagramDefinition } from 'mermaid';
const id = 'zenuml';
const regexp = /^\s*zenuml/;
const detector = (txt: string) => {
return txt.match(regexp) !== null;
return /^\s*zenuml/.test(txt);
};
const loader = async () => {

View File

@ -73,6 +73,7 @@
"devDependencies": {
"@types/cytoscape": "^3.19.9",
"@types/d3": "^7.4.0",
"@types/d3-selection": "^3.0.5",
"@types/dompurify": "^3.0.2",
"@types/jsdom": "^21.1.1",
"@types/lodash-es": "^4.17.7",
@ -91,7 +92,7 @@
"globby": "^13.1.4",
"jison": "^0.4.18",
"js-base64": "^3.7.5",
"jsdom": "^21.1.1",
"jsdom": "^22.0.0",
"micromatch": "^4.0.5",
"path-browserify": "^1.0.1",
"prettier": "^2.8.8",

View File

@ -51,7 +51,6 @@ describe('accessibility', () => {
desc: string | null | undefined,
givenId: string
) {
// @ts-ignore Required to easily handle the d3 select types
const svgAttrSpy = vi.spyOn(svgD3Node, 'attr').mockReturnValue(svgD3Node);
addSVGa11yTitleDescription(svgD3Node, title, desc, givenId);
expect(svgAttrSpy).toHaveBeenCalledWith('aria-labelledby', `chart-title-${givenId}`);
@ -63,7 +62,6 @@ describe('accessibility', () => {
desc: string | null | undefined,
givenId: string
) {
// @ts-ignore Required to easily handle the d3 select types
const svgAttrSpy = vi.spyOn(svgD3Node, 'attr').mockReturnValue(svgD3Node);
addSVGa11yTitleDescription(svgD3Node, title, desc, givenId);
expect(svgAttrSpy).toHaveBeenCalledWith('aria-describedby', `chart-desc-${givenId}`);

View File

@ -20,7 +20,7 @@
* of src to dst in order.
* @param {any} dst - The destination of the merge
* @param {any} src - The source object(s) to merge into destination
* @param {{ depth: number; clobber: boolean }} [config={ depth: 2, clobber: false }] - Depth: depth
* @param {{ depth: number; clobber: boolean }} [config] - Depth: depth
* to traverse within src and dst for merging - clobber: should dissimilar types clobber (default:
* { depth: 2, clobber: false }). Default is `{ depth: 2, clobber: false }`
* @returns {any}

View File

@ -1,6 +1,6 @@
# Cluster handling
Dagre does not support edges between nodes and clusters or between clusters to other clusters. In order to remedy this shortcoming the dagre wrapper implements a few work-arounds.
Dagre does not support edges between nodes and clusters or between clusters to other clusters. In order to remedy this shortcoming the dagre wrapper implements a few workarounds.
In the diagram below there are two clusters and there are no edges to nodes outside the own cluster.
@ -73,7 +73,7 @@ Sample object:
}
```
This is set by the renderer of the diagram and insert the data that the wrapper neds for rendering.
This is set by the renderer of the diagram and insert the data that the wrapper needs for rendering.
| property | description |
| ---------- | ------------------------------------------------------------------------------------------------ |
@ -114,7 +114,7 @@ Required edgeData for proper rendering:
| label | overlap between label and labelText? |
| labelPos | |
| labelType | overlap between label and labelText? |
| thickness | Sets the thinkess of the edge. Can be \['normal', 'thick'\] |
| thickness | Sets the thickness of the edge. Can be \['normal', 'thick'\] |
| pattern | Sets the pattern of the edge. Can be \['solid', 'dotted', 'dashed'\] |
# Markers

View File

@ -601,6 +601,8 @@ const doublecircle = async (parent, node) => {
const outerCircle = circleGroup.insert('circle');
const innerCircle = circleGroup.insert('circle');
circleGroup.attr('class', node.class);
// center the circle around its coordinate
outerCircle
.attr('style', node.style)

View File

@ -4,7 +4,7 @@ import flowchartV2 from '../diagrams/flowchart/flowDetector-v2.js';
import er from '../diagrams/er/erDetector.js';
import git from '../diagrams/git/gitGraphDetector.js';
import gantt from '../diagrams/gantt/ganttDetector.js';
import info from '../diagrams/info/infoDetector.js';
import { info } from '../diagrams/info/infoDetector.js';
import pie from '../diagrams/pie/pieDetector.js';
import quadrantChart from '../diagrams/quadrant-chart/quadrantDetector.js';
import requirement from '../diagrams/requirement/requirementDetector.js';

View File

@ -1,4 +1,4 @@
import { DiagramDb } from './types.js';
import { DiagramDB } from './types.js';
// The "* as yaml" part is necessary for tree-shaking
import * as yaml from 'js-yaml';
@ -22,7 +22,7 @@ type FrontMatterMetadata = {
* @param db - Diagram database, could be of any diagram.
* @returns text with frontmatter stripped out
*/
export function extractFrontMatter(text: string, db: DiagramDb): string {
export function extractFrontMatter(text: string, db: DiagramDB): string {
const matches = text.match(frontMatterRegex);
if (matches) {
const parsed: FrontMatterMetadata = yaml.load(matches[1], {

View File

@ -1,4 +1,6 @@
import { Diagram } from '../Diagram.js';
import { MermaidConfig } from '../config.type.js';
import type * as d3 from 'd3';
export interface InjectUtils {
_log: any;
@ -13,7 +15,7 @@ export interface InjectUtils {
/**
* Generic Diagram DB that may apply to any diagram type.
*/
export interface DiagramDb {
export interface DiagramDB {
clear?: () => void;
setDiagramTitle?: (title: string) => void;
setDisplayMode?: (title: string) => void;
@ -23,10 +25,10 @@ export interface DiagramDb {
}
export interface DiagramDefinition {
db: DiagramDb;
db: DiagramDB;
renderer: any;
parser: any;
styles: any;
styles?: any;
init?: (config: MermaidConfig) => void;
injectUtils?: (
_log: InjectUtils['_log'],
@ -52,3 +54,33 @@ export interface ExternalDiagramDefinition {
export type DiagramDetector = (text: string, config?: MermaidConfig) => boolean;
export type DiagramLoader = () => Promise<{ id: string; diagram: DiagramDefinition }>;
/**
* Type for function draws diagram in the tag with id: id based on the graph definition in text.
*
* @param text - The text of the diagram.
* @param id - The id of the diagram which will be used as a DOM element id.
* @param version - MermaidJS version from package.json.
* @param diagramObject - A standard diagram containing the DB and the text and type etc of the diagram.
*/
export type DrawDefinition = (
text: string,
id: string,
version: string,
diagramObject: Diagram
) => void;
/**
* Type for function parse directive from diagram code.
*
* @param statement -
* @param context -
* @param type -
*/
export type ParseDirectiveDefinition = (statement: string, context: string, type: string) => void;
export type HTML = d3.Selection<HTMLIFrameElement, unknown, Element, unknown>;
export type SVG = d3.Selection<SVGSVGElement, unknown, Element, unknown>;
export type DiagramStylesProvider = (options?: any) => string;

View File

@ -1,12 +1,16 @@
import type { ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'c4';
const detector = (txt: string) => {
return txt.match(/^\s*C4Context|C4Container|C4Component|C4Dynamic|C4Deployment/) !== null;
const detector: DiagramDetector = (txt) => {
return /^\s*C4Context|C4Container|C4Component|C4Dynamic|C4Deployment/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./c4Diagram.js');
return { id, diagram };
};

View File

@ -220,7 +220,7 @@ export const drawC4ShapeArray = function (currentBounds, diagram, c4ShapeArray,
let c4ShapeTypeConf = c4ShapeFont(conf, c4Shape.typeC4Shape.text);
c4ShapeTypeConf.fontSize = c4ShapeTypeConf.fontSize - 2;
c4Shape.typeC4Shape.width = calculateTextWidth(
'<<' + c4Shape.typeC4Shape.text + '>>',
'«' + c4Shape.typeC4Shape.text + '»',
c4ShapeTypeConf
);
c4Shape.typeC4Shape.height = c4ShapeTypeConf.fontSize + 2;

View File

@ -1,20 +1,21 @@
import type { DiagramDetector, ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'classDiagram';
const detector: DiagramDetector = (txt, config) => {
// If we have configured to use dagre-wrapper then we should return true in this function for classDiagram code thus making it use the new class diagram
if (
txt.match(/^\s*classDiagram/) !== null &&
config?.class?.defaultRenderer === 'dagre-wrapper'
) {
if (/^\s*classDiagram/.test(txt) && config?.class?.defaultRenderer === 'dagre-wrapper') {
return true;
}
// We have not opted to use the new renderer so we should return true if we detect a class diagram
return txt.match(/^\s*classDiagram-v2/) !== null;
return /^\s*classDiagram-v2/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./classDiagram-v2.js');
return { id, diagram };
};

View File

@ -1,4 +1,8 @@
import type { DiagramDetector, ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'class';
@ -8,10 +12,10 @@ const detector: DiagramDetector = (txt, config) => {
return false;
}
// We have not opted to use the new renderer so we should return true if we detect a class diagram
return txt.match(/^\s*classDiagram/) !== null;
return /^\s*classDiagram/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./classDiagram.js');
return { id, diagram };
};

View File

@ -1,4 +1,4 @@
// @ts-expect-error - d3 types issue
// @ts-nocheck - don't check until handle it
import { select, Selection } from 'd3';
import { log } from '../../logger.js';
import * as configApi from '../../config.js';
@ -369,7 +369,6 @@ export const relationType = {
const setupToolTips = function (element: Element) {
let tooltipElem: Selection<HTMLDivElement, unknown, HTMLElement, unknown> =
select('.mermaidTooltip');
// @ts-ignore - _groups is a dynamic property
if ((tooltipElem._groups || tooltipElem)[0][0] === null) {
tooltipElem = select('body').append('div').attr('class', 'mermaidTooltip').style('opacity', 0);
}

View File

@ -1,4 +1,4 @@
// @ts-ignore d3 types are not available
// @ts-nocheck - don't check until handle it
import { select, curveLinear } from 'd3';
import * as graphlib from 'dagre-d3-es/src/graphlib/index.js';
import { log } from '../../logger.js';
@ -347,11 +347,9 @@ export const draw = async function (text: string, id: string, _version: string,
securityLevel === 'sandbox'
? select(sandboxElement.nodes()[0].contentDocument.body)
: select('body');
// @ts-ignore Ignore type error for now
const svg = root.select(`[id="${id}"]`);
// Run the renderer. This is what draws the final graph.
// @ts-ignore Ignore type error for now
const element = root.select('#' + id + ' g');
await render(
element,
@ -367,7 +365,6 @@ export const draw = async function (text: string, id: string, _version: string,
// Add label rects for non html labels
if (!conf?.htmlLabels) {
// @ts-ignore Ignore type error for now
const doc = securityLevel === 'sandbox' ? sandboxElement.nodes()[0].contentDocument : document;
const labels = doc.querySelectorAll('[id="' + id + '"] .edgeLabel .label');
for (const label of labels) {

View File

@ -1,12 +1,16 @@
import type { DiagramDetector, ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'er';
const detector: DiagramDetector = (txt) => {
return txt.match(/^\s*erDiagram/) !== null;
return /^\s*erDiagram/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./erDiagram.js');
return { id, diagram };
};

View File

@ -1,4 +1,4 @@
// @ts-ignore: TODO Fix ts errors
// @ts-ignore: TODO: Fix ts errors
import erParser from './parser/erDiagram.jison';
import erDb from './erDb.js';
import erRenderer from './erRenderer.js';

View File

@ -1,21 +1,24 @@
import type { MermaidConfig } from '../../../config.type.js';
import type { ExternalDiagramDefinition, DiagramDetector } from '../../../diagram-api/types.js';
import type {
ExternalDiagramDefinition,
DiagramDetector,
DiagramLoader,
} from '../../../diagram-api/types.js';
const id = 'flowchart-elk';
const detector: DiagramDetector = (txt: string, config?: MermaidConfig): boolean => {
const detector: DiagramDetector = (txt, config): boolean => {
if (
// If diagram explicitly states flowchart-elk
txt.match(/^\s*flowchart-elk/) ||
/^\s*flowchart-elk/.test(txt) ||
// If a flowchart/graph diagram has their default renderer set to elk
(txt.match(/^\s*flowchart|graph/) && config?.flowchart?.defaultRenderer === 'elk')
(/^\s*flowchart|graph/.test(txt) && config?.flowchart?.defaultRenderer === 'elk')
) {
return true;
}
return false;
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./flowchart-elk-definition.js');
return { id, diagram };
};

View File

@ -208,21 +208,22 @@ export const updateLink = function (positions, style) {
});
};
export const addClass = function (id, style) {
if (classes[id] === undefined) {
classes[id] = { id: id, styles: [], textStyles: [] };
}
export const addClass = function (ids, style) {
ids.split(',').forEach(function (id) {
if (classes[id] === undefined) {
classes[id] = { id, styles: [], textStyles: [] };
}
if (style !== undefined && style !== null) {
style.forEach(function (s) {
if (s.match('color')) {
const newStyle1 = s.replace('fill', 'bgFill');
const newStyle2 = newStyle1.replace('color', 'fill');
classes[id].textStyles.push(newStyle2);
}
classes[id].styles.push(s);
});
}
if (style !== undefined && style !== null) {
style.forEach(function (s) {
if (s.match('color')) {
const newStyle = s.replace('fill', 'bgFill').replace('color', 'fill');
classes[id].textStyles.push(newStyle);
}
classes[id].styles.push(s);
});
}
});
};
/**

View File

@ -41,3 +41,26 @@ describe('flow db subgraphs', () => {
});
});
});
describe('flow db addClass', () => {
beforeEach(() => {
flowDb.clear();
});
it('should detect many classes', () => {
flowDb.addClass('a,b', ['stroke-width: 8px']);
const classes = flowDb.getClasses();
expect(classes.hasOwnProperty('a')).toBe(true);
expect(classes.hasOwnProperty('b')).toBe(true);
expect(classes['a']['styles']).toEqual(['stroke-width: 8px']);
expect(classes['b']['styles']).toEqual(['stroke-width: 8px']);
});
it('should detect single class', () => {
flowDb.addClass('a', ['stroke-width: 8px']);
const classes = flowDb.getClasses();
expect(classes.hasOwnProperty('a')).toBe(true);
expect(classes['a']['styles']).toEqual(['stroke-width: 8px']);
});
});

View File

@ -1,4 +1,4 @@
import type { DiagramDetector } from '../../diagram-api/types.js';
import type { DiagramDetector, DiagramLoader } from '../../diagram-api/types.js';
import type { ExternalDiagramDefinition } from '../../diagram-api/types.js';
const id = 'flowchart-v2';
@ -12,13 +12,13 @@ const detector: DiagramDetector = (txt, config) => {
}
// If we have configured to use dagre-wrapper then we should return true in this function for graph code thus making it use the new flowchart diagram
if (txt.match(/^\s*graph/) !== null && config?.flowchart?.defaultRenderer === 'dagre-wrapper') {
if (/^\s*graph/.test(txt) && config?.flowchart?.defaultRenderer === 'dagre-wrapper') {
return true;
}
return txt.match(/^\s*flowchart/) !== null;
return /^\s*flowchart/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./flowDiagram-v2.js');
return { id, diagram };
};

View File

@ -1,4 +1,8 @@
import type { DiagramDetector, ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'flowchart';
@ -11,10 +15,10 @@ const detector: DiagramDetector = (txt, config) => {
) {
return false;
}
return txt.match(/^\s*graph/) !== null;
return /^\s*graph/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./flowDiagram.js');
return { id, diagram };
};

View File

@ -113,6 +113,22 @@ describe('[Style] when parsing', () => {
expect(classes['exClass'].styles[1]).toBe('border:1px solid red');
});
it('should be possible to declare multiple classes', function () {
const res = flow.parser.parse(
'graph TD;classDef firstClass,secondClass background:#bbb,border:1px solid red;'
);
const classes = flow.parser.yy.getClasses();
expect(classes['firstClass'].styles.length).toBe(2);
expect(classes['firstClass'].styles[0]).toBe('background:#bbb');
expect(classes['firstClass'].styles[1]).toBe('border:1px solid red');
expect(classes['secondClass'].styles.length).toBe(2);
expect(classes['secondClass'].styles[0]).toBe('background:#bbb');
expect(classes['secondClass'].styles[1]).toBe('border:1px solid red');
});
it('should be possible to declare a class with a dot in the style', function () {
const res = flow.parser.parse(
'graph TD;classDef exClass background:#bbb,border:1.5px solid red;'
@ -322,4 +338,20 @@ describe('[Style] when parsing', () => {
expect(edges[0].type).toBe('arrow_point');
});
it('should handle multiple vertices with style', function () {
const res = flow.parser.parse(`
graph TD
classDef C1 stroke-dasharray:4
classDef C2 stroke-dasharray:6
A & B:::C1 & D:::C1 --> E:::C2
`);
const vert = flow.parser.yy.getVertices();
expect(vert['A'].classes.length).toBe(0);
expect(vert['B'].classes[0]).toBe('C1');
expect(vert['D'].classes[0]).toBe('C1');
expect(vert['E'].classes[0]).toBe('C2');
});
});

View File

@ -359,7 +359,7 @@ statement
separator: NEWLINE | SEMI | EOF ;
verticeStatement: verticeStatement link node
{ /* console.warn('vs',$1.stmt,$3); */ yy.addLink($1.stmt,$3,$2); $$ = { stmt: $3, nodes: $3.concat($1.nodes) } }
| verticeStatement link node spaceList
@ -368,12 +368,16 @@ verticeStatement: verticeStatement link node
|node { /*console.warn('noda', $1);*/ $$ = {stmt: $1, nodes:$1 }}
;
node: vertex
node: styledVertex
{ /* console.warn('nod', $1); */ $$ = [$1];}
| node spaceList AMP spaceList vertex
| node spaceList AMP spaceList styledVertex
{ $$ = $1.concat($5); /* console.warn('pip', $1[0], $5, $$); */ }
;
styledVertex: vertex
{ /* console.warn('nod', $1); */ $$ = $1;}
| vertex STYLE_SEPARATOR idString
{$$ = [$1];yy.setClass($1,$3)}
{$$ = $1;yy.setClass($1,$3)}
;
vertex: idString SQS text SQE

View File

@ -1,12 +1,16 @@
import type { DiagramDetector, ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'gantt';
const detector: DiagramDetector = (txt) => {
return txt.match(/^\s*gantt/) !== null;
return /^\s*gantt/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./ganttDiagram.js');
return { id, diagram };
};

View File

@ -1,13 +1,13 @@
import type { DiagramDetector } from '../../diagram-api/types.js';
import type { DiagramDetector, DiagramLoader } from '../../diagram-api/types.js';
import type { ExternalDiagramDefinition } from '../../diagram-api/types.js';
const id = 'gitGraph';
const detector: DiagramDetector = (txt) => {
return txt.match(/^\s*gitGraph/) !== null;
return /^\s*gitGraph/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./gitGraphDiagram.js');
return { id, diagram };
};

View File

@ -1,16 +0,0 @@
import { parser } from './parser/info.jison';
import infoDb from './infoDb.js';
describe('when parsing an info graph it', function () {
let ex;
beforeEach(function () {
ex = parser;
ex.yy = infoDb;
});
it('should handle an info definition', function () {
let str = `info
showInfo`;
ex.parse(str);
});
});

View File

@ -0,0 +1,24 @@
// @ts-ignore - jison doesn't export types
import { parser } from './parser/info.jison';
import { db } from './infoDb.js';
describe('info diagram', () => {
beforeEach(() => {
parser.yy = db;
parser.yy.clear();
});
it('should handle an info definition', () => {
const str = `info`;
parser.parse(str);
expect(db.getInfo()).toBeFalsy();
});
it('should handle an info definition with showInfo', () => {
const str = `info showInfo`;
parser.parse(str);
expect(db.getInfo()).toBeTruthy();
});
});

View File

@ -1,36 +0,0 @@
/** Created by knut on 15-01-14. */
import { log } from '../../logger.js';
import { clear } from '../../commonDb.js';
var message = '';
var info = false;
export const setMessage = (txt) => {
log.debug('Setting message to: ' + txt);
message = txt;
};
export const getMessage = () => {
return message;
};
export const setInfo = (inf) => {
info = inf;
};
export const getInfo = () => {
return info;
};
// export const parseError = (err, hash) => {
// global.mermaidAPI.parseError(err, hash)
// }
export default {
setMessage,
getMessage,
setInfo,
getInfo,
clear,
// parseError
};

View File

@ -0,0 +1,23 @@
import type { InfoFields, InfoDB } from './infoTypes.js';
export const DEFAULT_INFO_DB: InfoFields = {
info: false,
} as const;
let info: boolean = DEFAULT_INFO_DB.info;
export const setInfo = (toggle: boolean): void => {
info = toggle;
};
export const getInfo = (): boolean => info;
const clear = (): void => {
info = DEFAULT_INFO_DB.info;
};
export const db: InfoDB = {
clear,
setInfo,
getInfo,
};

View File

@ -1,20 +1,22 @@
import type { DiagramDetector, ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'info';
const detector: DiagramDetector = (txt) => {
return txt.match(/^\s*info/) !== null;
return /^\s*info/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./infoDiagram.js');
return { id, diagram };
};
const plugin: ExternalDiagramDefinition = {
export const info: ExternalDiagramDefinition = {
id,
detector,
loader,
};
export default plugin;

View File

@ -1,13 +1,11 @@
import { DiagramDefinition } from '../../diagram-api/types.js';
// @ts-ignore: TODO Fix ts errors
import type { DiagramDefinition } from '../../diagram-api/types.js';
// @ts-ignore - jison doesn't export types
import parser from './parser/info.jison';
import db from './infoDb.js';
import styles from './styles.js';
import renderer from './infoRenderer.js';
import { db } from './infoDb.js';
import { renderer } from './infoRenderer.js';
export const diagram: DiagramDefinition = {
parser,
db,
renderer,
styles,
};

View File

@ -1,57 +0,0 @@
/** Created by knut on 14-12-11. */
import { select } from 'd3';
import { log } from '../../logger.js';
import { getConfig } from '../../config.js';
/**
* Draws a an info picture in the tag with id: id based on the graph definition in text.
*
* @param {any} text
* @param {any} id
* @param {any} version
*/
export const draw = (text, id, version) => {
try {
// const parser = infoParser.parser;
// parser.yy = db;
log.debug('Rendering info diagram\n' + text);
const securityLevel = getConfig().securityLevel;
// Handle root and Document for when rendering in sandbox mode
let sandboxElement;
if (securityLevel === 'sandbox') {
sandboxElement = select('#i' + id);
}
const root =
securityLevel === 'sandbox'
? select(sandboxElement.nodes()[0].contentDocument.body)
: select('body');
// Parse the graph definition
// parser.parse(text);
// log.debug('Parsed info diagram');
// Fetch the default direction, use TD if none was found
const svg = root.select('#' + id);
const g = svg.append('g');
g.append('text') // text label for the x axis
.attr('x', 100)
.attr('y', 40)
.attr('class', 'version')
.attr('font-size', '32px')
.style('text-anchor', 'middle')
.text('v ' + version);
svg.attr('height', 100);
svg.attr('width', 400);
// svg.attr('viewBox', '0 0 300 150');
} catch (e) {
log.error('Error while rendering info diagram');
log.error(e.message);
}
};
export default {
draw,
};

View File

@ -0,0 +1,50 @@
import { select } from 'd3';
import { log } from '../../logger.js';
import { getConfig } from '../../config.js';
import type { DrawDefinition, HTML, SVG } from '../../diagram-api/types.js';
/**
* Draws a an info picture in the tag with id: id based on the graph definition in text.
*
* @param text - The text of the diagram.
* @param id - The id of the diagram which will be used as a DOM element id.
* @param version - MermaidJS version.
*/
const draw: DrawDefinition = (text, id, version) => {
try {
log.debug('rendering info diagram\n' + text);
const { securityLevel } = getConfig();
// handle root and document for when rendering in sandbox mode
let sandboxElement: HTML | undefined;
let document: Document | null | undefined;
if (securityLevel === 'sandbox') {
sandboxElement = select('#i' + id);
document = sandboxElement.nodes()[0].contentDocument;
}
// @ts-ignore - figure out how to assign HTML to document type
const root: HTML =
sandboxElement !== undefined && document !== undefined && document !== null
? select(document)
: select('body');
const svg: SVG = root.select('#' + id);
svg.attr('height', 100);
svg.attr('width', 400);
const g = svg.append('g');
g.append('text') // text label for the x axis
.attr('x', 100)
.attr('y', 40)
.attr('class', 'version')
.attr('font-size', '32px')
.style('text-anchor', 'middle')
.text('v ' + version);
} catch (e) {
log.error('error while rendering info diagram', e);
}
};
export const renderer = { draw };

View File

@ -0,0 +1,11 @@
import type { DiagramDB } from '../../diagram-api/types.js';
export interface InfoFields {
info: boolean;
}
export interface InfoDB extends DiagramDB {
clear: () => void;
setInfo: (info: boolean) => void;
getInfo: () => boolean;
}

View File

@ -1,3 +0,0 @@
const getStyles = () => ``;
export default getStyles;

View File

@ -1,11 +1,15 @@
import type { ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'mindmap';
const detector = (txt: string) => {
return txt.match(/^\s*mindmap/) !== null;
const detector: DiagramDetector = (txt) => {
return /^\s*mindmap/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./mindmap-definition.js');
return { id, diagram };
};

View File

@ -1,12 +1,16 @@
import type { DiagramDetector, ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'pie';
const detector: DiagramDetector = (txt) => {
return txt.match(/^\s*pie/) !== null;
return /^\s*pie/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./pieDiagram.js');
return { id, diagram };
};

View File

@ -1,12 +1,16 @@
import type { DiagramDetector, ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'quadrantChart';
const detector: DiagramDetector = (txt) => {
return txt.match(/^\s*quadrantChart/) !== null;
return /^\s*quadrantChart/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./quadrantDiagram.js');
return { id, diagram };
};

View File

@ -1,4 +1,4 @@
// @ts-ignore: TODO Fix ts errors
// @ts-nocheck - don't check until handle it
import { select } from 'd3';
import * as configApi from '../../config.js';
import { log } from '../../logger.js';

View File

@ -1,12 +1,16 @@
import type { DiagramDetector, ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'requirement';
const detector: DiagramDetector = (txt) => {
return txt.match(/^\s*requirement(Diagram)?/) !== null;
return /^\s*requirement(Diagram)?/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./requirementDiagram.js');
return { id, diagram };
};

View File

@ -1,12 +1,16 @@
import type { DiagramDetector, ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'sequence';
const detector: DiagramDetector = (txt) => {
return txt.match(/^\s*sequenceDiagram/) !== null;
return /^\s*sequenceDiagram/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./sequenceDiagram.js');
return { id, diagram };
};

View File

@ -1,21 +1,22 @@
import type { DiagramDetector, ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'stateDiagram';
const detector: DiagramDetector = (text, config) => {
if (text.match(/^\s*stateDiagram-v2/) !== null) {
const detector: DiagramDetector = (txt, config) => {
if (/^\s*stateDiagram-v2/.test(txt)) {
return true;
}
if (text.match(/^\s*stateDiagram/) && config?.state?.defaultRenderer === 'dagre-wrapper') {
return true;
}
if (text.match(/^\s*stateDiagram/) && config?.state?.defaultRenderer === 'dagre-wrapper') {
if (/^\s*stateDiagram/.test(txt) && config?.state?.defaultRenderer === 'dagre-wrapper') {
return true;
}
return false;
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./stateDiagram-v2.js');
return { id, diagram };
};

View File

@ -1,4 +1,8 @@
import type { DiagramDetector, ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'state';
@ -8,10 +12,10 @@ const detector: DiagramDetector = (txt, config) => {
if (config?.state?.defaultRenderer === 'dagre-wrapper') {
return false;
}
return txt.match(/^\s*stateDiagram/) !== null;
return /^\s*stateDiagram/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./stateDiagram.js');
return { id, diagram };
};

View File

@ -358,7 +358,7 @@ const setupDoc = (g, parentParsedItem, doc, diagramStates, diagramDb, altFlag) =
* Look through all of the documents (docs) in the parsedItems
* Because is a _document_ direction, the default direction is not necessarily the same as the overall default _diagram_ direction.
* @param {object[]} parsedItem - the parsed statement item to look through
* @param [defaultDir=DEFAULT_NESTED_DOC_DIR] - the direction to use if none is found
* @param [defaultDir] - the direction to use if none is found
* @returns {string}
*/
const getDir = (parsedItem, defaultDir = DEFAULT_NESTED_DOC_DIR) => {

View File

@ -1,12 +1,16 @@
import type { ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'timeline';
const detector = (txt: string) => {
return txt.match(/^\s*timeline/) !== null;
const detector: DiagramDetector = (txt) => {
return /^\s*timeline/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./timeline-definition.js');
return { id, diagram };
};

View File

@ -1,4 +1,4 @@
// @ts-ignore - db not typed yet
// @ts-nocheck - don't check until handle it
import { select, Selection } from 'd3';
import svgDraw from './svgDraw.js';
import { log } from '../../logger.js';
@ -46,11 +46,9 @@ export const draw = function (text: string, id: string, version: string, diagObj
}
const root =
securityLevel === 'sandbox'
? // @ts-ignore d3 types are wrong
select(sandboxElement.nodes()[0].contentDocument.body)
? select(sandboxElement.nodes()[0].contentDocument.body)
: select('body');
// @ts-ignore d3 types are wrong
const svg = root.select('#' + id);
svg.append('g');

View File

@ -1,12 +1,16 @@
import type { DiagramDetector, ExternalDiagramDefinition } from '../../diagram-api/types.js';
import type {
DiagramDetector,
DiagramLoader,
ExternalDiagramDefinition,
} from '../../diagram-api/types.js';
const id = 'journey';
const detector: DiagramDetector = (txt) => {
return txt.match(/^\s*journey/) !== null;
return /^\s*journey/.test(txt);
};
const loader = async () => {
const loader: DiagramLoader = async () => {
const { diagram } = await import('./journeyDiagram.js');
return { id, diagram };
};

View File

@ -16,7 +16,22 @@ export default defineConfig({
description: 'Create diagrams and visualizations using text and code.',
base: '/',
markdown: allMarkdownTransformers,
head: [['link', { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }]],
ignoreDeadLinks: [
// ignore all localhost links
/^https?:\/\/localhost/,
],
head: [
['link', { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
[
'script',
{
defer: 'true',
'data-domain': 'mermaid.js.org',
// All tracked stats are public and available at https://p.mermaid.live/mermaid.js.org
src: 'https://p.mermaid.live/js/script.js',
},
],
],
themeConfig: {
nav: nav(),
editLink: {
@ -42,6 +57,7 @@ export default defineConfig({
},
});
// Top (across the page) menu
function nav() {
return [
{ text: 'Docs', link: '/intro/', activeMatch: '/intro/' },
@ -65,7 +81,7 @@ function nav() {
},
{
text: 'Contributing',
link: 'https://github.com/mermaid-js/mermaid/blob/develop/CONTRIBUTING.md',
link: '/community/development',
},
],
},
@ -169,10 +185,7 @@ function sidebarCommunity() {
collapsible: true,
items: [
{ text: 'Overview for Beginners', link: '/community/n00b-overview' },
{
text: 'Development and Contribution',
link: '/community/development',
},
...sidebarCommunityDevelopContribute(),
{ text: 'Adding Diagrams', link: '/community/newDiagram' },
{ text: 'Security', link: '/community/security' },
],
@ -180,6 +193,40 @@ function sidebarCommunity() {
];
}
// Development and Contributing
function sidebarCommunityDevelopContribute() {
const page_path = '/community/development';
return [
{
text: 'Contributing to Mermaid',
link: page_path + '#contributing-to-mermaid',
collapsible: true,
items: [
{
text: 'Technical Requirements and Setup',
link: pathToId(page_path, 'technical-requirements-and-setup'),
},
{
text: 'Contributing Code',
link: pathToId(page_path, 'contributing-code'),
},
{
text: 'Contributing Documentation',
link: pathToId(page_path, 'contributing-documentation'),
},
{
text: 'Questions or Suggestions?',
link: pathToId(page_path, 'questions-or-suggestions'),
},
{
text: 'Last Words',
link: pathToId(page_path, 'last-words'),
},
],
},
];
}
function sidebarNews() {
return [
{
@ -192,3 +239,13 @@ function sidebarNews() {
},
];
}
/**
* Return a string that puts together the pagePage, a '#', then the given id
* @param pagePath
* @param id
* @returns the fully formed path
*/
function pathToId(pagePath: string, id = ''): string {
return pagePath + '#' + id;
}

View File

@ -9,6 +9,7 @@ import HomePage from '../components/HomePage.vue';
import { getRedirect } from './redirect.js';
import { h } from 'vue';
import Theme from 'vitepress/theme';
import '../style/main.css';
import 'uno.css';

View File

@ -1,4 +1,14 @@
# Development and Contribution 🙌
# Contributing to Mermaid
## Contents
- [Technical Requirements and Setup](#technical-requirements-and-setup)
- [Contributing Code](#contributing-code)
- [Contributing Documentation](#contributing-documentation)
- [Questions or Suggestions?](#questions-or-suggestions)
- [Last Words](#last-words)
---
So you want to help? That's great!
@ -6,72 +16,162 @@ So you want to help? That's great!
Here are a few things to get you started on the right path.
**The Docs Structure is dictated by [.vitepress/config.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/docs/.vitepress/config.ts)**.
## Technical Requirements and Setup
**Note: Commits and Pull Requests should be directed to the develop branch.**
### Technical Requirements
## Branching
These are the tools we use for working with the code and documentation.
Mermaid uses a [Git Flow](https://guides.github.com/introduction/flow/)inspired approach to branching. So development is done in the `develop` branch.
- [volta](https://volta.sh/) to manage node versions.
- [Node.js](https://nodejs.org/en/). `volta install node`
- [pnpm](https://pnpm.io/) package manager. `volta install pnpm`
- [npx](https://docs.npmjs.com/cli/v8/commands/npx) the packaged executor in npm. This is needed [to install pnpm.](#2-install-pnpm)
Once development is done we branch a `release` branch from `develop` for testing.
Follow [the setup steps below](#setup) to install them and verify they are working
Once the release happens we merge the `release` branch with `master` and kill the `release` branch.
### Setup
This means that **you should branch off your pull request from develop** and direct all Pull Requests to it.
Follow these steps to set up the environment you need to work on code and/or documentation.
#### 1. Fork and clone the repository
In GitHub, you first _fork_ a repository when you are going to make changes and submit pull requests.
Then you _clone_ a copy to your local development machine (e.g. where you code) to make a copy with all the files to work with.
[Here is a GitHub document that gives an overview of the process.](https://docs.github.com/en/get-started/quickstart/fork-a-repo)
#### 2. Install pnpm
Once you have cloned the repository onto your development machine, change into the `mermaid` project folder so that you can install `pnpm`. You will need `npx` to install pnpm because volta doesn't support it yet.
Ex:
```bash
# Change into the mermaid directory (the top level director of the mermaid project repository)
cd mermaid
# npx is required for first install because volta does not support pnpm yet
npx pnpm install
```
#### 3. Verify Everything Is Working
Once you have installed pnpm, you can run the `test` script to verify that pnpm is working _and_ that the repository has been cloned correctly:
```bash
pnpm test
```
The `test` script and others are in the top-level `package.json` file.
All tests should run successfully without any errors or failures. (You might see _lint_ or _formatting_ warnings; those are ok during this step.)
### Docker
If you are using docker and docker-compose, you have self-documented `run` bash script, which is a convenient alias for docker-compose commands:
```bash
./run install # npx pnpm install
./run test # pnpm test
```
## Contributing Code
We make all changes via Pull Requests. As we have many Pull Requests from developers new to mermaid, we have put in place a process, wherein _knsv, Knut Sveidqvist_ is the primary reviewer of changes and merging pull requests. The process is as follows:
The basic steps for contributing code are:
- Large changes reviewed by knsv or other developer asked to review by knsv
- Smaller, low-risk changes like dependencies, documentation, etc. can be merged by active collaborators
- Documentation (we encourage updates to the `/packages/mermaid/src/docs` folder; you can submit them via direct commits)
```mermaid
graph LR
git[1. Checkout a git branch] --> codeTest[2. Write tests and code] --> doc[3. Update documentation] --> submit[4. Submit a PR] --> review[5. Review and merge]
```
When you commit code, create a branch with the following naming convention:
1. **Create** and checkout a git branch and work on your code in the branch
2. Write and update **tests** (unit and perhaps even integration (e2e) tests) (If you do TDD/BDD, the order might be different.)
3. **Let users know** that things have changed or been added in the documents! This is often overlooked, but _critical_
4. **Submit** your code as a _pull request_.
5. Maintainers will **review** your code. If there are no changes necessary, the PR will be merged. Otherwise, make the requested changes and repeat.
Start with the type, such as **feature** or **bug**, followed by the issue number for reference, and a text that describes the issue.
### 1. Checkout a git branch
**One example:**
Mermaid uses a [Git Flow](https://guides.github.com/introduction/flow/)inspired approach to branching.
`feature/945_state_diagrams`
Development is done in the `develop` branch.
**Another example:**
Once development is done we create a `release/vX.X.X` branch from `develop` for testing.
`bug/123_nasty_bug_branch`
Once the release happens we add a tag to the `release` branch and merge it with `master`. The live product and on-line documentation are what is in the `master` branch.
## Contributing to Documentation
**All new work should be based on the `develop` branch.**
If it is not in the documentation, it's like it never happened. Wouldn't that be sad? With all the effort that was put into the feature?
**When you are ready to do work, always, ALWAYS:**
The docs are located in the `src/docs` folder and are written in Markdown. Just pick the right section and start typing. If you want to propose changes to the structure of the documentation, such as adding a new section or a new file you do that via **[.vitepress/config.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/docs/.vitepress/config.ts)**.
1. Make sure you have the most up-to-date version of the `develop` branch. (fetch or pull to update it)
2. Check out the `develop` branch
3. Create a new branch for your work. Please name the branch following our naming convention below.
> **All the documents displayed in the GitHub.io page are listed in [.vitepress/config.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/docs/.vitepress/config.ts)**.
We use the follow naming convention for branches:
The contents of [https://mermaid-js.github.io/mermaid/](https://mermaid-js.github.io/mermaid/) are based on the docs from the `master` branch. Updates committed to the `master` branch are reflected in the [Mermaid Docs](https://mermaid-js.github.io/mermaid/) once released.
```text
[feature | bug | chore | docs]/[issue number]_[short description using dashes ('-') or underscores ('_') instead of spaces]
```
## How to Contribute to Documentation
- The first part is the **type** of change: a feature, bug, chore, or documentation change ('docs')
- followed by a _slash_ (which helps to group like types together in many git tools)
- followed by the **issue number**
- followed by an _underscore_ ('\_')
- followed by a short text description (but use dashes ('-') or underscores ('\_') instead of spaces)
We are a little less strict here, it is OK to commit directly in the `develop` branch if you are a collaborator.
If your work is specific to a single diagram type, it is a good idea to put the diagram type at the start of the description. This will help us keep release notes organized: it will help us keep changes for a diagram type together.
The documentation is located in the `src/docs` directory and organized according to relevant subfolder.
**Ex: A new feature described in issue 2945 that adds a new arrow type called 'florbs' to state diagrams**
The `docs` folder will be automatically generated when committing to `src/docs` and should not be edited manually.
`feature/2945_state-diagram-new-arrow-florbs`
We encourage contributions to the documentation at [mermaid-js/mermaid/src/docs](https://github.com/mermaid-js/mermaid/tree/develop/packages/mermaid/src/docs). We publish documentation using GitHub Pages with [Docsify](https://www.youtube.com/watch?v=TV88lp7egMw&t=3s)
**Ex: A bug described in issue 1123 that causes random ugly red text in multiple diagram types**
`bug/1123_fix_random_ugly_red_text`
### Add Unit Tests for Parsing
### 2. Write Tests
This is important so that, if someone that does not know about this great feature suggests a change to the grammar, they get notified early on when that change breaks the parser. Another important aspect is that, without proper parsing, tests refactoring is pretty much impossible.
Tests ensure that each function, module, or part of code does what it says it will do. This is critically
important when other changes are made to ensure that existing code is not broken (no regression).
### Add E2E Tests
Just as important, the tests act as _specifications:_ they specify what the code does (or should do).
Whenever someone is new to a section of code, they should be able to read the tests to get a thorough understanding of what it does and why.
This tests the rendering and visual appearance of the diagrams. This ensures that the rendering of that feature in the e2e will be reviewed in the release process going forward. Less chance that it breaks!
If you are fixing a bug, you should add tests to ensure that your code has actually fixed the bug, to specify/describe what the code is doing, and to ensure the bug doesn't happen again.
(If there had been a test for the situation, the bug never would have happened in the first place.)
You may need to change existing tests if they were inaccurate.
If you are adding a feature, you will definitely need to add tests. Depending on the size of your feature, you may need to add integration tests.
#### Unit Tests
Unit tests are tests that test a single function or module. They are the easiest to write and the fastest to run.
Unit tests are mandatory all code except the renderers. (The renderers are tested with integration tests.)
We use [Vitest](https://vitest.dev) to run unit tests.
You can use the following command to run the unit tests:
```sh
pnpm test
```
When writing new tests, it's easier to have the tests automatically run as you make changes. You can do this by running the following command:
```sh
pnpm test:watch
```
#### Integration/End-to-End (e2e) tests
These test the rendering and visual appearance of the diagrams.
This ensures that the rendering of that feature in the e2e will be reviewed in the release process going forward. Less chance that it breaks!
To start working with the e2e tests:
1. Run `pnpm run dev` to start the dev server
2. Start **Cypress** by running `pnpm exec cypress open` in the **mermaid** folder.
1. Run `pnpm dev` to start the dev server
2. Start **Cypress** by running `pnpm cypress:open`.
The rendering tests are very straightforward to create. There is a function `imgSnapshotTest`, which takes a diagram in text form and the mermaid options, and it renders that diagram in Cypress.
@ -101,30 +201,155 @@ it('should render forks and joins', () => {
});
```
### Any Questions or Suggestions?
**_[TODO - running the tests against what is expected in development. ]_**
After logging in at [GitHub.com](https://www.github.com), open or append to an issue [using the GitHub issue tracker of the mermaid-js repository](https://github.com/mermaid-js/mermaid/issues?q=is%3Aissue+is%3Aopen+label%3A%22Area%3A+Documentation%22).
**_[TODO - how to generate new screenshots]_**
....
### How to Contribute a Suggestion
### 3. Update Documentation
If the users have no way to know that things have changed, then you haven't really _fixed_ anything for the users; you've just added to making Mermaid feel broken.
Likewise, if users don't know that there is a new feature that you've implemented, it will forever remain unknown and unused.
The documentation has to be updated to users know that things have changed and added!
We know it can sometimes be hard to code _and_ write user documentation.
Our documentation is managed in `packages/mermaid/src/docs`. Details on how to edit is in the [Contributing Documentation](#contributing-documentation) section.
Create another issue specifically for the documentation.
You will need to help with the PR, but definitely ask for help if you feel stuck.
When it feels hard to write stuff out, explaining it to someone and having that person ask you clarifying questions can often be 80% of the work!
When in doubt, write up and submit what you can. It can be clarified and refined later. (With documentation, something is better than nothing!)
### 4. Submit your pull request
**[TODO - PR titles should start with (fix | feat | ....)]**
We make all changes via Pull Requests (PRs). As we have many Pull Requests from developers new to Mermaid, we have put in place a process wherein _knsv, Knut Sveidqvist_ is in charge of the final release process and the active maintainers are in charge of reviewing and merging most PRs.
- PRs will be reviewed by active maintainers, who will provide feedback and request changes as needed.
- The maintainers will request a review from knsv, if necessary.
- Once the PR is approved, the maintainers will merge the PR into the `develop` branch.
- When a release is ready, the `release/x.x.x` branch will be created, extensively tested and knsv will be in charge of the release process.
**Reminder: Pull Requests should be submitted to the develop branch.**
## Contributing Documentation
**_[TODO: This section is still a WIP. It still needs MAJOR revision.]_**
If it is not in the documentation, it's like it never happened. Wouldn't that be sad? With all the effort that was put into the feature?
The docs are located in the `packages/mermaid/src/docs` folder and are written in Markdown. Just pick the right section and start typing.
The contents of [mermaid.js.org](https://mermaid.js.org/) are based on the docs from the `master` branch.
Updates committed to the `master` branch are reflected in the [Mermaid Docs](https://mermaid.js.org/) once published.
### How to Contribute to Documentation
We are a little less strict here, it is OK to commit directly in the `develop` branch if you are a collaborator.
The documentation is located in the `packages/mermaid/src/docs` directory and organized according to relevant subfolder.
The `docs` folder will be automatically generated when committing to `packages/mermaid/src/docs` and **should not** be edited manually.
```mermaid
flowchart LR
classDef default fill:#fff,color:black,stroke:black
source["files in /packages/mermaid/src/docs\n(changes should be done here)"] -- automatic processing\nto generate the final documentation--> published["files in /docs\ndisplayed on the official documentation site"]
```
You can use `note`, `tip`, `warning` and `danger` in triple backticks to add a note, tip, warning or danger box.
Do not use vitepress specific markdown syntax `::: warning` as it will not be processed correctly.
````
```note
Note content
```
```tip
Tip content
```
```warning
Warning content
```
```danger
Danger content
```
````
```note
If the change is _only_ to the documentation, you can get your changes published to the site quicker by making a PR to the `master` branch.
```
We encourage contributions to the documentation at [packages/mermaid/src/docs in the _develop_ branch](https://github.com/mermaid-js/mermaid/tree/develop/packages/mermaid/src/docs).
**_DO NOT CHANGE FILES IN `/docs`_**
### The official documentation site
**[The mermaid documentation site](https://mermaid.js.org/) is powered by [Vitepress](https://vitepress.vuejs.org/).**
To run the documentation site locally:
1. Run `pnpm --filter mermaid run docs:dev` to start the dev server. (Or `pnpm docs:dev` inside the `packages/mermaid` directory.)
2. Open [http://localhost:3333/](http://localhost:3333/) in your browser.
Markdown is used to format the text, for more information about Markdown [see the GitHub Markdown help page](https://help.github.com/en/github/writing-on-github/basic-writing-and-formatting-syntax).
To edit Docs on your computer:
1. Find the Markdown file (.md) to edit in the [packages/mermaid/src/docs](https://github.com/mermaid-js/mermaid/tree/develop/packages/mermaid/src/docs) directory in the `develop` branch.
2. Create a fork of the develop branch.
3. Make changes or add new documentation.
4. Commit changes to your fork and push it to GitHub.
5. Create a Pull Request of your fork.
_[TODO: need to keep this in sync with [check out a git branch in Contributing Code above](#1-checkout-a-git-branch) ]_
1. Create a fork of the develop branch to work on.
2. Find the Markdown file (.md) to edit in the `packages/mermaid/src/docs` directory.
3. Make changes or add new documentation.
4. Commit changes to your branch and push it to GitHub (which should create a new branch).
5. Create a Pull Request of your fork.
To edit Docs on GitHub:
1. Login to [GitHub.com](https://www.github.com).
2. Navigate to [packages/mermaid/src/docs](https://github.com/mermaid-js/mermaid/tree/develop/packages/mermaid/src/docs).
3. To edit a file, click the pencil icon at the top-right of the file contents panel.
4. Describe what you changed in the **Propose file change** section, located at the bottom of the page.
5. Submit your changes by clicking the button **Propose file change** at the bottom (by automatic creation of a fork and a new branch).
6. Create a Pull Request of your newly forked branch by clicking the green **Create Pull Request** button.
1. Login to [GitHub.com](https://www.github.com).
2. Navigate to [packages/mermaid/src/docs](https://github.com/mermaid-js/mermaid/tree/develop/packages/mermaid/src/docs) in the mermaid-js repository.
3. To edit a file, click the pencil icon at the top-right of the file contents panel.
4. Describe what you changed in the **Propose file change** section, located at the bottom of the page.
5. Submit your changes by clicking the button **Propose file change** at the bottom (by automatic creation of a fork and a new branch).
6. Visit the Actions tab in Github, `https://github.com/<Your Username>/mermaid/actions` and enable the actions for your fork. This will ensure that the documentation is built and updated in your fork.
7. Create a Pull Request of your newly forked branch by clicking the green **Create Pull Request** button.
### Documentation organization: Sidebar navigation
If you want to propose changes to how the documentation is _organized_, such as adding a new section or re-arranging or renaming a section, you must update the **sidebar navigation.**
The sidebar navigation is defined in [the vitepress configuration file config.ts](../.vitepress/config.ts).
## Questions or Suggestions?
#### First search to see if someone has already asked (and hopefully been answered) or suggested the same thing.
- Search in Discussions
- Search in open Issues
- Search in closed Issues
If you find an open issue or discussion thread that is similar to your question but isn't answered, you can let us know that you are also interested in it.
Use the GitHub reactions to add a thumbs-up to the issue or discussion thread.
This helps the team know the relative interest in something and helps them set priorities and assignments.
Feel free to add to the discussion on the issue or topic.
If you can't find anything that already addresses your question or suggestion, _open a new issue:_
Log in to [GitHub.com](https://www.github.com), open or append to an issue [using the GitHub issue tracker of the mermaid-js repository](https://github.com/mermaid-js/mermaid/issues?q=is%3Aissue+is%3Aopen+label%3A%22Area%3A+Documentation%22).
### How to Contribute a Suggestion
## Last Words

View File

@ -63,6 +63,6 @@ In fact one can pick up the syntax for it quite easily from the examples given a
## Mermaid is for everyone.
Video [Tutorials](https://mermaid-js.github.io/mermaid/#/../config/Tutorials) are also available for the mermaid [live editor](https://mermaid.live/).
Video [Tutorials](https://mermaid.js.org/config/Tutorials.html) are also available for the mermaid [live editor](https://mermaid.live/).
Alternatively you can use Mermaid [Plug-Ins](https://mermaid-js.github.io/mermaid/#/./integrations), with tools you already use, like Google Docs.

View File

@ -20,6 +20,10 @@ The definitions that can be generated the Live-Editor are also backwards-compati
[Eddie Jaoude: Can you code your diagrams?](https://www.youtube.com/watch?v=9HZzKkAqrX8)
## Mermaid with OpenAI
[Elle Neal: Mind Mapping with AI: An Accessible Approach for Neurodiverse Learners Tutorial:](https://medium.com/@elle.neal_71064/mind-mapping-with-ai-an-accessible-approach-for-neurodiverse-learners-1a74767359ff), [Demo:](https://databutton.com/v/jk9vrghc)
## Mermaid with HTML
Examples are provided in [Getting Started](../intro/n00b-gettingStarted.md)

View File

@ -2,11 +2,11 @@
## Directives
Directives gives a diagram author the capability to alter the appearance of a diagram before rendering by changing the applied configuration.
Directives give a diagram author the capability to alter the appearance of a diagram before rendering by changing the applied configuration.
The significance of having directives is that you have them available while writing the diagram, and can modify the default global and diagram specific configurations. So, directives are applied on top of the default configurations. The beauty of directives is that you can use them to alter configuration settings for a specific diagram, i.e. at an individual level.
The significance of having directives is that you have them available while writing the diagram, and can modify the default global and diagram-specific configurations. So, directives are applied on top of the default configuration. The beauty of directives is that you can use them to alter configuration settings for a specific diagram, i.e. at an individual level.
While directives allow you to change most of the default configuration settings, there are some that are not available, that too for security reasons. Also, you do have the _option to define the set of configurations_ that you would allow to be available to the diagram author for overriding with help of directives.
While directives allow you to change most of the default configuration settings, there are some that are not available, for security reasons. Also, you have the _option to define the set of configurations_ that you wish to allow diagram authors to override with directives.
## Types of Directives options
@ -14,30 +14,30 @@ Mermaid basically supports two types of configuration options to be overridden b
1. _General/Top Level configurations_ : These are the configurations that are available and applied to all the diagram. **Some of the most important top-level** configurations are:
- theme
- fontFamily
- logLevel
- securityLevel
- startOnLoad
- secure
- theme
- fontFamily
- logLevel
- securityLevel
- startOnLoad
- secure
2. _Diagram specific configurations_ : These are the configurations that are available and applied to a specific diagram. For each diagram there are specific configuration that will alter how that particular diagram looks and behaves.
For example, `mirrorActors` is a configuration that is specific to the `SequenceDiagram` and alter whether the actors are mirrored or not. So this config is available only for the `SequenceDiagram` type.
2. _Diagram-specific configurations_ : These are the configurations that are available and applied to a specific diagram. For each diagram there are specific configuration that will alter how that particular diagram looks and behaves.
For example, `mirrorActors` is a configuration that is specific to the `SequenceDiagram` and alters whether the actors are mirrored or not. So this config is available only for the `SequenceDiagram` type.
**NOTE:** These options listed here are not all the configuration options. To get hold of all the configuration options, please refer to the [defaultConfig.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/defaultConfig.ts) in the source code.
**NOTE:** Not all configuration options are listed here. To get hold of all the configuration options, please refer to the [defaultConfig.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/defaultConfig.ts) in the source code.
```note
We plan to publish a complete list of top-level configurations & all the diagram specific configurations, with their possible values in the docs soon.
We plan to publish a complete list of top-level configurations & diagram-specific configurations with their possible values in the docs soon.
```
## Declaring directives
Now that we have defined the types of configurations that are available, we can learn how to declare directives.
A directive always starts and end `%%` sign with directive text in between, like `%% {directive_text} %%`.
A directive always starts and ends with `%%` signs with directive text in between, like `%% {directive_text} %%`.
Here the structure of a directive text is like a nested key-value pair map or a JSON object with root being _init_. Where all the general configurations are defined in the top level, and all the diagram specific configurations are defined one level deeper with diagram type as key/root for that section.
Following code snippet shows the structure of a directive:
The following code snippet shows the structure of a directive:
```
%%{
@ -59,7 +59,7 @@ Following code snippet shows the structure of a directive:
You can also define the directives in a single line, like this:
```
%%{init: { **insert argument here**}}%%
%%{init: { **insert configuration options here** } }%%
```
For example, the following code snippet:
@ -69,7 +69,7 @@ For example, the following code snippet:
```
**Notes:**
The json object that is passed as {**argument** } must be valid key value pairs and encased in quotation marks or it will be ignored.
The JSON object that is passed as {**argument**} must be valid key value pairs and encased in quotation marks or it will be ignored.
Valid Key Value pairs can be found in config.
Example with a simple graph:
@ -82,7 +82,7 @@ A-->B
Here the directive declaration will set the `logLevel` to `debug` and the `theme` to `dark` for a rendered mermaid diagram, changing the appearance of the diagram itself.
Note: You can use 'init' or 'initialize' as both acceptable as init directives. Also note that `%%init%%` and `%%initialize%%` directives will be grouped together after they are parsed. This means:
Note: You can use 'init' or 'initialize' as both are acceptable as init directives. Also note that `%%init%%` and `%%initialize%%` directives will be grouped together after they are parsed.
```mermaid
%%{init: { 'logLevel': 'debug', 'theme': 'forest' } }%%
@ -90,7 +90,7 @@ Note: You can use 'init' or 'initialize' as both acceptable as init directives.
...
```
parsing the above generates a single `%%init%%` JSON object below, combining the two directives and carrying over the last value given for `loglevel`:
For example, parsing the above generates a single `%%init%%` JSON object below, combining the two directives and carrying over the last value given for `loglevel`:
```json
{
@ -104,16 +104,15 @@ This will then be sent to `mermaid.initialize(...)` for rendering.
## Directive Examples
More directive examples for diagram specific configuration overrides
Now that the concept of directives has been explained, Let us see some more examples for directives usage:
Now that the concept of directives has been explained, let us see some more examples of directive usage:
### Changing Theme via directive
### Changing theme via directive
The following code snippet changes theme to forest:
The following code snippet changes `theme` to `forest`:
`%%{init: { "theme": "forest" } }%%`
Possible themes value are: `default`,`base`, `dark`, `forest` and `neutral`.
Possible theme values are: `default`,`base`, `dark`, `forest` and `neutral`.
Default Value is `default`.
Example:
@ -132,7 +131,7 @@ A --> C[End]
### Changing fontFamily via directive
The following code snippet changes fontFamily to rebuchet MS, Verdana, Arial, Sans-Serif:
The following code snippet changes fontFamily to Trebuchet MS, Verdana, Arial, Sans-Serif:
`%%{init: { "fontFamily": "Trebuchet MS, Verdana, Arial, Sans-Serif" } }%%`
@ -152,11 +151,11 @@ A --> C[End]
### Changing logLevel via directive
The following code snippet changes logLevel to 2:
The following code snippet changes `logLevel` to `2`:
`%%{init: { "logLevel": 2 } }%%`
Possible logLevel values are:
Possible `logLevel` values are:
- `1` for _debug_,
- `2` for _info_
@ -188,14 +187,14 @@ Some common flowchart configurations are:
- _diagramPadding_: number
- _useMaxWidth_: number
For complete list of flowchart configurations, see [defaultConfig.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/defaultConfig.ts) in the source code.
_Soon we plan to publish a complete list all diagram specific configurations updated in the docs_
For a complete list of flowchart configurations, see [defaultConfig.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/defaultConfig.ts) in the source code.
_Soon we plan to publish a complete list of all diagram-specific configurations updated in the docs._
The following code snippet changes flowchart config:
`%%{init: { "flowchart": { "htmlLabels": true, "curve": "linear" } } }%%`
Here were are overriding only the flowchart config, and not the general config, where HtmlLabels is set to true and curve is set to linear.
Here we are overriding only the flowchart config, and not the general config, setting `htmlLabels` to `true` and `curve` to `linear`.
```mermaid-example
%%{init: { "flowchart": { "htmlLabels": true, "curve": "linear" } } }%%
@ -210,7 +209,7 @@ A --> C[End]
### Changing Sequence diagram config via directive
Some common sequence configurations are:
Some common sequence diagram configurations are:
- _width_: number
- _height_: number
@ -221,8 +220,8 @@ Some common sequence configurations are:
- _showSequenceNumbers_: boolean
- _wrap_: boolean
For complete list of sequence diagram configurations, see _defaultConfig.ts_ in the source code.
_Soon we plan to publish a complete list all diagram specific configurations updated in the docs_
For a complete list of sequence diagram configurations, see [defaultConfig.ts](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/defaultConfig.ts) in the source code.
_Soon we plan to publish a complete list of all diagram-specific configurations updated in the docs._
So, `wrap` by default has a value of `false` for sequence diagrams.
@ -232,7 +231,7 @@ Let us see an example:
sequenceDiagram
Alice->Bob: Hello Bob, how are you?
Bob->Alice: Fine, How did you mother like the book I suggested? And did you catch with the new book about alien invasion?
Bob->Alice: Fine, how did you mother like the book I suggested? And did you catch the new book about alien invasion?
Alice->Bob: Good.
Bob->Alice: Cool
```
@ -243,13 +242,13 @@ The following code snippet changes sequence diagram config for `wrap` to `true`:
`%%{init: { "sequence": { "wrap": true} } }%%`
Using in the diagram above, the wrap will be enabled.
By applying that snippet to the diagram above, `wrap` will be enabled:
```mermaid-example
%%{init: { "sequence": { "wrap": true, "width":300 } } }%%
sequenceDiagram
Alice->Bob: Hello Bob, how are you?
Bob->Alice: Fine, How did you mother like the book I suggested? And did you catch with the new book about alien invasion?
Bob->Alice: Fine, how did you mother like the book I suggested? And did you catch the new book about alien invasion?
Alice->Bob: Good.
Bob->Alice: Cool
```

View File

@ -1,5 +1,19 @@
# Integrations
## Recommendations
### File Extension
Applications that support mermaid files [SHOULD](https://datatracker.ietf.org/doc/html/rfc2119#section-3) use `.mermaid` or `.mmd` file extensions.
### MIME Type
The recommended [MIME type](https://www.iana.org/assignments/media-types/media-types.xhtml) for mermaid media is `text/vnd.mermaid`.
[IANA](https://www.iana.org/) recognition pending.
---
The following list is a compilation of different integrations and plugins that allow the rendering of mermaid definitions within other applications.
They also serve as proof of concept, for the variety of things that can be built with mermaid.
@ -46,7 +60,7 @@ They also serve as proof of concept, for the variety of things that can be built
## Blogs
- [Wordpress](https://wordpress.org)
- [WordPress](https://wordpress.org)
- [WordPress Markdown Editor](https://wordpress.org/plugins/wp-githuber-md)
- [WP-ReliableMD](https://wordpress.org/plugins/wp-reliablemd/)
- [Hexo](https://hexo.io)
@ -64,7 +78,7 @@ They also serve as proof of concept, for the variety of things that can be built
- [Plugin for Mermaid.js](https://github.com/eFrane/vuepress-plugin-mermaidjs)
- [Grav CMS](https://getgrav.org/)
- [Mermaid Diagrams](https://github.com/DanielFlaum/grav-plugin-mermaid-diagrams)
- [Gitlab Markdown Adapter](https://github.com/Goutte/grav-plugin-gitlab-markdown-adapter)
- [GitLab Markdown Adapter](https://github.com/Goutte/grav-plugin-gitlab-markdown-adapter)
## Communication
@ -84,7 +98,7 @@ They also serve as proof of concept, for the variety of things that can be built
- [Flex Diagrams Extension](https://www.mediawiki.org/wiki/Extension:Flex_Diagrams)
- [Semantic Media Wiki](https://semantic-mediawiki.org)
- [Mermaid Plugin](https://github.com/SemanticMediaWiki/Mermaid)
- [FosWiki](https://foswiki.org)
- [Foswiki](https://foswiki.org)
- [Mermaid Plugin](https://foswiki.org/Extensions/MermaidPlugin)
- [DokuWiki](https://dokuwiki.org)
- [Mermaid Plugin](https://www.dokuwiki.org/plugin:mermaid)
@ -141,6 +155,8 @@ They also serve as proof of concept, for the variety of things that can be built
- [Nano Mermaid](https://github.com/Yash-Singh1/nano-mermaid)
- [CKEditor](https://github.com/ckeditor/ckeditor5)
- [CKEditor 5 Mermaid plugin](https://github.com/ckeditor/ckeditor5-mermaid)
- [Standard Notes](https://standardnotes.com/)
- [sn-mermaid](https://github.com/nienow/sn-mermaid)
## Document Generation
@ -152,7 +168,7 @@ They also serve as proof of concept, for the variety of things that can be built
- [rehype-mermaidjs](https://github.com/remcohaszing/rehype-mermaidjs)
- [Gatsby](https://www.gatsbyjs.com/)
- [gatsby-remark-mermaid](https://github.com/remcohaszing/gatsby-remark-mermaid)
- [jSDoc](https://jsdoc.app/)
- [JSDoc](https://jsdoc.app/)
- [jsdoc-mermaid](https://github.com/Jellyvision/jsdoc-mermaid)
- [MkDocs](https://www.mkdocs.org)
- [mkdocs-mermaid2-plugin](https://github.com/fralau/mkdocs-mermaid2-plugin)

View File

@ -1,7 +1,7 @@
# Announcements
## [Bad documentation is bad for developers](https://www.mermaidchart.com/blog/posts/bad-documentation-is-bad-for-developers)
## [subhash-halder contributed quadrant charts so you can show your manager what to select - just like the strategy consultants at BCG do](https://www.mermaidchart.com/blog/posts/subhash-halder-contributed-quadrant-charts-so-you-can-show-your-manager-what-to-select-just-like-the-strategy-consultants-at-bcg-do/)
26 April 2023 · 11 mins
8 June 2023 · 7 mins
Documentation tends to be bad because companies and projects dont fully realize the costs of bad documentation.
A quadrant chart is a useful diagram that helps users visualize data and identify patterns in a data set.

View File

@ -1,5 +1,11 @@
# Blog
## [subhash-halder contributed quadrant charts so you can show your manager what to select - just like the strategy consultants at BCG do](https://www.mermaidchart.com/blog/posts/subhash-halder-contributed-quadrant-charts-so-you-can-show-your-manager-what-to-select-just-like-the-strategy-consultants-at-bcg-do/)
8 June 2023 · 7 mins
A quadrant chart is a useful diagram that helps users visualize data and identify patterns in a data set.
## [Bad documentation is bad for developers](https://www.mermaidchart.com/blog/posts/bad-documentation-is-bad-for-developers)
26 April 2023 · 11 mins

View File

@ -20,17 +20,17 @@
},
"devDependencies": {
"@iconify-json/carbon": "^1.1.16",
"@unocss/reset": "^0.52.0",
"@vite-pwa/vitepress": "^0.0.5",
"@unocss/reset": "^0.53.0",
"@vite-pwa/vitepress": "^0.2.0",
"@vitejs/plugin-vue": "^4.2.1",
"fast-glob": "^3.2.12",
"https-localhost": "^4.7.1",
"pathe": "^1.1.0",
"unocss": "^0.52.0",
"unplugin-vue-components": "^0.24.1",
"unocss": "^0.53.0",
"unplugin-vue-components": "^0.25.0",
"vite": "^4.3.3",
"vite-plugin-pwa": "^0.15.0",
"vitepress": "1.0.0-beta.1",
"workbox-window": "^6.5.4"
"vite-plugin-pwa": "^0.16.0",
"vitepress": "1.0.0-beta.3",
"workbox-window": "^7.0.0"
}
}

View File

@ -25,6 +25,10 @@ flowchart LR
The id is what is displayed in the box.
```
```tip
Instead of `flowchart` one can also use `graph`.
```
### A node with text
It is also possible to set text in the box that differs from the id. If this is done several times, it is the last text
@ -494,7 +498,11 @@ This feature is applicable to node labels, edge labels, and subgraph labels.
## Interaction
It is possible to bind a click event to a node, the click can lead to either a javascript callback or to a link which will be opened in a new browser tab. **Note**: This functionality is disabled when using `securityLevel='strict'` and enabled when using `securityLevel='loose'`.
It is possible to bind a click event to a node, the click can lead to either a javascript callback or to a link which will be opened in a new browser tab.
```note
This functionality is disabled when using `securityLevel='strict'` and enabled when using `securityLevel='loose'`.
```
```
click nodeId callback
@ -597,6 +605,12 @@ In the example below the style defined in the linkStyle statement will belong to
linkStyle 3 stroke:#ff3,stroke-width:4px,color:red;
```
It is also possible to add style to multiple links in a single statement, by separating link numbers with commas:
```
linkStyle 1,2,7 color:blue;
```
### Styling line curves
It is possible to style the type of curve used for lines between items, if the default method does not meet your needs.
@ -630,12 +644,18 @@ flowchart LR
More convenient than defining the style every time is to define a class of styles and attach this class to the nodes that
should have a different look.
a class definition looks like the example below:
A class definition looks like the example below:
```
classDef className fill:#f9f,stroke:#333,stroke-width:4px;
```
Also, it is possible to define style to multiple classes in one statement:
```
classDef firstClassName,secondClassName font-size:12pt;
```
Attachment of a class to a node is done as per below:
```
@ -737,7 +757,9 @@ You can change the renderer to elk by adding this directive:
%%{init: {"flowchart": {"defaultRenderer": "elk"}} }%%
```
```note
Note that the site needs to use mermaid version 9.4+ for this to work and have this featured enabled in the lazy-loading configuration.
```
### Width

View File

@ -133,6 +133,6 @@ quadrantChart
y-axis Not Important --> "Important ❤"
quadrant-1 Plan
quadrant-2 Do
quadrant-3 Deligate
quadrant-3 Delegate
quadrant-4 Delete
```

Some files were not shown because too many files have changed in this diff Show More