Merge branch 'next' into pr/Yokozuna59/4751

* next: (70 commits)
  chore: Add comment for `yy`.
  chore: Increase heap size when building
  chore: increase `test-util.ts` converage by returning `undefined`
  chore: add `vitest` imports to `test-util.ts`
  chore: run `pnpm lint:fix`
  create `noErrorsOrAlternatives` parser helper function
  chore: export `InfoModule` from `infoModule.ts`
  docs: Fix link
  Update docs
  fix(pie): align slices and legend orders
  Mermaid version v10.4.0
  unique batches every time, if not repeated tests end up in the same batch
  Added missed .md
  Increase JS heap
  More tests for redirects + prettier
  Fixed redirects inside vitepress, extended tests
  chore: Explain redirect.ts clearly
  docs: Fix npmjs link
  chore: Update editor.bash to build latest version
  chore: Build after clone
  ...
This commit is contained in:
Sidharth Vinod 2023-08-28 14:13:20 +05:30
commit 258dbf30e0
No known key found for this signature in database
GPG Key ID: FB5CCD378D3907CD
128 changed files with 2240 additions and 1739 deletions

View File

@ -1,5 +1,5 @@
import { execSync } from 'child_process';
import { generate } from 'langium-cli';
export function generateLangium() {
execSync(`pnpm --prefix ${process.cwd()}/packages/parser exec langium generate`);
export async function generateLangium() {
await generate({ file: `./packages/parser/langium-config.json` });
}

9
.build/langium-cli.d.ts vendored Normal file
View File

@ -0,0 +1,9 @@
declare module 'langium-cli' {
export interface GenerateOptions {
file?: string;
mode?: 'development' | 'production';
watch?: boolean;
}
export function generate(options: GenerateOptions): Promise<boolean>;
}

View File

@ -53,9 +53,10 @@ const handler = (e) => {
};
const main = async () => {
generateLangium();
await generateLangium();
await mkdir('stats').catch(() => {});
const packageNames = Object.keys(packageOptions) as (keyof typeof packageOptions)[];
// it should build `parser` before `mermaid` because it's a dependecy
for (const pkg of packageNames) {
await buildPackage(pkg).catch(handler);
}

View File

@ -79,7 +79,7 @@ function sendEventsToAll() {
}
async function createServer() {
generateLangium();
await generateLangium();
handleFileChange();
const app = express();
chokidar
@ -93,7 +93,7 @@ async function createServer() {
return;
}
if (/\.langium$/.test(path)) {
generateLangium();
await generateLangium();
}
console.log(`${path} changed. Rebuilding...`);
handleFileChange();

View File

@ -48,6 +48,7 @@ module.exports = {
'no-prototype-builtins': 'off',
'no-unused-vars': 'off',
'cypress/no-async-tests': 'off',
'@typescript-eslint/consistent-type-imports': 'error',
'@typescript-eslint/no-floating-promises': 'error',
'@typescript-eslint/no-misused-promises': 'error',
'@typescript-eslint/ban-ts-comment': [

View File

@ -1,14 +1,27 @@
name-template: '$NEXT_PATCH_VERSION'
tag-template: '$NEXT_PATCH_VERSION'
categories:
- title: '🚨 **Breaking Changes**'
labels:
- 'Breaking Change'
- title: '🚀 Features'
labels:
- 'Type: Enhancement'
- 'feature' # deprecated, new PRs shouldn't have this
- title: '🐛 Bug Fixes'
labels:
- 'Type: Bug / Error'
- 'fix' # deprecated, new PRs shouldn't have this
- title: '🧰 Maintenance'
label: 'Type: Other'
labels:
- 'Type: Other'
- 'chore' # deprecated, new PRs shouldn't have this
- title: '⚡️ Performance'
labels:
- 'Type: Performance'
- title: '📚 Documentation'
labels:
- 'Area: Documentation'
change-template: '- $TITLE (#$NUMBER) @$AUTHOR'
sort-by: title
sort-direction: ascending

View File

@ -62,8 +62,22 @@ jobs:
ERROR_MESSAGE+=' `pnpm run --filter mermaid types:build-config`'
ERROR_MESSAGE+=' on your local machine.'
echo "::error title=Lint failure::${ERROR_MESSAGE}"
# make sure to return an error exitcode so that GitHub actions shows a red-cross
exit 1
# make sure to return an error exitcode so that GitHub actions shows a red-cross
exit 1
fi
- name: Verify no circular dependencies
working-directory: ./packages/mermaid
shell: bash
run: |
if ! pnpm run --filter mermaid checkCircle; then
ERROR_MESSAGE='Circular dependency detected.'
ERROR_MESSAGE+=' This should be fixed by removing the circular dependency.'
ERROR_MESSAGE+=' Run `pnpm run --filter mermaid checkCircle` on your local machine'
ERROR_MESSAGE+=' to see the circular dependency.'
echo "::error title=Lint failure::${ERROR_MESSAGE}"
# make sure to return an error exitcode so that GitHub actions shows a red-cross
exit 1
fi
- name: Verify Docs

View File

@ -114,7 +114,7 @@ const main = async () => {
}
};
generateLangium();
await generateLangium();
if (watch) {
await build(getBuildConfig({ minify: false, watch, core: false, entryName: 'parser' }));

View File

@ -60,7 +60,7 @@ Use Mermaid with your favorite applications, check out the list of [Integrations
You can also use Mermaid within [GitHub](https://github.blog/2022-02-14-include-diagrams-markdown-files-mermaid/) as well many of your other favorite applications—check out the list of [Integrations and Usages of Mermaid](./docs/ecosystem/integrations.md).
For a more detailed introduction to Mermaid and some of its more basic uses, look to the [Beginner's Guide](./docs/community/n00b-overview.md), [Usage](./docs/config/usage.md) and [Tutorials](./docs/config/Tutorials.md).
For a more detailed introduction to Mermaid and some of its more basic uses, look to the [Beginner's Guide](./docs/intro/getting-started.md), [Usage](./docs/config/usage.md) and [Tutorials](./docs/config/Tutorials.md).
In our release process we rely heavily on visual regression tests using [applitools](https://applitools.com/). Applitools is a great service which has been easy to use and integrate with our tests.

View File

@ -55,7 +55,7 @@ Mermaid 通过允许用户创建便于修改的图表来解决这一难题,它
Mermaid 甚至能让非程序员也能通过 [Mermaid Live Editor](https://mermaid.live/) 轻松创建详细的图表。<br/>
你可以访问 [教程](./docs/config/Tutorials.md) 来查看 Live Editor 的视频教程,也可以查看 [Mermaid 的集成和使用](./docs/ecosystem/integrations.md) 这个清单来检查你的文档工具是否已经集成了 Mermaid 支持。
如果想要查看关于 Mermaid 更详细的介绍及基础使用方式,可以查看 [入门指引](./docs/community/n00b-overview.md), [用法](./docs/config/usage.md) 和 [教程](./docs/config/Tutorials.md).
如果想要查看关于 Mermaid 更详细的介绍及基础使用方式,可以查看 [入门指引](./docs/intro/getting-started.md), [用法](./docs/config/usage.md) 和 [教程](./docs/config/Tutorials.md).
<!-- </Main description> -->

View File

@ -44,6 +44,7 @@
"faber",
"flatmap",
"foswiki",
"frontmatter",
"ftplugin",
"gantt",
"gitea",
@ -94,6 +95,7 @@
"nextra",
"nikolay",
"nirname",
"npmjs",
"orlandoni",
"outdir",
"pathe",
@ -110,6 +112,7 @@
"rects",
"reda",
"redmine",
"regexes",
"rehype",
"roledescription",
"rozhkov",
@ -155,7 +158,8 @@
"xlink",
"yash",
"yokozuna",
"zenuml"
"zenuml",
"zune"
],
"patterns": [
{ "name": "Markdown links", "pattern": "\\((.*)\\)", "description": "" },

View File

@ -18,7 +18,11 @@ const utf8ToB64 = (str: string): string => {
return Buffer.from(decodeURIComponent(encodeURIComponent(str))).toString('base64');
};
const batchId: string = 'mermaid-batch-' + Cypress.env('CYPRESS_COMMIT') || Date.now().toString();
const batchId: string =
'mermaid-batch-' +
(Cypress.env('useAppli')
? Date.now().toString()
: Cypress.env('CYPRESS_COMMIT') || Date.now().toString());
export const mermaidUrl = (
graphStr: string,

View File

@ -14,7 +14,6 @@ describe('Configuration and directives - nodes should be light blue', () => {
`,
{}
);
cy.get('svg');
});
it('Settings from initialize - nodes should be green', () => {
imgSnapshotTest(
@ -28,7 +27,6 @@ graph TD
end `,
{ theme: 'forest' }
);
cy.get('svg');
});
it('Settings from initialize overriding themeVariable - nodes should be red', () => {
imgSnapshotTest(
@ -46,7 +44,6 @@ graph TD
`,
{ theme: 'base', themeVariables: { primaryColor: '#ff0000' }, logLevel: 0 }
);
cy.get('svg');
});
it('Settings from directive - nodes should be grey', () => {
imgSnapshotTest(
@ -62,7 +59,24 @@ graph TD
`,
{}
);
cy.get('svg');
});
it('Settings from frontmatter - nodes should be grey', () => {
imgSnapshotTest(
`
---
config:
theme: neutral
---
graph TD
A(Start) --> B[/Another/]
A[/Another/] --> C[End]
subgraph section
B
C
end
`,
{}
);
});
it('Settings from directive overriding theme variable - nodes should be red', () => {
@ -79,7 +93,6 @@ graph TD
`,
{}
);
cy.get('svg');
});
it('Settings from initialize and directive - nodes should be grey', () => {
imgSnapshotTest(
@ -95,7 +108,6 @@ graph TD
`,
{ theme: 'forest' }
);
cy.get('svg');
});
it('Theme from initialize, directive overriding theme variable - nodes should be red', () => {
imgSnapshotTest(
@ -111,8 +123,71 @@ graph TD
`,
{ theme: 'base' }
);
cy.get('svg');
});
it('Theme from initialize, frontmatter overriding theme variable - nodes should be red', () => {
imgSnapshotTest(
`
---
config:
theme: base
themeVariables:
primaryColor: '#ff0000'
---
graph TD
A(Start) --> B[/Another/]
A[/Another/] --> C[End]
subgraph section
B
C
end
`,
{ theme: 'forest' }
);
});
it('Theme from initialize, frontmatter overriding theme variable, directive overriding primaryColor - nodes should be red', () => {
imgSnapshotTest(
`
---
config:
theme: base
themeVariables:
primaryColor: '#00ff00'
---
%%{init: {'theme': 'base', 'themeVariables':{ 'primaryColor': '#ff0000'}}}%%
graph TD
A(Start) --> B[/Another/]
A[/Another/] --> C[End]
subgraph section
B
C
end
`,
{ theme: 'forest' }
);
});
it('should render if values are not quoted properly', () => {
// #ff0000 is not quoted properly, and will evaluate to null.
// This test ensures that the rendering still works.
imgSnapshotTest(
`---
config:
theme: base
themeVariables:
primaryColor: #ff0000
---
graph TD
A(Start) --> B[/Another/]
A[/Another/] --> C[End]
subgraph section
B
C
end
`,
{ theme: 'forest' }
);
});
it('Theme variable from initialize, theme from directive - nodes should be red', () => {
imgSnapshotTest(
`
@ -127,13 +202,11 @@ graph TD
`,
{ themeVariables: { primaryColor: '#ff0000' } }
);
cy.get('svg');
});
describe('when rendering several diagrams', () => {
it('diagrams should not taint later diagrams', () => {
const url = 'http://localhost:9000/theme-directives.html';
cy.visit(url);
cy.get('svg');
cy.matchImageSnapshot('conf-and-directives.spec-when-rendering-several-diagrams-diagram-1');
});
});

View File

@ -305,4 +305,21 @@ ORDER ||--|{ LINE-ITEM : contains
{}
);
});
it('should render entities with entity name aliases', () => {
imgSnapshotTest(
`
erDiagram
p[Person] {
varchar(64) firstName
varchar(64) lastName
}
c["Customer Account"] {
varchar(128) email
}
p ||--o| c : has
`,
{ logLevel: 1 }
);
});
});

View File

@ -21,6 +21,8 @@
<pre class="mermaid">
---
title: This is a title
config:
theme: forest
---
erDiagram
%% title This is a title
@ -108,6 +110,20 @@
}
MANUFACTURER only one to zero or more CAR : makes
</pre>
<hr />
<pre class="mermaid">
erDiagram
p[Person] {
string firstName
string lastName
}
a["Customer Account"] {
string email
}
p ||--o| a : has
</pre>
<hr />
<script type="module">
import mermaid from './mermaid.esm.mjs';

View File

@ -123,6 +123,13 @@
<h3>flowchart</h3>
<pre class="mermaid">
---
title: This is another complicated flow
config:
theme: base
flowchart:
curve: cardinal
---
flowchart LR
sid-B3655226-6C29-4D00-B685-3D5C734DC7E1["

View File

@ -3,20 +3,42 @@
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>States Mermaid Quick Test Page</title>
<title>Sankey Mermaid Quick Test Page</title>
<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgo=" />
<style>
div.mermaid {
/* font-family: 'trebuchet ms', verdana, arial; */
font-family: 'Courier New', Courier, monospace !important;
}
</style>
</head>
<body>
<h1>Sankey diagram demos</h1>
<h2>FY20-21 Performance</h2>
<pre class="mermaid">
---
config:
sankey:
showValues: true
prefix: $
suffix: B
width: 800
nodeAlignment: left
---
sankey-beta
Revenue,Expenses,10
Revenue,Profit,10
Expenses,Manufacturing,5
Expenses,Tax,3
Expenses,Research,2
</pre>
<h2>Energy flow</h2>
<pre class="mermaid">
---
config:
sankey:
showValues: false
width: 1200
height: 600
linkColor: gradient
nodeAlignment: justify
---
sankey-beta
Agricultural 'waste',Bio-conversion,124.729
@ -95,13 +117,7 @@
theme: 'default',
logLevel: 3,
securityLevel: 'loose',
sankey: {
title: 'Hey, this is Sankey-Beta',
width: 1200,
height: 600,
linkColor: 'gradient',
nodeAlignment: 'justify',
},
startOnLoad: true,
});
</script>
</body>

View File

@ -5,9 +5,9 @@ services:
stdin_open: true
tty: true
working_dir: /mermaid
mem_limit: '2G'
mem_limit: '4G'
environment:
- NODE_OPTIONS=--max_old_space_size=2048
- NODE_OPTIONS=--max_old_space_size=4096
volumes:
- ./:/mermaid
- root_cache:/root/.cache
@ -17,7 +17,7 @@ services:
- 9000:9000
- 3333:3333
cypress:
image: cypress/included:12.17.3
image: cypress/included:12.17.4
stdin_open: true
tty: true
working_dir: /mermaid

176
docs/community/code.md Normal file
View File

@ -0,0 +1,176 @@
> **Warning**
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/community/code.md](../../packages/mermaid/src/docs/community/code.md).
# Contributing Code
The basic steps for contributing code are:
```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]
```
```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]
```
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.
## 1. Checkout a git branch
Mermaid uses a [Git Flow](https://guides.github.com/introduction/flow/)inspired approach to branching.
Development is done in the `develop` branch.
Once development is done we create a `release/vX.X.X` branch from `develop` for testing.
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.
**All new work should be based on the `develop` branch.**
**When you are ready to do work, always, ALWAYS:**
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.
We use the follow naming convention for branches:
```txt
[feature | bug | chore | docs]/[issue number]_[short description using dashes ('-') or underscores ('_') instead of spaces]
```
You can always check current [configuration of labelling and branch prefixes](https://github.com/mermaid-js/mermaid/blob/develop/.github/pr-labeler.yml)
- 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)
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.
**Ex: A new feature described in issue 2945 that adds a new arrow type called 'florbs' to state diagrams**
`feature/2945_state-diagram-new-arrow-florbs`
**Ex: A bug described in issue 1123 that causes random ugly red text in multiple diagram types**
`bug/1123_fix_random_ugly_red_text`
## 2. Write 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).
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 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.
When running in CI it will take a snapshot of the rendered diagram and compare it with the snapshot from last build and flag it for review if it differs.
This is what a rendering test looks like:
```js
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');
});
```
**_\[TODO - running the tests against what is expected in development. ]_**
**_\[TODO - how to generate new screenshots]_**
....
## 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!
If you are adding a new feature, add `(v<MERMAID_RELEASE_VERSION>+)` in the title or description. It will be replaced automatically with the current version number when the release happens.
eg: `# Feature Name (v<MERMAID_RELEASE_VERSION>+)`
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.**

View File

@ -6,15 +6,9 @@
# 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)
---
> The following documentation describes how to work with Mermaid in your host environment.
> There's also a [Docker installation guide](../community/docker-development.md)
> if you prefer to work in a Docker environment.
So you want to help? That's great!
@ -22,47 +16,68 @@ So you want to help? That's great!
Here are a few things to get you started on the right path.
## Technical Requirements and Setup
## Get the Source Code
### Technical Requirements
In GitHub, you first **fork** a repository when you are going to make changes and submit pull requests.
These are the tools we use for working with the code and documentation.
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.
[Fork mermaid](https://github.com/mermaid-js/mermaid/fork) to start contributing to the main project and its documentaion, or [search for other repositories](https://github.com/orgs/mermaid-js/repositories).
[Here is a GitHub document that gives an overview of the process.](https://docs.github.com/en/get-started/quickstart/fork-a-repo)
## Technical Requirements
> The following documentation describes how to work with Mermaid in your host environment.
> There's also a [Docker installation guide](../community/docker-development.md)
> if you prefer to work in a Docker environment.
These are the tools we use for working with the code and documentation:
- [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)
- [npx](https://docs.npmjs.com/cli/v8/commands/npx) the packaged executor in npm. This is needed [to install pnpm.](#install-packages)
Follow [the setup steps below](#setup) to install them and verify they are working
Follow the setup steps below to install them and start the development.
### Setup
## Setup and Launch
Follow these steps to set up the environment you need to work on code and/or documentation.
### Switch to project
#### 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:
Once you have cloned the repository onto your development machine, change into the `mermaid` project folder (the top level directory of the mermaid project repository)
```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
### Install packages
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:
Run `npx pnpm install`. You will need `npx` for this because volta doesn't support it yet.
```bash
npx pnpm install # npx is required for first install
```
### Launch
```bash
npx pnpm run dev
```
Now you are ready to make your changes! Edit whichever files in `src` as required.
Open <http://localhost:9000> in your browser, after starting the dev server.
There is a list of demos that can be used to see and test your changes.
If you need a specific diagram, you can duplicate the `example.html` file in `/demos/dev` and add your own mermaid code to your copy.
That will be served at <http://localhost:9000/dev/your-file-name.html>.
After making code changes, the dev server will rebuild the mermaid library. You will need to reload the browser page yourself to see the changes. (PRs for auto reload are welcome!)
## Verify Everything is Working
You can run the `test` script to verify that pnpm is working _and_ that the repository has been cloned correctly:
```bash
pnpm test
@ -70,321 +85,7 @@ 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.)
#### 4. Make your changes
Now you are ready to make your changes!
Edit whichever files in `src` as required.
#### 5. See your changes
Open <http://localhost:9000> in your browser, after starting the dev server.
There is a list of demos that can be used to see and test your changes.
If you need a specific diagram, you can duplicate the `example.html` file in `/demos/dev` and add your own mermaid code to your copy.
That will be served at <http://localhost:9000/dev/your-file-name.html>.
After making code changes, the dev server will rebuild the mermaid library. You will need to reload the browser page yourself to see the changes. (PRs for auto reload are welcome!)
### 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
The basic steps for contributing code are:
```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]
```
```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]
```
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.
### 1. Checkout a git branch
Mermaid uses a [Git Flow](https://guides.github.com/introduction/flow/)inspired approach to branching.
Development is done in the `develop` branch.
Once development is done we create a `release/vX.X.X` branch from `develop` for testing.
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.
**All new work should be based on the `develop` branch.**
**When you are ready to do work, always, ALWAYS:**
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.
We use the follow naming convention for branches:
```text
[feature | bug | chore | docs]/[issue number]_[short description using dashes ('-') or underscores ('_') instead of spaces]
```
- 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)
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.
**Ex: A new feature described in issue 2945 that adds a new arrow type called 'florbs' to state diagrams**
`feature/2945_state-diagram-new-arrow-florbs`
**Ex: A bug described in issue 1123 that causes random ugly red text in multiple diagram types**
`bug/1123_fix_random_ugly_red_text`
### 2. Write 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).
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 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.
When running in CI it will take a snapshot of the rendered diagram and compare it with the snapshot from last build and flag it for review if it differs.
This is what a rendering test looks like:
```js
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');
});
```
**_\[TODO - running the tests against what is expected in development. ]_**
**_\[TODO - how to generate new screenshots]_**
....
### 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!
If you are adding a new feature, add `(v<MERMAID_RELEASE_VERSION>+)` in the title or description. It will be replaced automatically with the current version number when the release happens.
eg: `# Feature Name (v<MERMAID_RELEASE_VERSION>+)`
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:
_\[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) 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
All tests should run successfully without any errors or failures. (You might see _lint_ or _formatting_ warnings; those are ok during this step.)
## Last Words

View File

@ -0,0 +1,109 @@
> **Warning**
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/community/docker-development.md](../../packages/mermaid/src/docs/community/docker-development.md).
# Contributing to Mermaid via Docker
> The following documentation describes how to work with Mermaid in a Docker environment.
> There's also a [host installation guide](../community/development.md)
> if you prefer to work without a Docker environment.
So you want to help? That's great!
![Image of happy people jumping with excitement](https://media.giphy.com/media/BlVnrxJgTGsUw/giphy.gif)
Here are a few things to get you started on the right path.
## Get the Source Code
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.
[Fork mermaid](https://github.com/mermaid-js/mermaid/fork) to start contributing to the main project and its documentaion, or [search for other repositories](https://github.com/orgs/mermaid-js/repositories).
[Here is a GitHub document that gives an overview of the process.](https://docs.github.com/en/get-started/quickstart/fork-a-repo)
## Technical Requirements
> The following documentation describes how to work with Mermaid in a Docker environment.
> There's also a [host installation guide](../community/development.md)
> if you prefer to work without a Docker environment.
[Install Docker](https://docs.docker.com/engine/install/). And that is pretty much all you need.
Optionally, to run GUI (Cypress) within Docker you will also need an X11 server installed.
You might already have it installed, so check this by running:
```bash
echo $DISPLAY
```
If the `$DISPLAY` variable is not empty, then an X11 server is running. Otherwise you may need to install one.
## Setup and Launch
### Switch to project
Once you have cloned the repository onto your development machine, change into the `mermaid` project folder (the top level directory of the mermaid project repository)
```bash
cd mermaid
```
### Make `./run` executable
For development using Docker there is a self-documented `run` bash script, which provides convenient aliases for `docker compose` commands.
Ensure `./run` script is executable:
```bash
chmod +x run
```
> **💡 Tip**
> To get detailed help simply type `./run` or `./run help`.
>
> It also has short _Development quick start guide_ embedded.
### Install packages
```bash
./run pnpm install # Install packages
```
### Launch
```bash
./run dev
```
Now you are ready to make your changes! Edit whichever files in `src` as required.
Open <http://localhost:9000> in your browser, after starting the dev server.
There is a list of demos that can be used to see and test your changes.
If you need a specific diagram, you can duplicate the `example.html` file in `/demos/dev` and add your own mermaid code to your copy.
That will be served at <http://localhost:9000/dev/your-file-name.html>.
After making code changes, the dev server will rebuild the mermaid library. You will need to reload the browser page yourself to see the changes. (PRs for auto reload are welcome!)
## Verify Everything is Working
```bash
./run 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.)
## 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)
![Image of superhero wishing you good luck](https://media.giphy.com/media/l49JHz7kJvl6MCj3G/giphy.gif)

View File

@ -0,0 +1,105 @@
> **Warning**
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/community/documentation.md](../../packages/mermaid/src/docs/community/documentation.md).
# 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.
````markdown
```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. In that case, your branch should be based on master, not develop.
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:
_\[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 from the branch 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) 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).

View File

@ -1,74 +0,0 @@
> **Warning**
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/community/n00b-overview.md](../../packages/mermaid/src/docs/community/n00b-overview.md).
# Overview for Beginners
**Explaining with a Diagram**
A picture is worth a thousand words, a good diagram is undoubtedly worth more. They make understanding easier.
## Creating and Maintaining Diagrams
Anyone who has used Visio, or (God Forbid) Excel to make a Gantt Chart, knows how hard it is to create, edit and maintain good visualizations.
Diagrams/Charts are significant but also become obsolete/inaccurate very fast. This catch-22 hobbles the productivity of teams.
# Doc Rot in Diagrams
Doc-Rot kills diagrams as quickly as it does text, but it takes hours in a desktop application to produce a diagram.
Mermaid seeks to change using markdown-inspired syntax. The process is a quicker, less complicated, and more convenient way of going from concept to visualization.
It is a relatively straightforward solution to a significant hurdle with the software teams.
# Definition of Terms/ Dictionary
**Mermaid text definitions can be saved for later reuse and editing.**
> These are the Mermaid diagram definitions inside `<div>` tags, with the `class=mermaid`.
```html
<pre class="mermaid">
graph TD
A[Client] --> B[Load Balancer]
B --> C[Server01]
B --> D[Server02]
</pre>
```
**render**
> This is the core function of the Mermaid API. It reads all the `Mermaid Definitions` inside `div` tags and returns an SVG file, based on the definition.
**Nodes**
> These are the boxes that contain text or otherwise discrete pieces of each diagram, separated generally by arrows, except for Gantt Charts and User Journey Diagrams. They will be referred often in the instructions. Read for Diagram Specific [Syntax](../intro/n00b-syntaxReference.md)
## Advantages of using Mermaid
- Ease to generate, modify and render diagrams when you make them.
- The number of integrations and plugins it has.
- You can add it to your or companies website.
- Diagrams can be created through comments like this in a script:
## The catch-22 of Diagrams and Charts:
**Diagramming and charting is a large waste of developer's time, but not having diagrams ruins productivity.**
Mermaid solves this by reducing the time and effort required to create diagrams and charts.
Because, the text base for the diagrams allows it to be updated easily. Also, it can be made part of production scripts (and other pieces of code). So less time is spent on documenting, as a separate task.
## Catching up with Development
Being based on markdown, Mermaid can be used, not only by accomplished front-end developers, but by most computer savvy people to render diagrams, at much faster speeds.
In fact one can pick up the syntax for it quite easily from the examples given and there are many tutorials available in the internet.
## Mermaid is for everyone.
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

@ -0,0 +1,26 @@
> **Warning**
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/community/questions-and-suggestions.md](../../packages/mermaid/src/docs/community/questions-and-suggestions.md).
# Questions or Suggestions?
**_\[TODO: This section is still a WIP. It still needs MAJOR revision.]_**
## 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).

View File

@ -32,7 +32,7 @@ The definitions that can be generated the Live-Editor are also backwards-compati
## Mermaid with HTML
Examples are provided in [Getting Started](../intro/n00b-gettingStarted.md)
Examples are provided in [Getting Started](../intro/getting-started.md)
**CodePen Examples:**

View File

@ -2,9 +2,9 @@
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/config/n00b-advanced.md](../../packages/mermaid/src/docs/config/n00b-advanced.md).
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/config/advanced.md](../../packages/mermaid/src/docs/config/advanced.md).
# Advanced n00b mermaid (Coming soon..)
# Advanced mermaid (Coming soon..)
## splitting mermaid code from html

View File

@ -10,10 +10,41 @@ When mermaid starts, configuration is extracted to determine a configuration to
- The default configuration
- Overrides at the site level are set by the initialize call, and will be applied to all diagrams in the site/app. The term for this is the **siteConfig**.
- Directives - diagram authors can update select configuration parameters directly in the diagram code via directives. These are applied to the render config.
- Frontmatter (v\<MERMAID_RELEASE_VERSION>+) - diagram authors can update select configuration parameters in the frontmatter of the diagram. These are applied to the render config.
- Directives (Deprecated by Frontmatter) - diagram authors can update select configuration parameters directly in the diagram code via directives. These are applied to the render config.
**The render config** is configuration that is used when rendering by applying these configurations.
## Frontmatter config
The entire mermaid configuration (except the secure configs) can be overridden by the diagram author in the frontmatter of the diagram. The frontmatter is a YAML block at the top of the diagram.
```mermaid-example
---
title: Hello Title
config:
theme: base
themeVariables:
primaryColor: "#00ff00"
---
flowchart
Hello --> World
```
```mermaid
---
title: Hello Title
config:
theme: base
themeVariables:
primaryColor: "#00ff00"
---
flowchart
Hello --> World
```
## Theme configuration
## Starting mermaid

View File

@ -6,6 +6,9 @@
# Directives
> **Warning**
> Directives are deprecated from v\<MERMAID_RELEASE_VERSION>. Please use the `config` key in frontmatter to pass configuration. See [Configuration](./configuration.md) for more details.
## Directives
Directives give a diagram author the capability to alter the appearance of a diagram before rendering by changing the applied configuration.

View File

@ -16,4 +16,4 @@
#### Defined in
[mermaidAPI.ts:77](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L77)
[mermaidAPI.ts:78](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L78)

View File

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

View File

@ -14,7 +14,7 @@
#### Defined in
[config.ts:7](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L7)
[config.ts:8](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L8)
## Functions
@ -26,9 +26,9 @@ Pushes in a directive to the configuration
#### Parameters
| Name | Type | Description |
| :---------- | :---- | :----------------------- |
| `directive` | `any` | The directive to push in |
| Name | Type | Description |
| :---------- | :-------------- | :----------------------- |
| `directive` | `MermaidConfig` | The directive to push in |
#### Returns
@ -36,7 +36,7 @@ Pushes in a directive to the configuration
#### Defined in
[config.ts:191](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L191)
[config.ts:188](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L188)
---
@ -60,7 +60,7 @@ The currentConfig
#### Defined in
[config.ts:137](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L137)
[config.ts:131](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L131)
---
@ -118,7 +118,7 @@ The siteConfig
#### Defined in
[config.ts:223](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L223)
[config.ts:218](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L218)
---
@ -147,7 +147,7 @@ options in-place
#### Defined in
[config.ts:152](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L152)
[config.ts:146](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L146)
---
@ -242,10 +242,10 @@ The new siteConfig
#### Parameters
| Name | Type |
| :------------ | :-------------- |
| `siteCfg` | `MermaidConfig` |
| `_directives` | `any`\[] |
| Name | Type |
| :------------ | :----------------- |
| `siteCfg` | `MermaidConfig` |
| `_directives` | `MermaidConfig`\[] |
#### Returns
@ -253,7 +253,7 @@ The new siteConfig
#### Defined in
[config.ts:14](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L14)
[config.ts:15](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L15)
---

View File

@ -10,7 +10,7 @@
### configKeys
`Const` **configKeys**: `string`\[]
`Const` **configKeys**: `Set`<`string`>
#### Defined in

View File

@ -25,7 +25,7 @@ Renames and re-exports [mermaidAPI](mermaidAPI.md#mermaidapi)
#### Defined in
[mermaidAPI.ts:81](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L81)
[mermaidAPI.ts:82](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L82)
## Variables
@ -96,7 +96,7 @@ mermaid.initialize(config);
#### Defined in
[mermaidAPI.ts:668](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L668)
[mermaidAPI.ts:673](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L673)
## 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:310](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L310)
---
@ -153,7 +153,7 @@ the cleaned up svgCode
#### Defined in
[mermaidAPI.ts:255](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L255)
[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:184](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L184)
[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:232](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L232)
[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:168](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L168)
[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:154](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L154)
[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:125](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L125)
[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:286](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L286)
[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:360](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L360)

View File

@ -41,7 +41,7 @@ pnpm add mermaid
**Hosting mermaid on a web page:**
> Note:This topic explored in greater depth in the [User Guide for Beginners](../intro/n00b-gettingStarted.md)
> Note:This topic explored in greater depth in the [User Guide for Beginners](../intro/getting-started.md)
The easiest way to integrate mermaid on a web page requires two elements:

View File

@ -2,13 +2,13 @@
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/intro/n00b-gettingStarted.md](../../packages/mermaid/src/docs/intro/n00b-gettingStarted.md).
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/intro/getting-started.md](../../packages/mermaid/src/docs/intro/getting-started.md).
# A Mermaid User-Guide for Beginners
Mermaid is composed of three parts: Deployment, Syntax and Configuration.
This section talks about the different ways to deploy Mermaid. Learning the [Syntax](n00b-syntaxReference.md) would be of great help to the beginner.
This section talks about the different ways to deploy Mermaid. Learning the [Syntax](syntax-reference.md) would be of great help to the beginner.
> Generally the live editor is enough for most general uses of mermaid, and is a good place to start learning.
@ -53,7 +53,7 @@ graph TD
In the `Code` section one can write or edit raw mermaid code, and instantly `Preview` the rendered result on the panel beside it.
The `Configuration` Section is for changing the appearance and behavior of mermaid diagrams. An easy introduction to mermaid configuration is found in the [Advanced usage](../config/n00b-advanced.md) section. A complete configuration reference cataloging the default values can be found on the [mermaidAPI](../config/setup/README.md) page.
The `Configuration` Section is for changing the appearance and behavior of mermaid diagrams. An easy introduction to mermaid configuration is found in the [Advanced usage](../config/advanced.md) section. A complete configuration reference cataloging the default values can be found on the [mermaidAPI](../config/setup/README.md) page.
![Code,Config and Preview](./img/Code-Preview-Config.png)
@ -111,9 +111,9 @@ b. The importing of mermaid library through the `mermaid.esm.mjs` or `mermaid.es
<body>
Here is a mermaid diagram:
<pre class="mermaid">
graph TD
A[Client] --> B[Load Balancer]
B --> C[Server01]
graph TD
A[Client] --> B[Load Balancer]
B --> C[Server01]
B --> D[Server02]
</pre>
</body>
@ -152,18 +152,18 @@ Rendering in Mermaid is initialized by `mermaid.initialize()` call. However, doi
<body>
Here is one mermaid diagram:
<pre class="mermaid">
graph TD
A[Client] --> B[Load Balancer]
B --> C[Server1]
graph TD
A[Client] --> B[Load Balancer]
B --> C[Server1]
B --> D[Server2]
</pre>
And here is another:
<pre class="mermaid">
graph TD
graph TD
A[Client] -->|tcp_123| B
B(Load Balancer)
B -->|tcp_456| C[Server1]
B(Load Balancer)
B -->|tcp_456| C[Server1]
B -->|tcp_456| D[Server2]
</pre>
@ -185,15 +185,15 @@ In this example mermaid.js is referenced in `src` as a separate JavaScript file,
</head>
<body>
<pre class="mermaid">
graph LR
A --- B
B-->C[fa:fa-ban forbidden]
graph LR
A --- B
B-->C[fa:fa-ban forbidden]
B-->D(fa:fa-spinner);
</pre>
<pre class="mermaid">
graph TD
A[Client] --> B[Load Balancer]
B --> C[Server1]
graph TD
A[Client] --> B[Load Balancer]
B --> C[Server1]
B --> D[Server2]
</pre>
<script type="module">

View File

@ -10,13 +10,20 @@
It is a JavaScript based diagramming and charting tool that renders Markdown-inspired text definitions to create and modify diagrams dynamically.
> If you are familiar with Markdown you should have no problem learning [Mermaid's Syntax](n00b-syntaxReference.md).
> If you are familiar with Markdown you should have no problem learning [Mermaid's Syntax](syntax-reference.md).
<img src="/header.png" alt="" />
<div class='badges'>
[![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](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid) [![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) [![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid) [![NPM](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) [![Twitter Follow](https://img.shields.io/twitter/follow/mermaidjs_?style=social)](https://twitter.com/mermaidjs_)
[![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](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid)
[![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)
[![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid)
[![NPM](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)
[![Twitter Follow](https://img.shields.io/twitter/follow/mermaidjs_?style=social)](https://twitter.com/mermaidjs_)
</div>
@ -37,7 +44,7 @@ Mermaid allows even non-programmers to easily create detailed and diagrams throu
[Tutorials](../config/Tutorials.md) has video tutorials.
Use Mermaid with your favorite applications, check out the list of [Integrations and Usages of Mermaid](../ecosystem/integrations.md).
For a more detailed introduction to Mermaid and some of its more basic uses, look to the [Beginner's Guide](../community/n00b-overview.md) and [Usage](../config/usage.md).
For a more detailed introduction to Mermaid and some of its more basic uses, look to the [Beginner's Guide](../intro/getting-started.md) and [Usage](../config/usage.md).
🌐 [CDN](https://www.jsdelivr.com/package/npm/mermaid) | 📖 [Documentation](https://mermaidjs.github.io) | 🙌 [Contribution](../community/development.md) | 🔌 [Plug-Ins](../ecosystem/integrations.md)
@ -277,9 +284,9 @@ quadrantChart
## Installation
**In depth guides and examples can be found at [Getting Started](./n00b-gettingStarted.md) and [Usage](../config/usage.md).**
**In depth guides and examples can be found at [Getting Started](./getting-started.md) and [Usage](../config/usage.md).**
**It would also be helpful to learn more about mermaid's [Syntax](./n00b-syntaxReference.md).**
**It would also be helpful to learn more about mermaid's [Syntax](./syntax-reference.md).**
### CDN
@ -338,7 +345,19 @@ Together we could continue the work with things like:
Don't hesitate to contact me if you want to get involved!
## For contributors
## Contributors
<div class='badges'>
[![Good first issue](https://img.shields.io/github/labels/mermaid-js/mermaid/Good%20first%20issue%21)](https://github.com/mermaid-js/mermaid/issues?q=is%3Aissue+is%3Aopen+label%3A%22Good+first+issue%21%22)
[![Contributors](https://img.shields.io/github/contributors/mermaid-js/mermaid)](https://github.com/mermaid-js/mermaid/graphs/contributors)
[![Commits](https://img.shields.io/github/commit-activity/m/mermaid-js/mermaid)](https://github.com/mermaid-js/mermaid/graphs/contributors)
</div>
Mermaid is a growing community and is always accepting new contributors. There's a lot of different ways to help out and we're always looking for extra hands! Look at [this issue](https://github.com/mermaid-js/mermaid/issues/866) if you want to know where to start helping out.
Detailed information about how to contribute can be found in the [contribution guideline](/community/development).
### Requirements
@ -346,7 +365,7 @@ Don't hesitate to contact me if you want to get involved!
- [Node.js](https://nodejs.org/en/). `volta install node`
- [pnpm](https://pnpm.io/) package manager. `volta install pnpm`
## Development Installation
### Development Installation
```bash
git clone git@github.com:mermaid-js/mermaid.git
@ -383,25 +402,7 @@ Update version number in `package.json`.
npm publish
```
The above command generates files into the `dist` folder and publishes them to \<npmjs.org>.
## Related projects
- [Command Line Interface](https://github.com/mermaid-js/mermaid-cli)
- [Live Editor](https://github.com/mermaid-js/mermaid-live-editor)
- [HTTP Server](https://github.com/TomWright/mermaid-server)
## Contributors
<div class='badges'>
[![Good first issue](https://img.shields.io/github/labels/mermaid-js/mermaid/Good%20first%20issue%21)](https://github.com/mermaid-js/mermaid/issues?q=is%3Aissue+is%3Aopen+label%3A%22Good+first+issue%21%22) [![Contributors](https://img.shields.io/github/contributors/mermaid-js/mermaid)](https://github.com/mermaid-js/mermaid/graphs/contributors) [![Commits](https://img.shields.io/github/commit-activity/m/mermaid-js/mermaid)](https://github.com/mermaid-js/mermaid/graphs/contributors)
</div>
Mermaid is a growing community and is always accepting new contributors. There's a lot of different ways to help out and we're always looking for extra hands! Look at [this issue](https://github.com/mermaid-js/mermaid/issues/866) if you want to know where to start helping out.
Detailed information about how to contribute can be found in the [contribution guide](https://github.com/mermaid-js/mermaid/blob/develop/CONTRIBUTING.md)
The above command generates files into the `dist` folder and publishes them to [npmjs.com](https://www.npmjs.com/).
## Security and safe diagrams
@ -435,6 +436,7 @@ _Mermaid was created by Knut Sveidqvist for easier documentation._
.badges > p {
display: flex;
}
.badges > p > a {
margin: 0 0.5rem;
}

View File

@ -2,7 +2,7 @@
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/intro/n00b-syntaxReference.md](../../packages/mermaid/src/docs/intro/n00b-syntaxReference.md).
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/intro/syntax-reference.md](../../packages/mermaid/src/docs/intro/syntax-reference.md).
# Diagram Syntax
@ -42,7 +42,7 @@ erDiagram
PRODUCT ||--o{ ORDER-ITEM : "ordered in"
```
The [Getting Started](./n00b-gettingStarted.md) section can also provide some practical examples of mermaid syntax.
The [Getting Started](./getting-started.md) section can also provide some practical examples of mermaid syntax.
## Diagram Breaking
@ -56,30 +56,30 @@ One should **beware the use of some words or symbols** that can break diagrams.
| 'end' | The word "End" can cause Flowcharts and Sequence diagrams to break | Wrap them in quotation marks to prevent breakage. |
| [Nodes inside Nodes](../syntax/flowchart.md?id=special-characters-that-break-syntax) | Mermaid gets confused with nested shapes | wrap them in quotation marks to prevent breaking |
### Mermaid Live Editor
## Mermaid Live Editor
Now, that you've seen what you should not add to your diagrams, you can play around with them in the [Mermaid Live Editor](https://mermaid.live).
# Configuration
## Configuration
Configuration is the third part of Mermaid, after deployment and syntax. It deals with the different ways that Mermaid can be customized across different deployments.
If you are interested in altering and customizing your Mermaid Diagrams, you will find the methods and values available for [Configuration](../config/setup/README.md) here. It includes themes.
This section will introduce the different methods of configuring the behaviors and appearances of Mermaid Diagrams.
The following are the most commonly used methods, and they are all tied to Mermaid [Deployment](./n00b-gettingStarted.md) methods.
The following are the most commonly used methods, and they are all tied to Mermaid [Deployment](./getting-started.md) methods.
### Configuration Section in the [Live Editor](https://mermaid.live).
Here you can edit certain values to change the behavior and appearance of the diagram.
### [The initialize() call](https://mermaid-js.github.io/mermaid/#/n00b-gettingStarted?id=_3-calling-the-javascript-api),
### [The initialize() call](./getting-started.md#_3-calling-the-javascript-api)
Used when Mermaid is called via an API, or through a `<script>` tag.
### [Directives](../config/directives.md),
### [Directives](../config/directives.md)
Allows for the limited reconfiguration of a diagram just before it is rendered. It can alter the font style, color and other aesthetic aspects of the diagram. You can pass a directive alongside your definition inside `%%{ }%%`. It can be done either above or below your diagram definition.
### [Theme Manipulation](../config/theming.md):
### [Theme Manipulation](../config/theming.md)
An application of using Directives to change [Themes](../config/theming.md). `Theme` is a value within Mermaid's configuration that dictates the color scheme for diagrams.

View File

@ -6,8 +6,8 @@
# Announcements
## [From Chaos to Clarity: Exploring Mind Maps with MermaidJS](https://www.mermaidchart.com/blog/posts/from-chaos-to-clarity-exploring-mind-maps-with-mermaidjs)
## [Special cases broke Microsoft Zune and can ruin your code base too](https://www.mermaidchart.com/blog/posts/special-cases-broke-microsoft-zune-and-can-ruin-your-code-base-too/)
24 July 2023 · 4 mins
23 August 2023 · 15 mins
Introducing the concept of mind mapping as a tool for organizing complex information, and highlights Mermaid as a user-friendly software that simplifies the creation and editing of mind maps for applications in IT solution design, business decision-making, and knowledge organization.
Read about the pitfalls of special cases in programming, illustrating how they can lead to complexity, diminish readability, and create maintenance challenges.

View File

@ -6,6 +6,24 @@
# Blog
## [Special cases broke Microsoft Zune and can ruin your code base too](https://www.mermaidchart.com/blog/posts/special-cases-broke-microsoft-zune-and-can-ruin-your-code-base-too/)
23 August 2023 · 15 mins
Read about the pitfalls of special cases in programming, illustrating how they can lead to complexity, diminish readability, and create maintenance challenges.
## [New AI chatbot now available on Mermaid Chart to simplify text-based diagram creation](https://www.mermaidchart.com/blog/posts/ai-chatbot-now-available-on-mermaid-chart-to-simplify-text-based-diagram-creation/)
14 August 2023 · 4 mins
Introducing Mermaid Charts new AI chatbot, a diagramming assistant that simplifies text-based diagram creation for everyone, from developers to educators, offering features to start, edit, and fix diagrams, and embodying our vision to make diagramming accessible, user-friendly, and fun.
## [Believe It or Not, You Still Need an Online UML Diagram Tool](https://www.mermaidchart.com/blog/posts/uml-diagram-tool/)
14 August 2023 · 8 mins
A UML diagram tool helps developers and other professionals quickly create and share UML diagrams that communicate information about complex software systems.
## [From Chaos to Clarity: Exploring Mind Maps with MermaidJS](https://www.mermaidchart.com/blog/posts/from-chaos-to-clarity-exploring-mind-maps-with-mermaidjs)
24 July 2023 · 4 mins

View File

@ -198,6 +198,34 @@ erDiagram
The `type` values must begin with an alphabetic character and may contain digits, hyphens, underscores, parentheses and square brackets. The `name` values follow a similar format to `type`, but may start with an asterisk as another option to indicate an attribute is a primary key. Other than that, there are no restrictions, and there is no implicit set of valid data types.
### Entity Name Aliases (v\<MERMAID_RELEASE_VERSION>+)
An alias can be added to an entity using square brackets. If provided, the alias will be showed in the diagram instead of the entity name.
```mermaid-example
erDiagram
p[Person] {
string firstName
string lastName
}
a["Customer Account"] {
string email
}
p ||--o| a : has
```
```mermaid
erDiagram
p[Person] {
string firstName
string lastName
}
a["Customer Account"] {
string email
}
p ||--o| a : has
```
#### Attribute Keys and Comments
Attributes may also have a `key` or comment defined. Keys can be `PK`, `FK` or `UK`, for Primary Key, Foreign Key or Unique Key. To specify multiple key constraints on a single attribute, separate them with a comma (e.g., `PK, FK`).. A `comment` is defined by double quotes at the end of an attribute. Comments themselves cannot have double-quote characters in them.

View File

@ -1098,7 +1098,7 @@ The icons are accessed via the syntax fa:#icon class name#.
```mermaid-example
flowchart TD
B["fab:fa-twitter for peace"]
B["fa:fa-twitter for peace"]
B-->C[fa:fa-ban forbidden]
B-->D(fa:fa-spinner)
B-->E(A fa:fa-camera-retro perhaps?)
@ -1106,7 +1106,7 @@ flowchart TD
```mermaid
flowchart TD
B["fab:fa-twitter for peace"]
B["fa:fa-twitter for peace"]
B-->C[fa:fa-ban forbidden]
B-->D(fa:fa-spinner)
B-->E(A fa:fa-camera-retro perhaps?)

18
netlify.toml Normal file
View File

@ -0,0 +1,18 @@
# Settings in the [build] context are global and are applied to
# all contexts unless otherwise overridden by more specific contexts.
[build]
# Directory where the build system installs dependencies
# and runs your build. Store your package.json, .nvmrc, etc here.
# If not set, defaults to the root directory.
base = ""
# Directory that contains the deploy-ready HTML files and
# assets generated by the build. This is an absolute path relative
# to the base directory, which is the root by default (/).
# This sample publishes the directory located at the absolute
# path "root/project/build-output"
publish = "mermaid-live-editor/docs"
# Default build command.
command = "./scripts/editor.bash"

View File

@ -107,6 +107,7 @@
"jison": "^0.4.18",
"js-yaml": "^4.1.0",
"jsdom": "^22.0.0",
"langium-cli": "2.0.1",
"lint-staged": "^13.2.1",
"nyc": "^15.1.0",
"path-browserify": "^1.0.1",

22
packages/mermaid/.madgerc Normal file
View File

@ -0,0 +1,22 @@
{
"detectiveOptions": {
"ts": {
"skipTypeImports": true
},
"es6": {
"skipTypeImports": true
}
},
"fileExtensions": [
"js",
"ts"
],
"excludeRegExp": [
"node_modules",
"docs",
"vitepress",
"detector",
"Detector"
],
"tsConfig": "./tsconfig.json"
}

View File

@ -38,6 +38,7 @@
"docs:verify-version": "ts-node-esm scripts/update-release-version.mts --verify",
"types:build-config": "ts-node-esm --transpileOnly scripts/create-types-from-json-schema.mts",
"types:verify-config": "ts-node-esm scripts/create-types-from-json-schema.mts --verify",
"checkCircle": "npx madge --circular ./src",
"release": "pnpm build",
"prepublishOnly": "cpy '../../README.*' ./ --cwd=. && pnpm -w run build"
},
@ -71,7 +72,7 @@
"khroma": "^2.0.0",
"lodash-es": "^4.17.21",
"mdast-util-from-markdown": "^1.3.0",
"mermaid-parser": "workspace:*",
"mermaid-parser": "workspace:^",
"stylis": "^4.1.3",
"ts-dedent": "^2.2.0",
"uuid": "^9.0.0"

View File

@ -48,9 +48,10 @@ export class Diagram {
// extractFrontMatter().
this.parser.parse = (text: string) =>
originalParse(cleanupComments(extractFrontMatter(text, this.db)));
originalParse(cleanupComments(extractFrontMatter(text, this.db, configApi.addDirective)));
if (this.parser.parser?.yy) {
if (this.parser.parser !== undefined) {
// The parser.parser.yy is only present in JISON parsers. So, we'll only set if required.
this.parser.parser.yy = this.db;
}
this.init = diagram.init;

View File

@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* assignWithDepth Extends the functionality of {@link ObjectConstructor.assign} with the
* assignWithDepth Extends the functionality of {@link Object.assign} with the
* ability to merge arbitrary-depth objects For each key in src with path `k` (recursively)
* performs an Object.assign(dst[`k`], src[`k`]) with a slight change from the typical handling of
* undefined for dst[`k`]: instead of raising an error, dst[`k`] is auto-initialized to `{}` and

View File

@ -1,11 +1,13 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import * as configApi from './config.js';
import type { MermaidConfig } from './config.type.js';
describe('when working with site config', function () {
describe('when working with site config', () => {
beforeEach(() => {
// Resets the site config to default config
configApi.setSiteConfig({});
});
it('should set site config and config properly', function () {
it('should set site config and config properly', () => {
const config_0 = { fontFamily: 'foo-font', fontSize: 150 };
configApi.setSiteConfig(config_0);
const config_1 = configApi.getSiteConfig();
@ -14,19 +16,26 @@ describe('when working with site config', function () {
expect(config_1.fontSize).toEqual(config_0.fontSize);
expect(config_1).toEqual(config_2);
});
it('should respect secure keys when applying directives', function () {
const config_0 = {
it('should respect secure keys when applying directives', () => {
const config_0: MermaidConfig = {
fontFamily: 'foo-font',
securityLevel: 'strict', // can't be changed
fontSize: 12345, // can't be changed
secure: [...configApi.defaultConfig.secure!, 'fontSize'],
};
configApi.setSiteConfig(config_0);
const directive = { fontFamily: 'baf', fontSize: 54321 /* fontSize shouldn't be changed */ };
const cfg = configApi.updateCurrentConfig(config_0, [directive]);
const directive: MermaidConfig = {
fontFamily: 'baf',
// fontSize and securityLevel shouldn't be changed
fontSize: 54321,
securityLevel: 'loose',
};
const cfg: MermaidConfig = configApi.updateCurrentConfig(config_0, [directive]);
expect(cfg.fontFamily).toEqual(directive.fontFamily);
expect(cfg.fontSize).toBe(config_0.fontSize);
expect(cfg.securityLevel).toBe(config_0.securityLevel);
});
it('should allow setting partial options', function () {
it('should allow setting partial options', () => {
const defaultConfig = configApi.getConfig();
configApi.setConfig({
@ -42,7 +51,7 @@ describe('when working with site config', function () {
updatedConfig.quadrantChart!.chartWidth
);
});
it('should set reset config properly', function () {
it('should set reset config properly', () => {
const config_0 = { fontFamily: 'foo-font', fontSize: 150 };
configApi.setSiteConfig(config_0);
const config_1 = { fontFamily: 'baf' };
@ -55,7 +64,7 @@ describe('when working with site config', function () {
const config_4 = configApi.getSiteConfig();
expect(config_4.fontFamily).toEqual(config_0.fontFamily);
});
it('should set global reset config properly', function () {
it('should set global reset config properly', () => {
const config_0 = { fontFamily: 'foo-font', fontSize: 150 };
configApi.setSiteConfig(config_0);
const config_1 = configApi.getSiteConfig();

View File

@ -3,15 +3,16 @@ import { log } from './logger.js';
import theme from './themes/index.js';
import config from './defaultConfig.js';
import type { MermaidConfig } from './config.type.js';
import { sanitizeDirective } from './utils.js';
export const defaultConfig: MermaidConfig = Object.freeze(config);
let siteConfig: MermaidConfig = assignWithDepth({}, defaultConfig);
let configFromInitialize: MermaidConfig;
let directives: any[] = [];
let directives: MermaidConfig[] = [];
let currentConfig: MermaidConfig = assignWithDepth({}, defaultConfig);
export const updateCurrentConfig = (siteCfg: MermaidConfig, _directives: any[]) => {
export const updateCurrentConfig = (siteCfg: MermaidConfig, _directives: MermaidConfig[]) => {
// start with config being the siteConfig
let cfg: MermaidConfig = assignWithDepth({}, siteCfg);
// let sCfg = assignWithDepth(defaultConfig, siteConfigDelta);
@ -20,7 +21,6 @@ export const updateCurrentConfig = (siteCfg: MermaidConfig, _directives: any[])
let sumOfDirectives: MermaidConfig = {};
for (const d of _directives) {
sanitize(d);
// Apply the data from the directive where the the overrides the themeVariables
sumOfDirectives = assignWithDepth(sumOfDirectives, d);
}
@ -111,12 +111,6 @@ export const getSiteConfig = (): MermaidConfig => {
* @returns The currentConfig merged with the sanitized conf
*/
export const setConfig = (conf: MermaidConfig): MermaidConfig => {
// sanitize(conf);
// Object.keys(conf).forEach(key => {
// const manipulator = manipulators[key];
// conf[key] = manipulator ? manipulator(conf[key]) : conf[key];
// });
checkConfig(conf);
assignWithDepth(currentConfig, conf);
@ -150,9 +144,12 @@ export const getConfig = (): MermaidConfig => {
* @param options - The potential setConfig parameter
*/
export const sanitize = (options: any) => {
if (!options) {
return;
}
// Checking that options are not in the list of excluded options
['secure', ...(siteConfig.secure ?? [])].forEach((key) => {
if (options[key] !== undefined) {
if (Object.hasOwn(options, key)) {
// DO NOT attempt to print options[key] within `${}` as a malicious script
// can exploit the logger's attempt to stringify the value and execute arbitrary code
log.debug(`Denied attempt to modify a secure key ${key}`, options[key]);
@ -162,7 +159,7 @@ export const sanitize = (options: any) => {
// Check that there no attempts of prototype pollution
Object.keys(options).forEach((key) => {
if (key.indexOf('__') === 0) {
if (key.startsWith('__')) {
delete options[key];
}
});
@ -188,16 +185,14 @@ export const sanitize = (options: any) => {
*
* @param directive - The directive to push in
*/
export const addDirective = (directive: any) => {
if (directive.fontFamily) {
if (!directive.themeVariables) {
directive.themeVariables = { fontFamily: directive.fontFamily };
} else {
if (!directive.themeVariables.fontFamily) {
directive.themeVariables = { fontFamily: directive.fontFamily };
}
}
export const addDirective = (directive: MermaidConfig) => {
sanitizeDirective(directive);
// If the directive has a fontFamily, but no themeVariables, add the fontFamily to the themeVariables
if (directive.fontFamily && (!directive.themeVariables || !directive.themeVariables.fontFamily)) {
directive.themeVariables = { fontFamily: directive.fontFamily };
}
directives.push(directive);
updateCurrentConfig(siteConfig, directives);
};

View File

@ -1298,6 +1298,21 @@ export interface SankeyDiagramConfig extends BaseDiagramConfig {
*/
nodeAlignment?: 'left' | 'right' | 'center' | 'justify';
useMaxWidth?: boolean;
/**
* Toggle to display or hide values along with title.
*
*/
showValues?: boolean;
/**
* The prefix to use for values
*
*/
prefix?: string;
/**
* The suffix to use for values
*
*/
suffix?: string;
}
/**
* This interface was referenced by `MermaidConfig`'s JSON-Schema

View File

@ -265,5 +265,5 @@ const keyify = (obj: any, prefix = ''): string[] =>
return [...res, prefix + el];
}, []);
export const configKeys: string[] = keyify(config, '');
export const configKeys: Set<string> = new Set(keyify(config, ''));
export default config;

View File

@ -1,4 +1,4 @@
import { MermaidConfig } from '../config.type.js';
import type { MermaidConfig } from '../config.type.js';
import { log } from '../logger.js';
import type {
DetectorRecord,
@ -6,14 +6,10 @@ import type {
DiagramLoader,
ExternalDiagramDefinition,
} from './types.js';
import { frontMatterRegex } from './frontmatter.js';
import { getDiagram, registerDiagram } from './diagramAPI.js';
import { anyCommentRegex, directiveRegex, frontMatterRegex } from './regexes.js';
import { UnknownDiagramError } from '../errors.js';
const directive = /%{2}{\s*(?:(\w+)\s*:|(\w+))\s*(?:(\w+)|((?:(?!}%{2}).|\r?\n)*))?\s*(?:}%{2})?/gi;
const anyComment = /\s*%%.*\n/gm;
const detectors: Record<string, DetectorRecord> = {};
export const detectors: Record<string, DetectorRecord> = {};
/**
* Detects the type of the graph text.
@ -38,7 +34,10 @@ const detectors: Record<string, DetectorRecord> = {};
* @returns A graph definition key
*/
export const detectType = function (text: string, config?: MermaidConfig): string {
text = text.replace(frontMatterRegex, '').replace(directive, '').replace(anyComment, '\n');
text = text
.replace(frontMatterRegex, '')
.replace(directiveRegex, '')
.replace(anyCommentRegex, '\n');
for (const [key, { detector }] of Object.entries(detectors)) {
const diagram = detector(text, config);
if (diagram) {
@ -70,39 +69,6 @@ export const registerLazyLoadedDiagrams = (...diagrams: ExternalDiagramDefinitio
}
};
export const loadRegisteredDiagrams = async () => {
log.debug(`Loading registered diagrams`);
// Load all lazy loaded diagrams in parallel
const results = await Promise.allSettled(
Object.entries(detectors).map(async ([key, { detector, loader }]) => {
if (loader) {
try {
getDiagram(key);
} catch (error) {
try {
// Register diagram if it is not already registered
const { diagram, id } = await loader();
registerDiagram(id, diagram, detector);
} catch (err) {
// Remove failed diagram from detectors
log.error(`Failed to load external diagram with key ${key}. Removing from detectors.`);
delete detectors[key];
throw err;
}
}
}
})
);
const failed = results.filter((result) => result.status === 'rejected');
if (failed.length > 0) {
log.error(`Failed to load ${failed.length} external diagrams`);
for (const res of failed) {
log.error(res);
}
throw new Error(`Failed to load ${failed.length} external diagrams`);
}
};
export const addDetector = (key: string, detector: DiagramDetector, loader?: DiagramLoader) => {
if (detectors[key]) {
log.error(`Detector with key ${key} already exists`);

View File

@ -1,7 +1,7 @@
import { detectType } from './detectType.js';
import { getDiagram, registerDiagram } from './diagramAPI.js';
import { addDiagrams } from './diagram-orchestration.js';
import { DiagramDetector } from './types.js';
import type { DiagramDetector } from './types.js';
import { getDiagramFromText } from '../Diagram.js';
import { it, describe, expect, beforeAll } from 'vitest';

View File

@ -4,7 +4,7 @@ import { getConfig as _getConfig } from '../config.js';
import { sanitizeText as _sanitizeText } from '../diagrams/common/common.js';
import { setupGraphViewbox as _setupGraphViewbox } from '../setupGraphViewbox.js';
import { addStylesForDiagram } from '../styles.js';
import { DiagramDefinition, DiagramDetector } from './types.js';
import type { DiagramDefinition, DiagramDetector } from './types.js';
import * as _commonDb from '../commonDb.js';
import { parseDirective as _parseDirective } from '../directiveUtils.js';

View File

@ -2,8 +2,13 @@ import { vi } from 'vitest';
import { extractFrontMatter } from './frontmatter.js';
const dbMock = () => ({ setDiagramTitle: vi.fn() });
const setConfigMock = vi.fn();
describe('extractFrontmatter', () => {
beforeEach(() => {
setConfigMock.mockClear();
});
it('returns text unchanged if no frontmatter', () => {
expect(extractFrontMatter('diagram', dbMock())).toEqual('diagram');
});
@ -75,4 +80,21 @@ describe('extractFrontmatter', () => {
'tag suffix cannot contain exclamation marks'
);
});
it('handles frontmatter with config', () => {
const text = `---
title: hello
config:
graph:
string: hello
number: 14
boolean: false
array: [1, 2, 3]
---
diagram`;
expect(extractFrontMatter(text, {}, setConfigMock)).toEqual('diagram');
expect(setConfigMock).toHaveBeenCalledWith({
graph: { string: 'hello', number: 14, boolean: false, array: [1, 2, 3] },
});
});
});

View File

@ -1,46 +1,53 @@
import { DiagramDB } from './types.js';
import type { MermaidConfig } from '../config.type.js';
import { frontMatterRegex } from './regexes.js';
import type { DiagramDB } from './types.js';
// The "* as yaml" part is necessary for tree-shaking
import * as yaml from 'js-yaml';
// Match Jekyll-style front matter blocks (https://jekyllrb.com/docs/front-matter/).
// Based on regex used by Jekyll: https://github.com/jekyll/jekyll/blob/6dd3cc21c40b98054851846425af06c64f9fb466/lib/jekyll/document.rb#L10
// Note that JS doesn't support the "\A" anchor, which means we can't use
// multiline mode.
// Relevant YAML spec: https://yaml.org/spec/1.2.2/#914-explicit-documents
export const frontMatterRegex = /^-{3}\s*[\n\r](.*?)[\n\r]-{3}\s*[\n\r]+/s;
type FrontMatterMetadata = {
interface FrontMatterMetadata {
title?: string;
// Allows custom display modes. Currently used for compact mode in gantt charts.
displayMode?: string;
};
config?: MermaidConfig;
}
/**
* Extract and parse frontmatter from text, if present, and sets appropriate
* properties in the provided db.
* @param text - The text that may have a YAML frontmatter.
* @param db - Diagram database, could be of any diagram.
* @param setDiagramConfig - Optional function to set diagram config.
* @returns text with frontmatter stripped out
*/
export function extractFrontMatter(text: string, db: DiagramDB): string {
export function extractFrontMatter(
text: string,
db: DiagramDB,
setDiagramConfig?: (config: MermaidConfig) => void
): string {
const matches = text.match(frontMatterRegex);
if (matches) {
const parsed: FrontMatterMetadata = yaml.load(matches[1], {
// To keep things simple, only allow strings, arrays, and plain objects.
// https://www.yaml.org/spec/1.2/spec.html#id2802346
schema: yaml.FAILSAFE_SCHEMA,
}) as FrontMatterMetadata;
if (parsed?.title) {
db.setDiagramTitle?.(parsed.title);
}
if (parsed?.displayMode) {
db.setDisplayMode?.(parsed.displayMode);
}
return text.slice(matches[0].length);
} else {
if (!matches) {
return text;
}
const parsed: FrontMatterMetadata = yaml.load(matches[1], {
// To support config, we need JSON schema.
// https://www.yaml.org/spec/1.2/spec.html#id2803231
schema: yaml.JSON_SCHEMA,
}) as FrontMatterMetadata;
if (parsed?.title) {
// toString() is necessary because YAML could parse the title as a number/boolean
db.setDiagramTitle?.(parsed.title.toString());
}
if (parsed?.displayMode) {
// toString() is necessary because YAML could parse the title as a number/boolean
db.setDisplayMode?.(parsed.displayMode.toString());
}
if (parsed?.config) {
setDiagramConfig?.(parsed.config);
}
return text.slice(matches[0].length);
}

View File

@ -0,0 +1,36 @@
import { log } from '../logger.js';
import { detectors } from './detectType.js';
import { getDiagram, registerDiagram } from './diagramAPI.js';
export const loadRegisteredDiagrams = async () => {
log.debug(`Loading registered diagrams`);
// Load all lazy loaded diagrams in parallel
const results = await Promise.allSettled(
Object.entries(detectors).map(async ([key, { detector, loader }]) => {
if (loader) {
try {
getDiagram(key);
} catch (error) {
try {
// Register diagram if it is not already registered
const { diagram, id } = await loader();
registerDiagram(id, diagram, detector);
} catch (err) {
// Remove failed diagram from detectors
log.error(`Failed to load external diagram with key ${key}. Removing from detectors.`);
delete detectors[key];
throw err;
}
}
}
})
);
const failed = results.filter((result) => result.status === 'rejected');
if (failed.length > 0) {
log.error(`Failed to load ${failed.length} external diagrams`);
for (const res of failed) {
log.error(res);
}
throw new Error(`Failed to load ${failed.length} external diagrams`);
}
};

View File

@ -0,0 +1,11 @@
// Match Jekyll-style front matter blocks (https://jekyllrb.com/docs/front-matter/).
// Based on regex used by Jekyll: https://github.com/jekyll/jekyll/blob/6dd3cc21c40b98054851846425af06c64f9fb466/lib/jekyll/document.rb#L10
// Note that JS doesn't support the "\A" anchor, which means we can't use
// multiline mode.
// Relevant YAML spec: https://yaml.org/spec/1.2.2/#914-explicit-documents
export const frontMatterRegex = /^-{3}\s*[\n\r](.*?)[\n\r]-{3}\s*[\n\r]+/s;
export const directiveRegex =
/%{2}{\s*(?:(\w+)\s*:|(\w+))\s*(?:(\w+)|((?:(?!}%{2}).|\r?\n)*))?\s*(?:}%{2})?/gi;
export const anyCommentRegex = /\s*%%.*\n/gm;

View File

@ -1,4 +1,4 @@
import { Diagram } from '../Diagram.js';
import type { Diagram } from '../Diagram.js';
import type { BaseDiagramConfig, MermaidConfig } from '../config.type.js';
import type * as d3 from 'd3';

View File

@ -3,8 +3,8 @@ import c4Parser from './parser/c4Diagram.jison';
import c4Db from './c4Db.js';
import c4Renderer from './c4Renderer.js';
import c4Styles from './styles.js';
import { MermaidConfig } from '../../config.type.js';
import { DiagramDefinition } from '../../diagram-api/types.js';
import type { MermaidConfig } from '../../config.type.js';
import type { DiagramDefinition } from '../../diagram-api/types.js';
export const diagram: DiagramDefinition = {
parser: c4Parser,

View File

@ -1,5 +1,6 @@
// @ts-nocheck - don't check until handle it
import { select, Selection } from 'd3';
import type { Selection } from 'd3';
import { select } from 'd3';
import { log } from '../../logger.js';
import * as configApi from '../../config.js';
import common from '../common/common.js';
@ -14,7 +15,7 @@ import {
setDiagramTitle,
getDiagramTitle,
} from '../../commonDb.js';
import {
import type {
ClassRelation,
ClassNode,
ClassNote,

View File

@ -1,4 +1,4 @@
import { DiagramDefinition } from '../../diagram-api/types.js';
import type { DiagramDefinition } from '../../diagram-api/types.js';
// @ts-ignore: JISON doesn't support types
import parser from './parser/classDiagram.jison';
import db from './classDb.js';

View File

@ -1,4 +1,4 @@
import { DiagramDefinition } from '../../diagram-api/types.js';
import type { DiagramDefinition } from '../../diagram-api/types.js';
// @ts-ignore: JISON doesn't support types
import parser from './parser/classDiagram.jison';
import db from './classDb.js';

View File

@ -8,7 +8,7 @@ import utils from '../../utils.js';
import { interpolateToCurve, getStylesFromArray } from '../../utils.js';
import { setupGraphViewbox } from '../../setupGraphViewbox.js';
import common from '../common/common.js';
import { ClassRelation, ClassNote, ClassMap, EdgeData, NamespaceMap } from './classTypes.js';
import type { ClassRelation, ClassNote, ClassMap, EdgeData, NamespaceMap } from './classTypes.js';
const sanitizeText = (txt: string) => common.sanitizeText(txt, getConfig());

View File

@ -1,5 +1,5 @@
import DOMPurify from 'dompurify';
import { MermaidConfig } from '../../config.type.js';
import type { MermaidConfig } from '../../config.type.js';
// Remove and ignore br:s
export const lineBreakRegex = /<br\s*\/?>/gi;

View File

@ -3,7 +3,13 @@ import type { DiagramAST } from 'mermaid-parser';
import type { DiagramDB } from '../../diagram-api/types.js';
export function populateCommonDb(ast: DiagramAST, db: DiagramDB) {
ast.accDescr && db.setAccDescription?.(ast.accDescr);
ast.accTitle && db.setAccTitle?.(ast.accTitle);
ast.title && db.setDiagramTitle?.(ast.title);
if (ast.accDescr) {
db.setAccDescription?.(ast.accDescr);
}
if (ast.accTitle) {
db.setAccTitle?.(ast.accTitle);
}
if (ast.title) {
db.setDiagramTitle?.(ast.title);
}
}

View File

@ -32,10 +32,13 @@ export const parseDirective = function (statement, context, type) {
mermaidAPI.parseDirective(this, statement, context, type);
};
const addEntity = function (name) {
const addEntity = function (name, alias = undefined) {
if (entities[name] === undefined) {
entities[name] = { attributes: [] };
entities[name] = { attributes: [], alias: alias };
log.info('Added new entity :', name);
} else if (entities[name] && !entities[name].alias && alias) {
entities[name].alias = alias;
log.info(`Add alias '${alias}' to entity '${name}'`);
}
return entities[name];

View File

@ -326,7 +326,7 @@ const drawEntities = function (svgNode, entities, graph) {
.style('text-anchor', 'middle')
.style('font-family', getConfig().fontFamily)
.style('font-size', conf.fontSize + 'px')
.text(entityName);
.text(entities[entityName].alias ?? entityName);
const { width: entityWidth, height: entityHeight } = drawAttributes(
groupNode,

View File

@ -35,6 +35,8 @@ accDescr\s*"{"\s* { this.begin("acc_descr_multili
<block>[\n]+ /* nothing */
<block>"}" { this.popState(); return 'BLOCK_STOP'; }
<block>. return yytext[0];
"[" return 'SQS';
"]" return 'SQE';
"one or zero" return 'ZERO_OR_ONE';
"one or more" return 'ONE_OR_MORE';
@ -102,17 +104,21 @@ statement
yy.addEntity($1);
yy.addEntity($3);
yy.addRelationship($1, $5, $3, $2);
/*console.log($1 + $2 + $3 + ':' + $5);*/
}
| entityName BLOCK_START attributes BLOCK_STOP
{
/* console.log('detected block'); */
yy.addEntity($1);
yy.addAttributes($1, $3);
/* console.log('handled block'); */
}
| entityName BLOCK_START BLOCK_STOP { yy.addEntity($1); }
| entityName { yy.addEntity($1); }
| entityName SQS entityName SQE BLOCK_START attributes BLOCK_STOP
{
yy.addEntity($1, $3);
yy.addAttributes($1, $6);
}
| entityName SQS entityName SQE BLOCK_START BLOCK_STOP { yy.addEntity($1, $3); }
| entityName SQS entityName SQE { yy.addEntity($1, $3); }
| title title_value { $$=$2.trim();yy.setAccTitle($$); }
| acc_title acc_title_value { $$=$2.trim();yy.setAccTitle($$); }
| acc_descr acc_descr_value { $$=$2.trim();yy.setAccDescription($$); }

View File

@ -133,6 +133,43 @@ describe('when parsing ER diagram it...', function () {
const entities = erDb.getEntities();
expect(entities.hasOwnProperty(hyphensUnderscore)).toBe(true);
});
it('can have an alias', function () {
const entity = 'foo';
const alias = 'bar';
erDiagram.parser.parse(`erDiagram\n${entity}["${alias}"]\n`);
const entities = erDb.getEntities();
expect(entities.hasOwnProperty(entity)).toBe(true);
expect(entities[entity].alias).toBe(alias);
});
it('can have an alias even if the relationship is defined before class', function () {
const firstEntity = 'foo';
const secondEntity = 'bar';
const alias = 'batman';
erDiagram.parser.parse(
`erDiagram\n${firstEntity} ||--o| ${secondEntity} : rel\nclass ${firstEntity}["${alias}"]\n`
);
const entities = erDb.getEntities();
expect(entities.hasOwnProperty(firstEntity)).toBe(true);
expect(entities.hasOwnProperty(secondEntity)).toBe(true);
expect(entities[firstEntity].alias).toBe(alias);
expect(entities[secondEntity].alias).toBeUndefined();
});
it('can have an alias even if the relationship is defined after class', function () {
const firstEntity = 'foo';
const secondEntity = 'bar';
const alias = 'batman';
erDiagram.parser.parse(
`erDiagram\nclass ${firstEntity}["${alias}"]\n${firstEntity} ||--o| ${secondEntity} : rel\n`
);
const entities = erDb.getEntities();
expect(entities.hasOwnProperty(firstEntity)).toBe(true);
expect(entities.hasOwnProperty(secondEntity)).toBe(true);
expect(entities[firstEntity].alias).toBe(alias);
expect(entities[secondEntity].alias).toBeUndefined();
});
});
describe('attribute name', () => {

View File

@ -1,4 +1,5 @@
import { findCommonAncestor, TreeData } from './render-utils.js';
import type { TreeData } from './render-utils.js';
import { findCommonAncestor } from './render-utils.js';
describe('when rendering a flowchart using elk ', () => {
let lookupDb: TreeData;
beforeEach(() => {

View File

@ -3,7 +3,7 @@ import flowParser from './parser/flow.jison';
import flowDb from './flowDb.js';
import flowRendererV2 from './flowRenderer-v2.js';
import flowStyles from './styles.js';
import { MermaidConfig } from '../../config.type.js';
import type { MermaidConfig } from '../../config.type.js';
import { setConfig } from '../../config.js';
export const diagram = {

View File

@ -4,7 +4,7 @@ import flowDb from './flowDb.js';
import flowRenderer from './flowRenderer.js';
import flowRendererV2 from './flowRenderer-v2.js';
import flowStyles from './styles.js';
import { MermaidConfig } from '../../config.type.js';
import type { MermaidConfig } from '../../config.type.js';
export const diagram = {
parser: flowParser,

View File

@ -3,7 +3,7 @@ import ganttParser from './parser/gantt.jison';
import ganttDb from './ganttDb.js';
import ganttRenderer from './ganttRenderer.js';
import ganttStyles from './styles.js';
import { DiagramDefinition } from '../../diagram-api/types.js';
import type { DiagramDefinition } from '../../diagram-api/types.js';
export const diagram: DiagramDefinition = {
parser: ganttParser,

View File

@ -3,7 +3,7 @@ import gitGraphParser from './parser/gitGraph.jison';
import gitGraphDb from './gitGraphAst.js';
import gitGraphRenderer from './gitGraphRenderer.js';
import gitGraphStyles from './styles.js';
import { DiagramDefinition } from '../../diagram-api/types.js';
import type { DiagramDefinition } from '../../diagram-api/types.js';
export const diagram: DiagramDefinition = {
parser: gitGraphParser,

View File

@ -1,4 +1,5 @@
import d3, { scaleOrdinal, pie as d3pie, arc } from 'd3';
import type d3 from 'd3';
import { scaleOrdinal, pie as d3pie, arc } from 'd3';
import { log } from '../../logger.js';
import { configureSvgSize } from '../../setupGraphViewbox.js';
@ -11,14 +12,16 @@ import { selectSvgElement } from '../../rendering-util/selectSvgElement.js';
const createPieArcs = (sections: Sections): d3.PieArcDatum<D3Section>[] => {
// Compute the position of each group on the pie:
const pieData: D3Section[] = Object.entries(sections).map(
(element: [string, number]): D3Section => {
const pieData: D3Section[] = Object.entries(sections)
.map((element: [string, number]): D3Section => {
return {
label: element[0],
value: element[1],
};
}
);
})
.sort((a: D3Section, b: D3Section): number => {
return b.value - a.value;
});
const pie: d3.Pie<unknown, D3Section> = d3pie<D3Section>().value(
(d3Section: D3Section): number => d3Section.value
);

View File

@ -1,6 +1,7 @@
// @ts-ignore: JISON doesn't support types
import { parser } from './quadrant.jison';
import { Mock, vi } from 'vitest';
import type { Mock } from 'vitest';
import { vi } from 'vitest';
const parserFnConstructor = (str: string) => {
return () => {

View File

@ -1,4 +1,4 @@
import { DiagramDefinition } from '../../diagram-api/types.js';
import type { DiagramDefinition } from '../../diagram-api/types.js';
// @ts-ignore: JISON doesn't support types
import parser from './parser/quadrant.jison';
import db from './quadrantDb.js';

View File

@ -3,8 +3,8 @@ import { select } from 'd3';
import * as configApi from '../../config.js';
import { log } from '../../logger.js';
import { configureSvgSize } from '../../setupGraphViewbox.js';
import { Diagram } from '../../Diagram.js';
import {
import type { Diagram } from '../../Diagram.js';
import type {
QuadrantBuildType,
QuadrantLineType,
QuadrantPointType,

View File

@ -1,4 +1,4 @@
import { DiagramDefinition } from '../../diagram-api/types.js';
import type { DiagramDefinition } from '../../diagram-api/types.js';
// @ts-ignore: JISON doesn't support types
import parser from './parser/requirementDiagram.jison';
import db from './requirementDb.js';

View File

@ -31,7 +31,7 @@ class SankeyLink {
/**
* @param source - Node where the link starts
* @param target - Node where the link ends
* @param value - number, float or integer, describes the amount to be passed
* @param value - Describes the amount to be passed
*/
const addLink = (source: SankeyNode, target: SankeyNode, value: number): void => {
links.push(new SankeyLink(source, target, value));

View File

@ -1,4 +1,4 @@
import { DiagramDefinition } from '../../diagram-api/types.js';
import type { DiagramDefinition } from '../../diagram-api/types.js';
// @ts-ignore: jison doesn't export types
import parser from './parser/sankey.jison';
import db from './sankeyDB.js';

View File

@ -1,4 +1,4 @@
import { Diagram } from '../../Diagram.js';
import type { Diagram } from '../../Diagram.js';
import * as configApi from '../../config.js';
import {
@ -7,6 +7,7 @@ import {
schemeTableau10 as d3schemeTableau10,
} from 'd3';
import type { SankeyNode as d3SankeyNode } from 'd3-sankey';
import {
sankey as d3Sankey,
sankeyLinkHorizontal as d3SankeyLinkHorizontal,
@ -14,11 +15,10 @@ import {
sankeyRight as d3SankeyRight,
sankeyCenter as d3SankeyCenter,
sankeyJustify as d3SankeyJustify,
SankeyNode as d3SankeyNode,
} from 'd3-sankey';
import { configureSvgSize } from '../../setupGraphViewbox.js';
import { Uid } from '../../rendering-util/uid.js';
import type { SankeyLinkColor, SankeyNodeAlignment } from '../../config.type.js';
import type { SankeyNodeAlignment } from '../../config.type.js';
// Map config options to alignment functions
const alignmentsMap: Record<
@ -62,10 +62,13 @@ export const draw = function (text: string, id: string, _version: string, diagOb
// Establish svg dimensions and get width and height
//
const width = conf?.width || defaultSankeyConfig.width!;
const height = conf?.height || defaultSankeyConfig.width!;
const useMaxWidth = conf?.useMaxWidth || defaultSankeyConfig.useMaxWidth!;
const nodeAlignment = conf?.nodeAlignment || defaultSankeyConfig.nodeAlignment!;
const width = conf?.width ?? defaultSankeyConfig.width!;
const height = conf?.height ?? defaultSankeyConfig.width!;
const useMaxWidth = conf?.useMaxWidth ?? defaultSankeyConfig.useMaxWidth!;
const nodeAlignment = conf?.nodeAlignment ?? defaultSankeyConfig.nodeAlignment!;
const prefix = conf?.prefix ?? defaultSankeyConfig.prefix!;
const suffix = conf?.suffix ?? defaultSankeyConfig.suffix!;
const showValues = conf?.showValues ?? defaultSankeyConfig.showValues!;
// FIX: using max width prevents height from being set, is it intended?
// to add height directly one can use `svg.attr('height', height)`
@ -94,7 +97,7 @@ export const draw = function (text: string, id: string, _version: string, diagOb
const sankey = d3Sankey()
.nodeId((d: any) => d.id) // we use 'id' property to identify node
.nodeWidth(nodeWidth)
.nodePadding(10)
.nodePadding(10 + (showValues ? 15 : 0))
.nodeAlign(nodeAlign)
.extent([
[0, 0],
@ -130,6 +133,13 @@ export const draw = function (text: string, id: string, _version: string, diagOb
.attr('width', (d: any) => d.x1 - d.x0)
.attr('fill', (d: any) => colorScheme(d.id));
const getText = ({ id, value }: { id: string; value: number }) => {
if (!showValues) {
return id;
}
return `${id}\n${prefix}${Math.round(value * 100) / 100}${suffix}`;
};
// Create labels for nodes
svg
.append('g')
@ -141,9 +151,9 @@ export const draw = function (text: string, id: string, _version: string, diagOb
.join('text')
.attr('x', (d: any) => (d.x0 < width / 2 ? d.x1 + 6 : d.x0 - 6))
.attr('y', (d: any) => (d.y1 + d.y0) / 2)
.attr('dy', '0.35em')
.attr('dy', `${showValues ? '0' : '0.35'}em`)
.attr('text-anchor', (d: any) => (d.x0 < width / 2 ? 'start' : 'end'))
.text((d: any) => d.id);
.text(getText);
// Creates the paths that represent the links.
const link = svg

View File

@ -1,4 +1,4 @@
import { DiagramDefinition } from '../../diagram-api/types.js';
import type { DiagramDefinition } from '../../diagram-api/types.js';
// @ts-ignore: JISON doesn't support types
import parser from './parser/sequenceDiagram.jison';
import db from './sequenceDb.js';

View File

@ -8,7 +8,7 @@ import * as configApi from '../../config.js';
import assignWithDepth from '../../assignWithDepth.js';
import utils from '../../utils.js';
import { configureSvgSize } from '../../setupGraphViewbox.js';
import { Diagram } from '../../Diagram.js';
import type { Diagram } from '../../Diagram.js';
let conf = {};

View File

@ -1,4 +1,4 @@
import { DiagramDefinition } from '../../diagram-api/types.js';
import type { DiagramDefinition } from '../../diagram-api/types.js';
// @ts-ignore: JISON doesn't support types
import parser from './parser/stateDiagram.jison';
import db from './stateDb.js';

View File

@ -1,4 +1,4 @@
import { DiagramDefinition } from '../../diagram-api/types.js';
import type { DiagramDefinition } from '../../diagram-api/types.js';
// @ts-ignore: JISON doesn't support types
import parser from './parser/stateDiagram.jison';
import db from './stateDb.js';

View File

@ -1,11 +1,12 @@
// @ts-nocheck - don't check until handle it
import { select, Selection } from 'd3';
import type { Selection } from 'd3';
import { select } from 'd3';
import svgDraw from './svgDraw.js';
import { log } from '../../logger.js';
import { getConfig } from '../../config.js';
import { setupGraphViewbox } from '../../setupGraphViewbox.js';
import { Diagram } from '../../Diagram.js';
import { MermaidConfig } from '../../config.type.js';
import type { Diagram } from '../../Diagram.js';
import type { MermaidConfig } from '../../config.type.js';
interface Block<TDesc, TSection> {
number: number;

View File

@ -1,4 +1,4 @@
import { DiagramDefinition } from '../../diagram-api/types.js';
import type { DiagramDefinition } from '../../diagram-api/types.js';
// @ts-ignore: JISON doesn't support types
import parser from './parser/journey.jison';
import db from './journeyDb.js';

View File

@ -1,7 +1,5 @@
import * as configApi from './config.js';
import { log } from './logger.js';
import { directiveSanitizer } from './utils.js';
let currentDirective: { type?: string; args?: any } | undefined = {};
@ -60,9 +58,6 @@ const handleDirective = function (p: any, directive: any, type: string): void {
delete directive.args[prop];
}
});
log.info('sanitize in handleDirective', directive.args);
directiveSanitizer(directive.args);
log.info('sanitize in handleDirective (done)', directive.args);
configApi.addDirective(directive.args);
break;
}

View File

@ -72,6 +72,11 @@ function nav() {
activeMatch: '/config/',
},
{ text: 'Integrations', link: '/ecosystem/integrations', activeMatch: '/ecosystem/' },
{
text: 'Contributing',
link: '/community/development.html',
activeMatch: '/community/',
},
{
text: 'Latest News',
link: '/news/announcements',
@ -104,11 +109,8 @@ function sidebarAll() {
collapsed: false,
items: [
{ text: 'About Mermaid', link: '/intro/' },
{ text: 'Deployment', link: '/intro/n00b-gettingStarted' },
{
text: 'Syntax and Configuration',
link: '/intro/n00b-syntaxReference',
},
{ text: 'Getting Started', link: '/intro/getting-started' },
{ text: 'Syntax and Configuration', link: '/intro/syntax-reference' },
],
},
...sidebarSyntax(),
@ -165,7 +167,7 @@ function sidebarConfig() {
{ text: 'Theming', link: '/config/theming' },
{ text: 'Accessibility', link: '/config/accessibility' },
{ text: 'Mermaid CLI', link: '/config/mermaidCLI' },
{ text: 'Advanced usage', link: '/config/n00b-advanced' },
{ text: 'Advanced usage', link: '/config/advanced' },
{ text: 'FAQ', link: '/config/faq' },
],
},
@ -191,8 +193,10 @@ function sidebarCommunity() {
text: '🙌 Contributions and Community',
collapsed: false,
items: [
{ text: 'Overview for Beginners', link: '/community/n00b-overview' },
...sidebarCommunityDevelopContribute(),
{ text: 'Contributing to Mermaid', link: '/community/development' },
{ text: 'Contributing Code', link: '/community/code' },
{ text: 'Contributing Documentation', link: '/community/documentation' },
{ text: 'Questions and Suggestions', link: '/community/questions-and-suggestions' },
{ text: 'Adding Diagrams', link: '/community/newDiagram' },
{ text: 'Security', link: '/community/security' },
],
@ -200,40 +204,6 @@ function sidebarCommunity() {
];
}
// Development and Contributing
function sidebarCommunityDevelopContribute() {
const page_path = '/community/development';
return [
{
text: 'Contributing to Mermaid',
link: page_path + '#contributing-to-mermaid',
collapsed: false,
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 [
{

View File

@ -19,8 +19,17 @@ test.each([
'https://mermaid-js.github.io/mermaid/#/flowchart?another=test&id=my-id&one=more', // with multiple params
'syntax/flowchart.html#my-id',
],
['https://mermaid-js.github.io/mermaid/#/n00b-advanced', 'config/n00b-advanced.html'], // without .md
['https://mermaid-js.github.io/mermaid/#/n00b-advanced.md', 'config/n00b-advanced.html'], // with .md
['https://mermaid-js.github.io/mermaid/#/n00b-advanced', 'config/advanced.html'], // without .md
['https://mermaid-js.github.io/mermaid/#/n00b-advanced.md', 'config/advanced.html'], // with .md
['https://mermaid-js.github.io/mermaid/#/n00b-gettingstarted', 'intro/getting-started.html'],
['https://mermaid-js.github.io/mermaid/#/n00b-gettingstarted.md', 'intro/getting-started.html'],
['https://mermaid-js.github.io/mermaid/#/n00b-overview', 'intro/getting-started.html'],
['https://mermaid-js.github.io/mermaid/#/n00b-overview.md', 'intro/getting-started.html'],
['https://mermaid-js.github.io/mermaid/#/n00b-syntaxreference', 'intro/syntax-reference.html'],
['https://mermaid-js.github.io/mermaid/#/n00b-syntaxreference.md', 'intro/syntax-reference.html'],
['https://mermaid-js.github.io/mermaid/#/quickstart', 'intro/getting-started.html'],
['https://mermaid-js.github.io/mermaid/#/quickstart.md', 'intro/getting-started.html'],
[
'https://mermaid-js.github.io/mermaid/#/flowchart?id=a-node-in-the-form-of-a-circle', // with id, without .md
'syntax/flowchart.html#a-node-in-the-form-of-a-circle',

View File

@ -25,9 +25,13 @@ const getBaseFile = (url: URL): Redirect => {
};
/**
* Used to redirect old documentation pages to corresponding new pages.
* Used to redirect old (pre-vitepress) documentation pages to corresponding new pages.
* The key is the old documentation ID, and the value is the new documentation path.
* No key should be added here as it already has all the old documentation IDs.
* If you are changing a documentation page, you should update the corresponding value here, and add an entry in the urlRedirectMap below.
*/
const idRedirectMap: Record<string, string> = {
// ID of the old documentation page: Path of the new documentation page
'8.6.0_docs': '',
accessibility: 'config/theming',
breakingchanges: '',
@ -50,14 +54,14 @@ const idRedirectMap: Record<string, string> = {
mermaidcli: 'config/mermaidCLI',
mindmap: 'syntax/mindmap',
'more-pages': '',
'n00b-advanced': 'config/n00b-advanced',
'n00b-gettingstarted': 'intro/n00b-gettingStarted',
'n00b-overview': 'community/n00b-overview',
'n00b-syntaxreference': 'intro/n00b-syntaxReference',
'n00b-advanced': 'config/advanced',
'n00b-gettingstarted': 'intro/getting-started',
'n00b-overview': 'intro/getting-started',
'n00b-syntaxreference': 'intro/syntax-reference',
newdiagram: 'community/newDiagram',
pie: 'syntax/pie',
plugins: '',
quickstart: 'intro/n00b-gettingStarted',
quickstart: 'intro/getting-started',
requirementdiagram: 'syntax/requirementDiagram',
security: 'community/security',
sequencediagram: 'syntax/sequenceDiagram',
@ -73,10 +77,19 @@ const idRedirectMap: Record<string, string> = {
/**
* Used to redirect pages that have been moved in the vitepress site.
* No keys should be deleted from here.
* If you are changing a documentation page, you should update the corresponding value here,
* and update the entry in the idRedirectMap above if it was present
* (No need to add new keys in idRedirectMap).
*/
const urlRedirectMap: Record<string, string> = {
// Old URL: New URL
'/misc/faq.html': 'configure/faq.html',
'/syntax/c4c.html': 'syntax/c4.html',
'/config/n00b-advanced.html': 'config/advanced',
'/intro/n00b-gettingStarted.html': 'intro/getting-started',
'/intro/n00b-syntaxReference.html': 'intro/syntax-reference',
'/community/n00b-overview.html': 'intro/getting-started',
};
/**

View File

@ -0,0 +1,165 @@
# Contributing Code
The basic steps for contributing code are:
```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]
```
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.
## 1. Checkout a git branch
Mermaid uses a [Git Flow](https://guides.github.com/introduction/flow/)inspired approach to branching.
Development is done in the `develop` branch.
Once development is done we create a `release/vX.X.X` branch from `develop` for testing.
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.
**All new work should be based on the `develop` branch.**
**When you are ready to do work, always, ALWAYS:**
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.
We use the follow naming convention for branches:
```txt
[feature | bug | chore | docs]/[issue number]_[short description using dashes ('-') or underscores ('_') instead of spaces]
```
You can always check current [configuration of labelling and branch prefixes](https://github.com/mermaid-js/mermaid/blob/develop/.github/pr-labeler.yml)
- 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)
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.
**Ex: A new feature described in issue 2945 that adds a new arrow type called 'florbs' to state diagrams**
`feature/2945_state-diagram-new-arrow-florbs`
**Ex: A bug described in issue 1123 that causes random ugly red text in multiple diagram types**
`bug/1123_fix_random_ugly_red_text`
## 2. Write 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).
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 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.
When running in CI it will take a snapshot of the rendered diagram and compare it with the snapshot from last build and flag it for review if it differs.
This is what a rendering test looks like:
```js
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');
});
```
**_[TODO - running the tests against what is expected in development. ]_**
**_[TODO - how to generate new screenshots]_**
....
## 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!
If you are adding a new feature, add `(v<MERMAID_RELEASE_VERSION>+)` in the title or description. It will be replaced automatically with the current version number when the release happens.
eg: `# Feature Name (v<MERMAID_RELEASE_VERSION>+)`
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.**

View File

@ -1,14 +1,8 @@
# 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)
---
> The following documentation describes how to work with Mermaid in your host environment.
> There's also a [Docker installation guide](../community/docker-development.md)
> if you prefer to work in a Docker environment.
So you want to help? That's great!
@ -16,47 +10,68 @@ So you want to help? That's great!
Here are a few things to get you started on the right path.
## Technical Requirements and Setup
## Get the Source Code
### Technical Requirements
In GitHub, you first **fork** a repository when you are going to make changes and submit pull requests.
These are the tools we use for working with the code and documentation.
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.
[Fork mermaid](https://github.com/mermaid-js/mermaid/fork) to start contributing to the main project and its documentaion, or [search for other repositories](https://github.com/orgs/mermaid-js/repositories).
[Here is a GitHub document that gives an overview of the process.](https://docs.github.com/en/get-started/quickstart/fork-a-repo)
## Technical Requirements
> The following documentation describes how to work with Mermaid in your host environment.
> There's also a [Docker installation guide](../community/docker-development.md)
> if you prefer to work in a Docker environment.
These are the tools we use for working with the code and documentation:
- [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)
- [npx](https://docs.npmjs.com/cli/v8/commands/npx) the packaged executor in npm. This is needed [to install pnpm.](#install-packages)
Follow [the setup steps below](#setup) to install them and verify they are working
Follow the setup steps below to install them and start the development.
### Setup
## Setup and Launch
Follow these steps to set up the environment you need to work on code and/or documentation.
### Switch to project
#### 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:
Once you have cloned the repository onto your development machine, change into the `mermaid` project folder (the top level directory of the mermaid project repository)
```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
### Install packages
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:
Run `npx pnpm install`. You will need `npx` for this because volta doesn't support it yet.
```bash
npx pnpm install # npx is required for first install
```
### Launch
```bash
npx pnpm run dev
```
Now you are ready to make your changes! Edit whichever files in `src` as required.
Open <http://localhost:9000> in your browser, after starting the dev server.
There is a list of demos that can be used to see and test your changes.
If you need a specific diagram, you can duplicate the `example.html` file in `/demos/dev` and add your own mermaid code to your copy.
That will be served at <http://localhost:9000/dev/your-file-name.html>.
After making code changes, the dev server will rebuild the mermaid library. You will need to reload the browser page yourself to see the changes. (PRs for auto reload are welcome!)
## Verify Everything is Working
You can run the `test` script to verify that pnpm is working _and_ that the repository has been cloned correctly:
```bash
pnpm test
@ -64,309 +79,7 @@ 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.)
#### 4. Make your changes
Now you are ready to make your changes!
Edit whichever files in `src` as required.
#### 5. See your changes
Open <http://localhost:9000> in your browser, after starting the dev server.
There is a list of demos that can be used to see and test your changes.
If you need a specific diagram, you can duplicate the `example.html` file in `/demos/dev` and add your own mermaid code to your copy.
That will be served at <http://localhost:9000/dev/your-file-name.html>.
After making code changes, the dev server will rebuild the mermaid library. You will need to reload the browser page yourself to see the changes. (PRs for auto reload are welcome!)
### 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
The basic steps for contributing code are:
```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]
```
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.
### 1. Checkout a git branch
Mermaid uses a [Git Flow](https://guides.github.com/introduction/flow/)inspired approach to branching.
Development is done in the `develop` branch.
Once development is done we create a `release/vX.X.X` branch from `develop` for testing.
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.
**All new work should be based on the `develop` branch.**
**When you are ready to do work, always, ALWAYS:**
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.
We use the follow naming convention for branches:
```text
[feature | bug | chore | docs]/[issue number]_[short description using dashes ('-') or underscores ('_') instead of spaces]
```
- 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)
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.
**Ex: A new feature described in issue 2945 that adds a new arrow type called 'florbs' to state diagrams**
`feature/2945_state-diagram-new-arrow-florbs`
**Ex: A bug described in issue 1123 that causes random ugly red text in multiple diagram types**
`bug/1123_fix_random_ugly_red_text`
### 2. Write 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).
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 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.
When running in CI it will take a snapshot of the rendered diagram and compare it with the snapshot from last build and flag it for review if it differs.
This is what a rendering test looks like:
```js
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');
});
```
**_[TODO - running the tests against what is expected in development. ]_**
**_[TODO - how to generate new screenshots]_**
....
### 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!
If you are adding a new feature, add `(v<MERMAID_RELEASE_VERSION>+)` in the title or description. It will be replaced automatically with the current version number when the release happens.
eg: `# Feature Name (v<MERMAID_RELEASE_VERSION>+)`
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:
_[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) 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
All tests should run successfully without any errors or failures. (You might see _lint_ or _formatting_ warnings; those are ok during this step.)
## Last Words

View File

@ -0,0 +1,104 @@
# Contributing to Mermaid via Docker
> The following documentation describes how to work with Mermaid in a Docker environment.
> There's also a [host installation guide](../community/development.md)
> if you prefer to work without a Docker environment.
So you want to help? That's great!
![Image of happy people jumping with excitement](https://media.giphy.com/media/BlVnrxJgTGsUw/giphy.gif)
Here are a few things to get you started on the right path.
## Get the Source Code
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.
[Fork mermaid](https://github.com/mermaid-js/mermaid/fork) to start contributing to the main project and its documentaion, or [search for other repositories](https://github.com/orgs/mermaid-js/repositories).
[Here is a GitHub document that gives an overview of the process.](https://docs.github.com/en/get-started/quickstart/fork-a-repo)
## Technical Requirements
> The following documentation describes how to work with Mermaid in a Docker environment.
> There's also a [host installation guide](../community/development.md)
> if you prefer to work without a Docker environment.
[Install Docker](https://docs.docker.com/engine/install/). And that is pretty much all you need.
Optionally, to run GUI (Cypress) within Docker you will also need an X11 server installed.
You might already have it installed, so check this by running:
```bash
echo $DISPLAY
```
If the `$DISPLAY` variable is not empty, then an X11 server is running. Otherwise you may need to install one.
## Setup and Launch
### Switch to project
Once you have cloned the repository onto your development machine, change into the `mermaid` project folder (the top level directory of the mermaid project repository)
```bash
cd mermaid
```
### Make `./run` executable
For development using Docker there is a self-documented `run` bash script, which provides convenient aliases for `docker compose` commands.
Ensure `./run` script is executable:
```bash
chmod +x run
```
```tip
To get detailed help simply type `./run` or `./run help`.
It also has short _Development quick start guide_ embedded.
```
### Install packages
```bash
./run pnpm install # Install packages
```
### Launch
```bash
./run dev
```
Now you are ready to make your changes! Edit whichever files in `src` as required.
Open <http://localhost:9000> in your browser, after starting the dev server.
There is a list of demos that can be used to see and test your changes.
If you need a specific diagram, you can duplicate the `example.html` file in `/demos/dev` and add your own mermaid code to your copy.
That will be served at <http://localhost:9000/dev/your-file-name.html>.
After making code changes, the dev server will rebuild the mermaid library. You will need to reload the browser page yourself to see the changes. (PRs for auto reload are welcome!)
## Verify Everything is Working
```bash
./run 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.)
## 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)
![Image of superhero wishing you good luck](https://media.giphy.com/media/l49JHz7kJvl6MCj3G/giphy.gif)

View File

@ -0,0 +1,92 @@
# 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.
````markdown
```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. In that case, your branch should be based on master, not develop.
```
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:
_[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 from the branch 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) 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).

View File

@ -1,68 +0,0 @@
# Overview for Beginners
**Explaining with a Diagram**
A picture is worth a thousand words, a good diagram is undoubtedly worth more. They make understanding easier.
## Creating and Maintaining Diagrams
Anyone who has used Visio, or (God Forbid) Excel to make a Gantt Chart, knows how hard it is to create, edit and maintain good visualizations.
Diagrams/Charts are significant but also become obsolete/inaccurate very fast. This catch-22 hobbles the productivity of teams.
# Doc Rot in Diagrams
Doc-Rot kills diagrams as quickly as it does text, but it takes hours in a desktop application to produce a diagram.
Mermaid seeks to change using markdown-inspired syntax. The process is a quicker, less complicated, and more convenient way of going from concept to visualization.
It is a relatively straightforward solution to a significant hurdle with the software teams.
# Definition of Terms/ Dictionary
**Mermaid text definitions can be saved for later reuse and editing.**
> These are the Mermaid diagram definitions inside `<div>` tags, with the `class=mermaid`.
```html
<pre class="mermaid">
graph TD
A[Client] --> B[Load Balancer]
B --> C[Server01]
B --> D[Server02]
</pre>
```
**render**
> This is the core function of the Mermaid API. It reads all the `Mermaid Definitions` inside `div` tags and returns an SVG file, based on the definition.
**Nodes**
> These are the boxes that contain text or otherwise discrete pieces of each diagram, separated generally by arrows, except for Gantt Charts and User Journey Diagrams. They will be referred often in the instructions. Read for Diagram Specific [Syntax](../intro/n00b-syntaxReference.md)
## Advantages of using Mermaid
- Ease to generate, modify and render diagrams when you make them.
- The number of integrations and plugins it has.
- You can add it to your or companies website.
- Diagrams can be created through comments like this in a script:
## The catch-22 of Diagrams and Charts:
**Diagramming and charting is a large waste of developer's time, but not having diagrams ruins productivity.**
Mermaid solves this by reducing the time and effort required to create diagrams and charts.
Because, the text base for the diagrams allows it to be updated easily. Also, it can be made part of production scripts (and other pieces of code). So less time is spent on documenting, as a separate task.
## Catching up with Development
Being based on markdown, Mermaid can be used, not only by accomplished front-end developers, but by most computer savvy people to render diagrams, at much faster speeds.
In fact one can pick up the syntax for it quite easily from the examples given and there are many tutorials available in the internet.
## Mermaid is for everyone.
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

@ -0,0 +1,20 @@
# Questions or Suggestions?
**_[TODO: This section is still a WIP. It still needs MAJOR revision.]_**
## 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).

View File

@ -26,7 +26,7 @@ The definitions that can be generated the Live-Editor are also backwards-compati
## Mermaid with HTML
Examples are provided in [Getting Started](../intro/n00b-gettingStarted.md)
Examples are provided in [Getting Started](../intro/getting-started.md)
**CodePen Examples:**

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