Merge branch 'next' into sidv/FlowDB_TS

* next: (194 commits)
  Use pixelmatch for image comparison
  Run all tests
  Fix lint
  Update lockfile
  E2E test
  Use cache to store snapshots
  chore(deps): update all patch dependencies
  Change string concatenation to template literal
  Revert "Revert 5041 feature/4935 subgraph title margin config option"
  build(deps-dev): bump follow-redirects from 1.15.2 to 1.15.5
  Draft release on master
  docs: Add release version
  Revert "fix: render the participants in same order as they are created"
  Revert "Feature/4935 subgraph title margin config option"
  Fix typo
  Run dev docs without npx
  Remove npx completely from run script
  Update docs
  Fix linters
  Removed volta requirement, leave pnpm only
  ...
This commit is contained in:
Sidharth Vinod 2024-01-19 13:48:03 +05:30
commit af7282511a
No known key found for this signature in database
GPG Key ID: FB5CCD378D3907CD
135 changed files with 4198 additions and 3028 deletions

View File

@ -8,6 +8,8 @@ const buildType = (packageName: string) => {
out.length > 0 && console.log(out.toString());
} catch (e) {
console.error(e);
e.stdout.length > 0 && console.error(e.stdout.toString());
e.stderr.length > 0 && console.error(e.stderr.toString());
}
};

View File

@ -65,6 +65,9 @@ export const getBuildConfig = (options: MermaidBuildOptions): BuildOptions => {
minify,
logLevel: 'info',
chunkNames: `chunks/${outFileName}/[name]-[hash]`,
define: {
'import.meta.vitest': 'undefined',
},
});
if (core) {

View File

@ -14,5 +14,5 @@ Make sure you
- [ ] :book: have read the [contribution guidelines](https://github.com/mermaid-js/mermaid/blob/develop/CONTRIBUTING.md)
- [ ] :computer: have added necessary unit/e2e tests.
- [ ] :notebook: have added documentation. Make sure [`MERMAID_RELEASE_VERSION`](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/docs/community/development.md#3-update-documentation) is used for all new features.
- [ ] :notebook: have added documentation. Make sure [`MERMAID_RELEASE_VERSION`](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/docs/community/contributing.md#update-documentation) is used for all new features.
- [ ] :bookmark: targeted `develop` branch

View File

@ -28,7 +28,7 @@ jobs:
- if: ${{ ! env.USE_APPLI }}
name: Warn if not using Applitools
run: |
echo "::error,title=Not using Applitols::APPLITOOLS_API_KEY is empty, disabling Applitools for this run."
echo "::error,title=Not using Applitools::APPLITOOLS_API_KEY is empty, disabling Applitools for this run."
- uses: actions/checkout@v4

View File

@ -9,8 +9,42 @@ permissions:
contents: read
jobs:
cache:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 18.x
- name: Cache snapshots
id: cache-snapshot
uses: actions/cache@v4
with:
save-always: true
path: ./cypress/snapshots
key: ${{ runner.os }}-snapshots
- name: Switch to base branch
if: ${{ steps.cache-snapshot.outputs.cache-hit != 'true' }}
uses: actions/checkout@v4
with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event_name == 'merge_group' && github.event.merge_group.base.sha || 'develop' }}
- name: Cypress run
uses: cypress-io/github-action@v4
id: cypress-snapshot-gen
if: ${{ steps.cache-snapshot.outputs.cache-hit != 'true' }}
with:
start: pnpm run dev
wait-on: 'http://localhost:9000'
browser: chrome
e2e:
runs-on: ubuntu-latest
needs: cache
strategy:
fail-fast: false
matrix:
@ -27,6 +61,13 @@ jobs:
with:
node-version: ${{ matrix.node-version }}
- name: Cache snapshots
id: cache-snapshot
uses: actions/cache/restore@v3
with:
path: ./cypress/snapshots
key: ${{ runner.os }}-snapshots
# Install NPM dependencies, cache them correctly
# and run all Cypress tests
- name: Cypress run
@ -38,6 +79,7 @@ jobs:
with:
start: pnpm run dev:coverage
wait-on: 'http://localhost:9000'
browser: chrome
# Disable recording if we don't have an API key
# e.g. if this action was run from a fork
record: ${{ secrets.CYPRESS_RECORD_KEY != '' }}
@ -46,6 +88,7 @@ jobs:
CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}
VITEST_COVERAGE: true
CYPRESS_COMMIT: ${{ github.sha }}
- name: Upload Coverage to Codecov
uses: codecov/codecov-action@v3
# Run step only pushes to develop and pull_requests
@ -57,6 +100,7 @@ jobs:
fail_ci_if_error: false
verbose: true
token: 6845cc80-77ee-4e17-85a1-026cd95e0766
- name: Upload Artifacts
uses: actions/upload-artifact@v3
if: ${{ failure() && steps.cypress.conclusion == 'failure' }}

View File

@ -36,7 +36,7 @@ jobs:
restore-keys: cache-lychee-
- name: Link Checker
uses: lycheeverse/lychee-action@v1.8.0
uses: lycheeverse/lychee-action@v1.9.1
with:
args: >-
--config .github/lychee.toml

View File

@ -3,7 +3,7 @@ name: Draft Release
on:
push:
branches:
- develop
- master
permissions:
contents: read

3
.gitignore vendored
View File

@ -47,6 +47,7 @@ stats/
demos/dev/**
!/demos/dev/example.html
!/demos/dev/reload.js
tsx-0/**
# autogenereated by langium-cli
generated/
generated/

View File

@ -6,6 +6,6 @@ export default {
// https://prettier.io/docs/en/cli.html#--cache
'prettier --write',
],
'cSpell.json': ['ts-node-esm scripts/fixCSpell.ts'],
'cSpell.json': ['tsx scripts/fixCSpell.ts'],
'**/*.jison': ['pnpm -w run lint:jison'],
};

1
.npmrc
View File

@ -1,2 +1,3 @@
registry=https://registry.npmjs.org
auto-install-peers=true
strict-peer-dependencies=false

View File

@ -10,6 +10,8 @@ stats
.nyc_output
# Autogenerated by `pnpm run --filter mermaid types:build-config`
packages/mermaid/src/config.type.ts
# autogenereated by langium-cli
generated/
# Ignore the files creates in /demos/dev except for example.html
demos/dev/**
!/demos/dev/example.html

View File

@ -74,6 +74,9 @@ export const getBuildConfig = ({ minify, core, watch, entryName }: BuildOptions)
output,
},
},
define: {
'import.meta.vitest': 'undefined',
},
resolve: {
extensions: [],
},

3
.vscode/launch.json vendored
View File

@ -18,7 +18,8 @@
"type": "node",
"request": "launch",
"args": ["scripts/docs.cli.mts"],
"runtimeArgs": ["--loader", "ts-node/esm"],
// we'll need to change this to --import in Node.JS v20.6.0 and up
"runtimeArgs": ["--loader", "tsx/esm"],
"cwd": "${workspaceRoot}/packages/mermaid",
"skipFiles": ["<node_internals>/**", "**/node_modules/**"],
"smartStep": true,

View File

@ -1,78 +0,0 @@
# Contributing
Please read in detail about how to contribute documentation and code on the [Mermaid documentation site.](https://mermaid-js.github.io/mermaid/#/development)
---
# Mermaid contribution cheat-sheet
## Requirements
- [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`
## Development Installation
If you don't have direct access to push to mermaid repositories, make a fork first. Then clone. Or clone directly from mermaid-js:
```bash
git clone git@github.com:mermaid-js/mermaid.git
cd mermaid
```
Install required packages:
```bash
# npx is required for first install as volta support for pnpm is not added yet.
npx pnpm install
pnpm test # run unit tests
pnpm dev # starts a dev server
```
Open <http://localhost:9000> in your browser after starting the dev server.
You can also duplicate the `example.html` file in `demos/dev`, rename it and add your own mermaid code to it.
That will be served at <http://localhost:9000/dev/your-file-name.html>.
### 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
```
## Testing
```bash
# Run unit test
pnpm test
# Run unit test in watch mode
pnpm test:watch
# Run E2E test
pnpm e2e
# Debug E2E tests
pnpm dev
pnpm cypress:open # in another terminal
```
## Branch name format:
```text
[feature | bug | chore | docs]/[issue number]_[short description using dashes ('-') or underscores ('_') instead of spaces]
```
eg: `feature/2945_state-diagram-new-arrow-florbs`, `bug/1123_fix_random_ugly_red_text`
## Documentation
Documentation is necessary for all non bugfix/refactoring changes.
Only make changes to files that are in [`/packages/mermaid/src/docs`](packages/mermaid/src/docs)
**_DO NOT CHANGE FILES IN `/docs` MANUALLY_**
The `/docs` folder will be rebuilt and committed as part of a pre-commit hook.
[Join our slack community if you want closer contact!](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE)

1
CONTRIBUTING.md Symbolic link
View File

@ -0,0 +1 @@
./packages/mermaid/src/docs/community/contributing.md

2
Dockerfile Normal file
View File

@ -0,0 +1,2 @@
FROM node:18.19.0-alpine3.18 AS base
RUN wget -qO- https://get.pnpm.io/install.sh | ENV="$HOME/.shrc" SHELL="$(which sh)" sh -

View File

@ -74,12 +74,12 @@ Mermaid addresses this problem by enabling users to create easily modifiable dia
<br/>
Mermaid allows even non-programmers to easily create detailed diagrams through the [Mermaid Live Editor](https://mermaid.live/).<br/>
For video tutorials, visit our [Tutorials](./docs/config/Tutorials.md) page.
For video tutorials, visit our [Tutorials](./docs/ecosystem/tutorials.md) page.
Use Mermaid with your favorite applications, check out the list of [Integrations and Usages of Mermaid](./docs/ecosystem/integrations-community.md).
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-community.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).
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/ecosystem/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

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

View File

@ -26,6 +26,7 @@
"città",
"classdef",
"codedoc",
"codemia",
"colour",
"commitlint",
"cpettitt",
@ -105,6 +106,7 @@
"pathe",
"pbrolin",
"phpbb",
"pixelmatch",
"plantuml",
"playfair",
"pnpm",
@ -127,6 +129,7 @@
"sidharth",
"sidharthv",
"sphinxcontrib",
"ssim",
"startx",
"starty",
"statediagram",

View File

@ -6,10 +6,18 @@ const coverage = require('@cypress/code-coverage/task');
module.exports = defineConfig({
projectId: 'n2sma2',
viewportWidth: 1440,
viewportHeight: 1024,
e2e: {
specPattern: 'cypress/integration/**/*.{js,jsx,ts,tsx}',
specPattern: 'cypress/integration/**/*.{js,ts}',
setupNodeEvents(on, config) {
coverage(on, config);
on('before:browser:launch', (browser = {}, launchOptions) => {
if (browser.name === 'chrome' && browser.isHeadless) {
launchOptions.args.push('--window-size=1440,1024', '--force-device-scale-factor=1');
}
return launchOptions;
});
addMatchImageSnapshotPlugin(on, config);
// copy any needed variables from process.env to config.env
config.env.useAppli = process.env.USE_APPLI ? true : false;

View File

@ -10,7 +10,7 @@ interface CypressConfig {
type CypressMermaidConfig = MermaidConfig & CypressConfig;
interface CodeObject {
code: string;
code: string | string[];
mermaid: CypressMermaidConfig;
}
@ -25,7 +25,7 @@ const batchId: string =
: Cypress.env('CYPRESS_COMMIT') || Date.now().toString());
export const mermaidUrl = (
graphStr: string,
graphStr: string | string[],
options: CypressMermaidConfig,
api: boolean
): string => {
@ -82,7 +82,7 @@ export const urlSnapshotTest = (
};
export const renderGraph = (
graphStr: string,
graphStr: string | string[],
options: CypressMermaidConfig = {},
api = false
): void => {

View File

@ -117,7 +117,6 @@ describe('Configuration', () => {
});
it('should not taint the initial configuration when using multiple directives', () => {
const url = 'http://localhost:9000/regression/issue-1874.html';
cy.viewport(1440, 1024);
cy.visit(url);
cy.get('svg');

View File

@ -1,14 +1,12 @@
describe('Rerendering', () => {
it('should be able to render after an error has occurred', () => {
const url = 'http://localhost:9000/render-after-error.html';
cy.viewport(1440, 1024);
cy.visit(url);
cy.get('#graphDiv').should('exist');
});
it('should be able to render and rerender a graph via API', () => {
const url = 'http://localhost:9000/rerender.html';
cy.viewport(1440, 1024);
cy.visit(url);
cy.get('#graph [id^=flowchart-A]').should('have.text', 'XMas');

View File

@ -571,4 +571,14 @@ class C13["With Città foreign language"]
{ logLevel: 1, flowchart: { htmlLabels: false } }
);
});
it('should render a simple class diagram with style definition', () => {
imgSnapshotTest(
`
classDiagram-v2
class Class10
style Class10 fill:#f9f,stroke:#333,stroke-width:4px
`,
{ logLevel: 1, flowchart: { htmlLabels: false } }
);
});
});

View File

@ -729,6 +729,18 @@ A ~~~ B
{}
);
});
it('5064: Should render when subgraph child has links to outside node and subgraph', () => {
imgSnapshotTest(
`flowchart TB
Out --> In
subgraph Sub
In
end
Sub --> In`
);
});
describe('Markdown strings flowchart (#4220)', () => {
describe('html labels', () => {
it('With styling and classes', () => {
@ -874,4 +886,93 @@ end
});
});
});
describe('Subgraph title margins', () => {
it('Should render subgraphs with title margins set (LR)', () => {
imgSnapshotTest(
`flowchart LR
subgraph TOP
direction TB
subgraph B1
direction RL
i1 -->f1
end
subgraph B2
direction BT
i2 -->f2
end
end
A --> TOP --> B
B1 --> B2
`,
{ flowchart: { subGraphTitleMargin: { top: 10, bottom: 5 } } }
);
});
it('Should render subgraphs with title margins set (TD)', () => {
imgSnapshotTest(
`flowchart TD
subgraph TOP
direction LR
subgraph B1
direction RL
i1 -->f1
end
subgraph B2
direction BT
i2 -->f2
end
end
A --> TOP --> B
B1 --> B2
`,
{ flowchart: { subGraphTitleMargin: { top: 8, bottom: 16 } } }
);
});
it('Should render subgraphs with title margins set (LR) and htmlLabels set to false', () => {
imgSnapshotTest(
`flowchart LR
subgraph TOP
direction TB
subgraph B1
direction RL
i1 -->f1
end
subgraph B2
direction BT
i2 -->f2
end
end
A --> TOP --> B
B1 --> B2
`,
{
htmlLabels: false,
flowchart: { htmlLabels: false, subGraphTitleMargin: { top: 10, bottom: 5 } },
}
);
});
it('Should render subgraphs with title margins and edge labels', () => {
imgSnapshotTest(
`flowchart LR
subgraph TOP
direction TB
subgraph B1
direction RL
i1 --lb1-->f1
end
subgraph B2
direction BT
i2 --lb2-->f2
end
end
A --lb3--> TOP --lb4--> B
B1 --lb5--> B2
`,
{ flowchart: { subGraphTitleMargin: { top: 10, bottom: 5 } } }
);
});
});
});

View File

@ -245,7 +245,10 @@ describe('Gantt diagram', () => {
const style = svg.attr('style');
expect(style).to.match(/^max-width: [\d.]+px;$/);
const maxWidthValue = parseFloat(style.match(/[\d.]+/g).join(''));
expect(maxWidthValue).to.be.within(984 * 0.95, 984 * 1.05);
expect(maxWidthValue).to.be.within(
Cypress.config().viewportWidth * 0.95,
Cypress.config().viewportWidth * 1.05
);
});
});
@ -285,11 +288,11 @@ describe('Gantt diagram', () => {
{ gantt: { useMaxWidth: false } }
);
cy.get('svg').should((svg) => {
// const height = parseFloat(svg.attr('height'));
const width = parseFloat(svg.attr('width'));
// use within because the absolute value can be slightly different depending on the environment ±5%
// expect(height).to.be.within(484 * 0.95, 484 * 1.05);
expect(width).to.be.within(984 * 0.95, 984 * 1.05);
expect(width).to.be.within(
Cypress.config().viewportWidth * 0.95,
Cypress.config().viewportWidth * 1.05
);
expect(svg).to.not.have.attr('style');
});
});

View File

@ -811,4 +811,19 @@ gitGraph TB:
{}
);
});
it('40: should render a simple gitgraph with cherry pick merge commit', () => {
imgSnapshotTest(
`gitGraph
commit id: "ZERO"
branch feature
branch release
checkout feature
commit id: "A"
commit id: "B"
checkout main
merge feature id: "M"
checkout release
cherry-pick id: "M" parent:"B"`
);
});
});

View File

@ -44,7 +44,7 @@ describe('pie chart', () => {
const style = svg.attr('style');
expect(style).to.match(/^max-width: [\d.]+px;$/);
const maxWidthValue = parseFloat(style.match(/[\d.]+/g).join(''));
expect(maxWidthValue).to.eq(984);
expect(maxWidthValue).to.be.within(590, 600); // depends on installed fonts: 596.2 on my PC, 597.5 on CI
});
});
@ -59,7 +59,7 @@ describe('pie chart', () => {
);
cy.get('svg').should((svg) => {
const width = parseFloat(svg.attr('width'));
expect(width).to.eq(984);
expect(width).to.be.within(590, 600); // depends on installed fonts: 596.2 on my PC, 597.5 on CI
expect(svg).to.not.have.attr('style');
});
});

View File

@ -930,4 +930,36 @@ context('Sequence diagram', () => {
});
});
});
context('render after error', () => {
it('should render diagram after fixing destroy participant error', () => {
cy.on('uncaught:exception', (err) => {
return false;
});
renderGraph([
`sequenceDiagram
Alice->>Bob: Hello Bob, how are you ?
Bob->>Alice: Fine, thank you. And you?
create participant Carl
Alice->>Carl: Hi Carl!
create actor D as Donald
Carl->>D: Hi!
destroy Carl
Alice-xCarl: We are too many
destroy Bo
Bob->>Alice: I agree`,
`sequenceDiagram
Alice->>Bob: Hello Bob, how are you ?
Bob->>Alice: Fine, thank you. And you?
create participant Carl
Alice->>Carl: Hi Carl!
create actor D as Donald
Carl->>D: Hi!
destroy Carl
Alice-xCarl: We are too many
destroy Bob
Bob->>Alice: I agree`,
]);
});
});
});

View File

@ -24,8 +24,18 @@
// -- This is will overwrite an existing command --
// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })
// import '@percy/cypress';
import { addMatchImageSnapshotCommand } from 'cypress-image-snapshot/command';
// The SSIM comparison method can be used if the pixelmatch is throwing lots of false positives.
// SSIM actually does not catch minute changes in the image, so it is not as accurate as pixelmatch.
// addMatchImageSnapshotCommand({
// comparisonMethod: 'ssim',
// failureThreshold: 0.01,
// failureThresholdType: 'percent',
// customDiffConfig: {
// ssim: 'fast',
// },
// blur: 1,
// });
addMatchImageSnapshotCommand();

View File

@ -33,6 +33,7 @@
---
config:
sankey:
useMaxWidth: true
showValues: false
width: 1200
height: 600

View File

@ -164,13 +164,6 @@
end
</pre>
<pre class="mermaid">
sequenceDiagram
actor Alice
actor John
Alice-xJohn: Hello John, how are you?
John--xAlice: Great!
</pre>
<script type="module">
import mermaid from './mermaid.esm.mjs';
mermaid.initialize({

View File

@ -1,13 +1,16 @@
version: '3.9'
services:
mermaid:
image: node:18.18.2-alpine3.18
build:
context: .
dockerfile: Dockerfile
stdin_open: true
tty: true
working_dir: /mermaid
mem_limit: '4G'
mem_limit: '8G'
entrypoint: '/mermaid/docker-entrypoint.sh'
environment:
- NODE_OPTIONS=--max_old_space_size=4096
- NODE_OPTIONS=--max_old_space_size=8192
volumes:
- ./:/mermaid
- root_cache:/root/.cache

3
docker-entrypoint.sh Executable file
View File

@ -0,0 +1,3 @@
#!/bin/sh
source /root/.shrc
exec "$@"

View File

@ -1,176 +0,0 @@
> **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 following 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

@ -0,0 +1,521 @@
> **Warning**
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/community/contributing.md](../../packages/mermaid/src/docs/community/contributing.md).
# Mermaid Contributing Guide
You decided to take part in the development? Welcome!
We are trying to make our guidelines for you as explicit and detailed as possible.
## Initial Setup
Initial setup consists of 3 main steps:
```mermaid
flowchart LR
source --> requirements --> setup
source[Get the Source Code]
requirements[Install the Requirements]
setup[Install Packages]
```
### Get the Source Code
In GitHub, you first [**fork a mermaid repository**](https://github.com/mermaid-js/mermaid/fork) 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.
> **💡 Tip** > [Here is a GitHub document that gives an overview of the process](https://docs.github.com/en/get-started/quickstart/fork-a-repo).
```bash
git clone git@github.com/your-fork/mermaid
```
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
```
### Install Requirements
We support **development within Docker** environment along with **host setup**. You may choose it up to your preferences.
**Host**
These are the tools we use for working with the code and documentation:
- [Node.js](https://nodejs.org/en/).
- [pnpm](https://pnpm.io/) package manager.
The following commands must be sufficient enough to start with:
```bash
curl -fsSL https://get.pnpm.io/install.sh | sh -
pnpm env use --global 18
```
You may also need to reload `.shrc` or `.bashrc` afterwards.
**Docker**
[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.
### Install Packages
**Host**
Install packages:
```bash
pnpm install
```
**Docker**
For development using Docker there is a self-documented `run` bash script, which provides convenient aliases for `docker compose` commands.
Make sure that `./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.
Then install packages:
```bash
./run pnpm install
```
### Verify Everything Works
This step is optional, but it helps to make sure that everything in development branch was OK before you started making any changes.
You can run the `test` script to verify that pnpm is working _and_ that the repository has been cloned correctly:
**Host**
```bash
pnpm test
```
**Docker**
```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.
> **Note**
> You might see _lint_ or _formatting_ warnings. Those are ok during this step.
## Workflow
Contributing process is very simple and strightforward:
```mermaid
flowchart LR
branch --> changes --> submit
branch[Checkout a New Branch]
changes[Make Changes]
submit[Submit a PR]
```
Mermaid uses a [Git Flow](https://guides.github.com/introduction/flow/)inspired approach to branching.
Development is done in the `develop` branch.
```mermaid
---
config:
gitGraph:
mainBranchName: develop
---
gitGraph LR:
commit
commit
branch "docs/2910_update-guidelines" order: 1
commit
commit
commit
checkout develop
merge "docs/2910_update-guidelines"
commit
```
To prepare a new version for release the maintainers 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.
## Checkout a New Branch
> **💡 Tip**
> All new work should be based on the `develop` branch.
Make sure you have the most up-to-date version of the `develop` branch.
Check out the `develop` branch, then `fetch` or `pull` to update it:
```bash
git checkout develop
git fetch # or `git pull`
```
Create a new branch for your work:
```bash
git checkout -b docs/2910_update-contributing-guidelines
```
We use the following naming convention for branches:
```txt
[feature | bug | chore | docs]/[issue number]_[short-description]
```
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`, `docs`
- followed by a **slash** (`/`),which helps to group like types together in many git tools
- followed by the **issue number**, e.g. `2910`
- followed by an **underscore** (`_`)
- followed by a **short description** with dashes (`-`) or underscores (`_`) instead of spaces
```mermaid
flowchart LR
feature --> slash
bug --> slash
chore --> slash
docs --> slash
slash --> 2945 --> underscore
slash --> 1123 --> underscore
underscore --> short_description_1
underscore --> short_description_2
underscore["_"]
slash["/"]
short_description_1["state-diagram-new-arrow-florbs"]
short_description_2["fix_random_ugly_red_text"]
```
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 by a diagram type.
> **Note**
> 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`
> **💡 Tip**
> A bug described in issue 1123 that causes random ugly red text in multiple diagram types
>
> `bug/1123_fix_random_ugly_red_text`
## Contributing Code
Code is the heart of every software project. We strive to make it better. Who if not us?
### Where is the Code Located?
The core of Mermaid is located under `packages/mermaid/src`.
### Running Mermaid Locally
**Host**
```bash
pnpm run dev
```
**Docker**
```bash
./run dev
```
After starting the dev server open <http://localhost:9000> in your browser.
Now you are ready to make your changes!
### Make Changes
Have a look at <http://localhost:9000>. 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 and automatically reload the page.
Edit files in `packages/mermaid/src` as required.
### 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 for all code except the renderers. (The renderers are tested with integration tests.)
We use [Vitest](https://vitest.dev) to run unit tests.
**Host**
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
```
**Docker**
When using Docker prepend your command with `./run`:
```sh
./run pnpm test
```
#### 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:
**Host**
- Run `pnpm dev` to start the dev server
- Start **Cypress** by running `pnpm cypress:open`
**Docker**
- Enable local connections for x11 server `xhost +local:`
- Run `./run pnpm dev` to start the dev server
- Start **Cypress** by running `./run pnpm cypress:open --project .`
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 }
);
});
```
<!-- **_[TODO - running the tests against what is expected in development. ]_** -->
<!-- **_[TODO - how to generate new screenshots]_** -->
### Update Documentation
> **💡 Tip**
> Our documentation is managed in `packages/mermaid/src/docs`. Details on how to edit is in the [documentation section](#contributing-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 for users to know that things have been 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.
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!)
## Contributing Documentation
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?
### Where is the Documentation Located?
> **Warning**
> DO NOT CHANGE FILES IN `/docs`
>
> The `docs` folder will be automatically generated when committing to `packages/mermaid/src/docs` and **should not** be edited manually.
Documentation is located in the [`packages/mermaid/src/docs`](https://github.com/mermaid-js/mermaid/tree/develop/packages/mermaid/src/docs) folder. 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.
```mermaid-example
flowchart LR
classDef default fill:#fff,color:black,stroke:black
source["Edit /packages/mermaid/src/docs"] -- automatic processing--> published["View /docs which will be publised on Official Website"]
```
```mermaid
flowchart LR
classDef default fill:#fff,color:black,stroke:black
source["Edit /packages/mermaid/src/docs"] -- automatic processing--> published["View /docs which will be publised on Official Website"]
```
### Running the Documentation Website Locally
**[The mermaid documentation site](https://mermaid.js.org/) is powered by [Vitepress](https://vitepress.vuejs.org/).**
Start development server for the documentation site
**Host**
```bash
pnpm --filter mermaid run docs:dev
```
or
```bash
cd packages/mermaid
pnpm docs:dev
```
**Docker**
```bash
./run docs:dev
```
Open <http://localhost:3333/> in your browser.
### Formatting
The documentation is written in Markdown. To get acquainted with its syntax [see the GitHub Markdown help page](https://help.github.com/en/github/writing-on-github/basic-writing-and-formatting-syntax).
You can use `note`, `tip`, `warning` and `danger` in triple backticks to add a note, tip, warning or danger box.
> **‼️ Danger**
> Do not use vitepress specific markdown syntax `::: warning` as it will not be processed correctly.
Here are a few examples:
````markdown
```note
This is a note
```
```tip
This is a tip
```
```warning
This is a warning
```
```danger
This is a danger alert
```
````
> **Note**
> This is a note
> **💡 Tip**
> This is a tip
> **Warning**
> This is a warning
> **‼️ Danger**
> This is a danger alert
### 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**, which is defined in [the vitepress config](../.vitepress/config.ts). The same goes to **topbar**.
### Build Docs
The content of `/docs` folder is built with Github Actions.
> **Warning**
> So as to allow automatic compilation of documentation pages you have to enable Github Actions on your fork first
## Submit your pull request
> **Note**
> Do not forget to push your changes
>
> ```bash
> git push -u origin docs/2910_update-guidelines
> ```
We make all changes via Pull Requests (PRs). Open a new one.
Right now we are not following any strict rules about naming PRs. Give it a representative title and short description. There is also a [pull request template](https://github.com/mermaid-js/mermaid/blob/develop/.github/pull_request_template.md) which will help you with it.
In case in its description contains a [magic comment](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) your PR will be automatically attached to the issue:
```markdown
Resolves #<your issue ID here>
```
## Congratulations
You have successfully submitted your improvements! What is next?
- 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.
Thanks for you help!

View File

@ -1,96 +0,0 @@
> **Warning**
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/community/development.md](../../packages/mermaid/src/docs/community/development.md).
# Contributing to Mermaid
> 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!
![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 documentation, 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.](#install-packages)
Follow the setup steps below to install them and start the development.
## 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
```
### Install packages
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
```
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

@ -1,109 +0,0 @@
> **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 documentation, 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

@ -1,105 +0,0 @@
> **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).

60
docs/community/intro.md Normal file
View File

@ -0,0 +1,60 @@
> **Warning**
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/community/intro.md](../../packages/mermaid/src/docs/community/intro.md).
# Getting Started
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.
## How can I help?
```mermaid
mindmap
root)Contributing(
Development
Solving issues
Adding new diagrams
Handling pull requests
Updating tooling
Testing
Verification of fixed issues
Regression testing in connection with releases
Testing pull requests
Management
Coordinating the work
Classification and monitoring of incoming issues
```
## Join the Development
> **💡 Tip** > **Check out our** [**detailed contribution guide**](./contributing.md).
Where to start:
- You could start getting some knowledge of the code base by working on [these "good first issues"](https://github.com/mermaid-js/mermaid/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+label%3A%22Good+first+issue%21%22+).
- You could jump right in and help us fix any of [these bugs](https://github.com/mermaid-js/mermaid/issues?q=is%3Aissue+is%3Aopen+label%3A%22Type%3A+Bug+%2F+Error%22++label%3A%22Contributor+needed%22+)!
- You could help write and [improve the documentation](https://github.com/mermaid-js/mermaid/issues?q=is%3Aissue+is%3Aopen+label%3A%22Area%3A+Documentation%22).
- You could work on a new feature! [These](https://github.com/mermaid-js/mermaid/issues?q=is%3Aissue+is%3Aopen+label%3A%22Area%3A+Development%22+label%3A%22Type%3A+Enhancement%22+label%3A%22Status%3A+Approved%22+) are some ideas!
- You could confirm the bugs in [these issues](https://github.com/mermaid-js/mermaid/issues?q=is%3Aissue+is%3Aopen+label%3A%22Status%3A+Triage%22++label%3A%22Type%3A+Bug+%2F+Error%22).
[Join our slack community if you want closer contact!](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE)
## A Question Or a Suggestion?
> **💡 Tip** > **Have a look at** [**how to open an issue**](./questions-and-suggestions.md).
If you have faced a vulnerability [report it to us](./security.md).
## 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

@ -2,7 +2,7 @@
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/community/newDiagram.md](../../packages/mermaid/src/docs/community/newDiagram.md).
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/community/new-diagram.md](../../packages/mermaid/src/docs/community/new-diagram.md).
# Adding a New Diagram/Chart 📊

View File

@ -6,20 +6,20 @@
# Questions or Suggestions?
**_\[TODO: This section is still a WIP. It still needs MAJOR revision.]_**
## Search for Existing Issue
## First search to see if someone has already asked (and hopefully been answered) or suggested the same thing.
First search to see if someone has already asked (and hopefully been answered) or suggested the same thing.
- [Search in Discussions](https://github.com/orgs/mermaid-js/discussions)
- [Search in Issues (Open & Closed)](https://github.com/mermaid-js/mermaid/issues?q=is%3Aissue)
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.
Use the GitHub reactions to add a thumbs-up to the issue or discussion thread, or append to the issue if needed.
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.
## Add a new Issue
If you can't find anything that already addresses your question or suggestion, _open a new issue:_
You have not found anything that already addresses your request, or maybe you have come up with the new idea? Feel free to open a new issue or discussion.
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).
Log in to [GitHub.com](https://www.github.com), and use [GitHub issue tracker of the mermaid-js repository](https://github.com/mermaid-js/mermaid/issues). Press \[<https://github.com/mermaid-js/mermaid/issues/new/choose>] issue, select the appropriate template and describe your problem.

View File

@ -1,30 +0,0 @@
> **Warning**
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/config/advanced.md](../../packages/mermaid/src/docs/config/advanced.md).
# Advanced mermaid (Coming soon..)
## splitting mermaid code from html
A more condensed html code can be achieved by embedding the mermaid code in its own .js file, which is referenced like so:
```html
...
</div>
</body>
</html>
```
The actual mermaid file could for example look like this:
```javascript
mermaid content ...
```
## mermaid configuration options
```markdown
(coming soon)
```

View File

@ -14,6 +14,9 @@
`Optional` **suppressErrors**: `boolean`
If `true`, parse will return `false` instead of throwing error when the diagram is invalid.
The `parseError` function will not be called.
#### Defined in
[mermaidAPI.ts:60](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L60)
[mermaidAPI.ts:64](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L64)

View File

@ -0,0 +1,21 @@
> **Warning**
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/config/setup/interfaces/mermaidAPI.ParseResult.md](../../../../packages/mermaid/src/docs/config/setup/interfaces/mermaidAPI.ParseResult.md).
# Interface: ParseResult
[mermaidAPI](../modules/mermaidAPI.md).ParseResult
## Properties
### diagramType
**diagramType**: `string`
The diagram type, e.g. 'flowchart', 'sequence', etc.
#### Defined in
[mermaidAPI.ts:71](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L71)

View File

@ -39,7 +39,19 @@ bindFunctions?.(div); // To call bindFunctions only if it's present.
#### Defined in
[mermaidAPI.ts:80](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L80)
[mermaidAPI.ts:94](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L94)
---
### diagramType
**diagramType**: `string`
The diagram type, e.g. 'flowchart', 'sequence', etc.
#### Defined in
[mermaidAPI.ts:84](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L84)
---
@ -51,4 +63,4 @@ The svg code for the rendered graph.
#### Defined in
[mermaidAPI.ts:70](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L70)
[mermaidAPI.ts:80](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L80)

View File

@ -9,6 +9,7 @@
## Interfaces
- [ParseOptions](../interfaces/mermaidAPI.ParseOptions.md)
- [ParseResult](../interfaces/mermaidAPI.ParseResult.md)
- [RenderResult](../interfaces/mermaidAPI.RenderResult.md)
## References
@ -25,13 +26,13 @@ Renames and re-exports [mermaidAPI](mermaidAPI.md#mermaidapi)
#### Defined in
[mermaidAPI.ts:64](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L64)
[mermaidAPI.ts:74](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L74)
## Variables
### mermaidAPI
`Const` **mermaidAPI**: `Readonly`<{ `defaultConfig`: `MermaidConfig` = configApi.defaultConfig; `getConfig`: () => `MermaidConfig` = configApi.getConfig; `getDiagramFromText`: (`text`: `string`, `metadata`: `Pick`<`DiagramMetadata`, `"title"`>) => `Promise`<`Diagram`> ; `getSiteConfig`: () => `MermaidConfig` = configApi.getSiteConfig; `globalReset`: () => `void` ; `initialize`: (`options`: `MermaidConfig`) => `void` ; `parse`: (`text`: `string`, `parseOptions?`: [`ParseOptions`](../interfaces/mermaidAPI.ParseOptions.md)) => `Promise`<`boolean`> ; `render`: (`id`: `string`, `text`: `string`, `svgContainingElement?`: `Element`) => `Promise`<[`RenderResult`](../interfaces/mermaidAPI.RenderResult.md)> ; `reset`: () => `void` ; `setConfig`: (`conf`: `MermaidConfig`) => `MermaidConfig` = configApi.setConfig; `updateSiteConfig`: (`conf`: `MermaidConfig`) => `MermaidConfig` = configApi.updateSiteConfig }>
`Const` **mermaidAPI**: `Readonly`<{ `defaultConfig`: `MermaidConfig` = configApi.defaultConfig; `getConfig`: () => `MermaidConfig` = configApi.getConfig; `getDiagramFromText`: (`text`: `string`, `metadata`: `Pick`<`DiagramMetadata`, `"title"`>) => `Promise`<`Diagram`> ; `getSiteConfig`: () => `MermaidConfig` = configApi.getSiteConfig; `globalReset`: () => `void` ; `initialize`: (`options`: `MermaidConfig`) => `void` ; `parse`: (`text`: `string`, `parseOptions`: [`ParseOptions`](../interfaces/mermaidAPI.ParseOptions.md) & { `suppressErrors`: `true` }) => `Promise`<[`ParseResult`](../interfaces/mermaidAPI.ParseResult.md) | `false`>(`text`: `string`, `parseOptions?`: [`ParseOptions`](../interfaces/mermaidAPI.ParseOptions.md)) => `Promise`<[`ParseResult`](../interfaces/mermaidAPI.ParseResult.md)> ; `render`: (`id`: `string`, `text`: `string`, `svgContainingElement?`: `Element`) => `Promise`<[`RenderResult`](../interfaces/mermaidAPI.RenderResult.md)> ; `reset`: () => `void` ; `setConfig`: (`conf`: `MermaidConfig`) => `MermaidConfig` = configApi.setConfig; `updateSiteConfig`: (`conf`: `MermaidConfig`) => `MermaidConfig` = configApi.updateSiteConfig }>
## mermaidAPI configuration defaults
@ -96,7 +97,7 @@ mermaid.initialize(config);
#### Defined in
[mermaidAPI.ts:603](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L603)
[mermaidAPI.ts:623](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L623)
## Functions
@ -127,7 +128,7 @@ Return the last node appended
#### Defined in
[mermaidAPI.ts:263](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L263)
[mermaidAPI.ts:277](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L277)
---
@ -153,7 +154,7 @@ the cleaned up svgCode
#### Defined in
[mermaidAPI.ts:209](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L209)
[mermaidAPI.ts:223](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L223)
---
@ -178,7 +179,7 @@ the string with all the user styles
#### Defined in
[mermaidAPI.ts:139](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L139)
[mermaidAPI.ts:153](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L153)
---
@ -201,7 +202,7 @@ the string with all the user styles
#### Defined in
[mermaidAPI.ts:186](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L186)
[mermaidAPI.ts:200](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L200)
---
@ -228,7 +229,7 @@ with an enclosing block that has each of the cssClasses followed by !important;
#### Defined in
[mermaidAPI.ts:124](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L124)
[mermaidAPI.ts:138](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L138)
---
@ -254,7 +255,7 @@ Put the svgCode into an iFrame. Return the iFrame code
#### Defined in
[mermaidAPI.ts:240](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L240)
[mermaidAPI.ts:254](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L254)
---
@ -279,4 +280,4 @@ Remove any existing elements from the given document
#### Defined in
[mermaidAPI.ts:313](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L313)
[mermaidAPI.ts:327](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L327)

View File

@ -20,7 +20,7 @@ Please note that you can switch versions through the dropdown box at the top rig
For the majority of users, Using the [Live Editor](https://mermaid.live/) would be sufficient, however you may also opt to deploy mermaid as a dependency or using the [Mermaid API](./setup/README.md).
We have compiled some Video [Tutorials](./Tutorials.md) on how to use the Mermaid Live Editor.
We have compiled some Video [Tutorials](../ecosystem/tutorials.md) on how to use the Mermaid Live Editor.
### Installing and Hosting Mermaid on a Webpage
@ -331,15 +331,17 @@ module.exports = (options) ->
## Advanced usage
**Syntax validation without rendering (Work in Progress)**
### Syntax validation without rendering
The **mermaid.parse(txt)** function validates graph definitions without rendering a graph. **[This function is still a work in progress](https://github.com/mermaid-js/mermaid/issues/1066), find alternatives below.**
The `mermaid.parse(text, parseOptions)` function validates graph definitions without rendering a graph.
The function **mermaid.parse(txt)**, takes a text string as an argument and returns true if the definition follows mermaid's syntax and
false if it does not. The parseError function will be called when the parse function returns false.
The function `mermaid.parse(text, parseOptions)`, takes a text string as an argument and returns `{ diagramType: string }` if the definition follows mermaid's syntax.
When the parser encounters invalid syntax the **mermaid.parseError** function is called. It is possible to override this
function in order to handle the error in an application-specific way.
If the definition is invalid, the function returns `false` if `parseOptions.suppressErrors` is set to `true`. Otherwise, it throws an error.
The parseError function will be called when the parse function throws an error. It will not be called if `parseOptions.suppressErrors` is set to `true`.
It is possible to override this function in order to handle the error in an application-specific way.
The code-example below in meta code illustrates how this could work:
@ -359,26 +361,10 @@ const textFieldUpdated = async function () {
bindEventHandler('change', 'code', textFieldUpdated);
```
**Alternative to mermaid.parse():**
One effective and more future-proof method of validating your graph definitions, is to paste and render them via the [Mermaid Live Editor](https://mermaid.live/). This will ensure that your code is compliant with the syntax of Mermaid's most recent version.
## Configuration
Mermaid takes a number of options which lets you tweak the rendering of the diagrams. Currently there are three ways of
setting the options in mermaid.
1. Instantiation of the configuration using the initialize call
2. _Using the global mermaid object_ - **Deprecated**
3. _using the global mermaid_config object_ - **Deprecated**
4. Instantiation of the configuration using the **mermaid.init** call- **Deprecated**
The list above has two ways too many of doing this. Three are deprecated and will eventually be removed. The list of
configuration objects are described [in the mermaidAPI documentation](./setup/README.md).
## Using the `mermaidAPI.initialize`/`mermaid.initialize` call
The future proof way of setting the configuration is by using the initialization call to mermaid or mermaidAPI depending
on what kind of integration you use.
You can pass the required configuration to the `mermaid.initialize` call. This is the preferred way of configuring mermaid.
The list of configuration objects are described [in the mermaidAPI documentation](./setup/README.md).
```html
<script type="module">
@ -407,32 +393,3 @@ mermaid.startOnLoad = true;
> **Warning**
> This way of setting the configuration is deprecated. Instead the preferred way is to use the initialize method. This functionality is only kept for backwards compatibility.
## Using the mermaid_config
It is possible to set some configuration via the mermaid object. The two parameters that are supported using this
approach are:
- mermaid_config.startOnLoad
- mermaid_config.htmlLabels
```javascript
mermaid_config.startOnLoad = true;
```
> **Warning**
> This way of setting the configuration is deprecated. Instead the preferred way is to use the initialize method. This functionality is only kept for backwards compatibility.
## Using the mermaid.init call
To set some configuration via the mermaid object. The two parameters that are supported using this approach are:
- mermaid_config.startOnLoad
- mermaid_config.htmlLabels
```javascript
mermaid_config.startOnLoad = true;
```
> **Warning**
> This way of setting the configuration is deprecated. Instead the preferred way is to use the initialize method. This functionality is only kept for backwards compatibility.

View File

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 38 KiB

View File

@ -6,18 +6,27 @@
# Integrations
## Official integration: [Mermaid Chart](./mermaid-chart.md)
## Official integration
We're excited about the growth of the Mermaid community, and the number of plugins and integrations that have been created with Mermaid.
### Mermaid Chart
Mermaid Chart is built by the team behind Mermaid JS.
For more details, visit the [Mermaid Chart page](./mermaid-chart.md), or visit the [Mermaid Chart website](https://www.mermaidchart.com) .
## Community integrations
Below are a list of community plugins and integrations created with Mermaid.
We're excited about the growth of the Mermaid community, and the number of plugins and integrations that have been created by the community.
See the list below of community plugins and integrations created with Mermaid.
> **Note**
> A ✅ indicates Native support for Mermaid on the respective platform.
To add an integration to this list, see the [Integrations - create page](./integrations-create.md).
### Productivity tools
✅ = Native support
- [GitHub](https://github.com) ✅
- [Using code blocks](https://github.blog/2022-02-14-include-diagrams-markdown-files-mermaid/) ✅
- [GitHub action: Compile mermaid to image](https://github.com/neenjaw/compile-mermaid-markdown-action)
@ -61,6 +70,7 @@ Below are a list of community plugins and integrations created with Mermaid.
- [Mermaid Plugin for JetBrains IDEs](https://plugins.jetbrains.com/plugin/20146-mermaid)
- [mermerd](https://github.com/KarnerTh/mermerd)
- Visual Studio Code [Polyglot Interactive Notebooks](https://github.com/dotnet/interactive#net-interactive)
- Codemia [a tool to practice system design problems](https://codemia.io)
### CRM/ERP
@ -111,6 +121,8 @@ Communication tools and platforms
### Wikis
- [PmWiki](https://www.pmwiki.org)
- [MermaidJs Cookbook recipe](https://www.pmwiki.org/wiki/Cookbook/MermaidJs)
- [MediaWiki](https://www.mediawiki.org)
- [Mermaid Extension](https://www.mediawiki.org/wiki/Extension:Mermaid)
- [Flex Diagrams Extension](https://www.mediawiki.org/wiki/Extension:Flex_Diagrams)
@ -141,7 +153,6 @@ Communication tools and platforms
- [Textual UML Parser](https://github.com/manastalukdar/markdown-it-textual-uml)
- [Mermaid Plugin](https://github.com/tylingsoft/markdown-it-mermaid)
- [md-it-mermaid](https://github.com/iamcco/md-it-mermaid)
- [markdown-it-mermaid-fence-new](https://github.com/Revomatico/markdown-it-mermaid-fence-new)
- [markdown-it-mermaid-less](https://github.com/searKing/markdown-it-mermaid-less)
- Atom _(Atom has been [archived.](https://github.blog/2022-06-08-sunsetting-atom/))_
- [Markdown Preview Enhanced](https://github.com/shd101wyy/markdown-preview-enhanced)
@ -179,6 +190,7 @@ Communication tools and platforms
### Document Generation
- [Docusaurus](https://docusaurus.io/docs/markdown-features/diagrams) ✅
- [Unison programming language](https://www.unison-lang.org/docs/usage-topics/documentation/) ✅
- [Swimm - Up-to-date diagrams with Swimm, the knowledge management tool for code](https://docs.swimm.io/features/diagrams-and-charts/#mermaid--swimm--up-to-date-diagrams-)
- [Sphinx](https://www.sphinx-doc.org/en/master/)
- [sphinxcontrib-mermaid](https://github.com/mgaitan/sphinxcontrib-mermaid)
@ -195,13 +207,14 @@ Communication tools and platforms
- [mkdocs-material](https://github.com/squidfunk/mkdocs-material), check the [docs](https://squidfunk.github.io/mkdocs-material/reference/diagrams/)
- [Type Doc](https://typedoc.org/)
- [typedoc-plugin-mermaid](https://www.npmjs.com/package/typedoc-plugin-mermaid)
- [Docsy Hugo Theme](https://www.docsy.dev/docs/adding-content/lookandfeel/#diagrams-with-mermaid) (native support in theme)
- [Docsy Hugo Theme](https://www.docsy.dev/docs/adding-content/lookandfeel/#diagrams-with-mermaid)
- [Codedoc](https://codedoc.cc/)
- [codedoc-mermaid-plugin](https://www.npmjs.com/package/codedoc-mermaid-plugin)
- [mdbook](https://rust-lang.github.io/mdBook/index.html)
- [mdbook-mermaid](https://github.com/badboy/mdbook-mermaid)
- [Quarto](https://quarto.org/)
- [Typora](https://typora.io/) ([native support](https://support.typora.io/Draw-Diagrams-With-Markdown/#mermaid))
- [Typora](https://typora.io/) ✅
- [See docs](https://support.typora.io/Draw-Diagrams-With-Markdown/#mermaid)
### Browser Extensions
@ -233,6 +246,6 @@ Communication tools and platforms
- [mermaid-server: Generate diagrams using a HTTP request](https://github.com/TomWright/mermaid-server)
- [ExDoc](https://github.com/elixir-lang/ex_doc)
- [Rendering Mermaid graphs](https://github.com/elixir-lang/ex_doc#rendering-mermaid-graphs)
- [NiceGUI: Let any browser be the frontend of your Python code](https://nicegui.io)
- [ui.mermaid(...)](https://nicegui.io/reference#mermaid_diagrams)
- [ui.markdown(..., extras=\['mermaid'\])](https://nicegui.io/reference#markdown_element)
- [NiceGUI: Let any browser be the frontend of your Python code](https://nicegui.io)
- [ui.mermaid(...)](https://nicegui.io/documentation/section_text_elements#markdown_element)
- [ui.markdown(..., extras=\['mermaid'\])](https://nicegui.io/documentation/section_text_elements#mermaid_diagrams)

View File

@ -22,9 +22,16 @@
- **Collaboration** - A web based collaboration feature for multi-user editing on Mermaid diagrams in real-time (Pro plan).
- **Plugins** - A plugin system for extending the functionality of Mermaid. Currently includes [VS Code](https://marketplace.visualstudio.com/items?itemName=MermaidChart.vscode-mermaid-chart) and [ChatGPT](https://www.mermaidchart.com/plugins/chatgpt).
- **Plugins** - A plugin system for extending the functionality of Mermaid.
- **AI** - An AI chatbot that can generate Mermaid diagrams from text (Pro plan).
Plugins are available for:
- [ChatGPT](https://docs.mermaidchart.com/plugins/chatgpt)
- [JetBrains IDE](https://plugins.jetbrains.com/plugin/23043-mermaid-chart)
- [Microsoft PowerPoint and Word](https://appsource.microsoft.com/en-us/product/office/WA200006214?tab=Overview)
- [Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=MermaidChart.vscode-mermaid-chart)
- **AI diagramming** - A feature for generating Mermaid diagrams from text using AI (Pro plan).
- **More** - To learn more, visit our [Product](https://www.mermaidchart.com/product) page.
@ -40,7 +47,7 @@
Sign up for a free account at [Mermaid Chart](https://www.mermaidchart.com/app/sign-up).
Mermaid Chart is currently offering a 30-day free trial of our newly-launched Pro tier. To learn more, visit our [Pricing](https://mermaidchart.com/pricing) page.
Mermaid Chart is currently offering a 14-day free trial of our newly-launched Pro tier. To learn more, visit our [Pricing](https://mermaidchart.com/pricing) page.
## Mermaid JS contributions

View File

@ -2,7 +2,7 @@
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/config/Tutorials.md](../../packages/mermaid/src/docs/config/Tutorials.md).
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/ecosystem/tutorials.md](../../packages/mermaid/src/docs/ecosystem/tutorials.md).
# Tutorials

View File

@ -4,30 +4,44 @@
>
> ## 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 User Guide
Mermaid is composed of three parts: Deployment, Syntax and Configuration.
## Mermaid is composed of three parts
This section talks about the different ways to deploy Mermaid. Learning the [Syntax](syntax-reference.md) would be of great help to the beginner.
1. Deployment
2. Syntax
3. Configuration
> Generally the live editor is enough for most general uses of mermaid, and is a good place to start learning.
This section talks about the different ways to **deploy** Mermaid.
**Absolute beginners are advised to view the Video [Tutorials](../config/Tutorials.md) on the Live Editor, to gain a better understanding of mermaid.**
If you are a beginner:
## Four ways of using mermaid:
- Check out the [Diagram Syntax](syntax-reference.md) page
- Check out the [Tutorials](../ecosystem/tutorials.md) page
1. Using the Mermaid Live Editor at [mermaid.live](https://mermaid.live).
2. Using [mermaid plugins](../ecosystem/integrations-community.md) with programs you are familiar with.
3. Calling the Mermaid JavaScript API.
4. Deploying Mermaid as a dependency.
## Ways to use Mermaid
**Note: It is our recommendation that you review all approaches, and choose the one that is best for your project.**
1. [Using the Mermaid Live Editor](getting-started.md#_1-using-the-mermaid-live-editor)
2. [Using the Mermaid Chart Editor](getting-started.md#_2-using-the-mermaid-chart-editor)
3. [Using Mermaid Plugins and Integrations](getting-started.md#_3-using-mermaid-plugins)
4. [Calling the Mermaid JavaScript API](getting-started.md#_4-calling-the-mermaid-javascript-api)
5. [Adding Mermaid as a dependency](getting-started.md#_5-adding-mermaid-as-a-dependency)
> More in depth information can be found at [Usage](../config/usage.md).
To learn more, visit the [Usage](../config/usage.md) page.
## 1. Using the Live Editor
## 1. Using the Mermaid Live Editor
Available at [mermaid.live](https://mermaid.live)
Available at the [Mermaid Live Editor](https://mermaid.live) website.
### Features
<br />
#### • Diagram Code
In the `Code` panel, write or edit Mermaid code, and instantly `Preview` the rendered result in the diagram panel.
Here is an example of Mermaid code and its rendered result:
```mermaid-example
graph TD
@ -51,79 +65,161 @@ graph TD
F --> B
```
In the `Code` section one can write or edit raw mermaid code, and instantly `Preview` the rendered result on the panel beside it.
<br />
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.
#### • Configurations
Configuration options are available in the `Configuration` panel. The options are applied to the diagram in the `Preview` panel.
To learn more, visit the [Configuration Reference](../config/setup/README.md) page
![Code,Config and Preview](./img/Code-Preview-Config.png)
### Editing History
<br />
Your code will be autosaved every minute into the Timeline tab of History which shows the most recent 30 items.
#### • Editing History
You can manually save code by clicking the Save icon in the History section. It can also be accessed in the Saved tab. This is stored in the browser storage only.
Your code will be autosaved and appear in the `Timeline` tab of the `History` section. Edits are saved every minute and only the last 30 edits are viewable.
### Saving a Diagram:
Alternatively, you can manually save code by clicking on the `Save` icon from the `History` section.
You may choose any of the methods below, to save it
> **Note**
> History is stored in the browser storage only.
**We recommend that you save your diagram code on top of any method you choose, in order to make edits and modifications further down the line.**
<br />
#### • Saving a diagram
There are multiple ways of saving your diagram from the `Actions` section:
- export PNG
- export SVG
- export as Markdown
![Flowchart](./img/Live-Editor-Choices.png)
### Editing your diagrams
<br />
Editing is as easy as pasting your **Diagram code**, into the `code` section of the `Live Editor`.
#### • Editing your diagrams
### Loading from Gists
To edit your diagram, you can copy paste existing Mermaid diagram code into the `Code` section of the `Live Editor`.
The Gist you create should have a code.mmd file and optionally a config.json. [Example](https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a)
Or:
To load a gist into the Editor, you can use <https://mermaid.live/edit?gist=https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a>
- create a new diagram from scratch
- use a Sample Diagram from the `Sample Diagrams` section
and to View, <https://mermaid.live/view?gist=https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a>
<br />
## 2. Using Mermaid Plugins:
#### • Loading from Gists
You can generate mermaid diagrams from within popular applications using plug-ins. It can be done in the same way, you would use the Live Editor. Here's a list of [Mermaid Plugins](../ecosystem/integrations-community.md).
The Gist you create should have a `code.mmd` file and optionally a `config.json`, similar to this [example](https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a).
**This is covered in greater detail in the [Usage section](../config/usage.md)**
> **Note**
> To learn about Gists, visit the GitHub documentation page on [Creating gists](https://docs.github.com/en/get-started/writing-on-github/editing-and-sharing-content-with-gists/creating-gists).
## 3. Calling the JavaScript API
Once you have created a Gist, copy paste the Gist URL into the respective field in the `Actions` section and click on the `Load Gist` button.
This method can be used with any common web server like Apache, IIS, nginx, node express.
Here is an example of a Gist being loaded into the Editor:
You will also need a text editing tool like Notepad++ to generate a .html file. It is then deployed by a web browser (such as Firefox, Chrome, Safari, but not Internet Explorer).
<https://mermaid.live/edit?gist=https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a>
And, here is the diagram view from the above example:
<https://mermaid.live/view?gist=https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a>
## 2. Using the Mermaid Chart Editor
Available at the [Mermaid Chart](https://www.mermaidchart.com/) website.
Mermaid Chart is a web-based diagram editor that allows you to create and edit diagrams in your browser. It is built by the team behind Mermaid.
Features include:
- AI diagramming
- Collaboration & multi-user editing
- Storage
- and more
To learn more, visit the [Mermaid Chart page](/ecosystem/mermaid-chart.html) in the Ecosystem section of the documentation.
Or go to the [Mermaid Chart website](https://www.mermaidchart.com/app/sign-up) to sign up for a Free account.
## 3. Using Mermaid Plugins
### Mermaid Plugins
You can generate Mermaid diagrams from within popular applications using plug-ins.
For a list of Mermaid Plugins and Integrations, visit the [Integrations page](../ecosystem/integrations-community.md).
### Mermaid Chart Plugins
Mermaid Chart plugins are available for:
- [ChatGPT](https://docs.mermaidchart.com/plugins/chatgpt)
- [JetBrains IDE](https://docs.mermaidchart.com/plugins/jetbrains-ide)
- [Microsoft PowerPoint](https://docs.mermaidchart.com/plugins/microsoft-powerpoint)
- [Microsoft Word](https://docs.mermaidchart.com/plugins/microsoft-word)
- [Visual Studio Code](https://docs.mermaidchart.com/plugins/visual-studio-code)
To learn more, visit the [Mermaid Chart Plugins](https://www.mermaidchart.com/plugins) page.
### Native Mermaid Support
For apps that support markdown (e.g. [GitHub](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-diagrams) and [GitLab](https://handbook.gitlab.com/handbook/tools-and-tips/mermaid/)), you can add Mermaid diagrams by making a `mermaid` code block.
````markdown
The following code-block will be rendered as a Mermaid diagram:
```mermaid
flowchart LR
A --> B
```
````
## 4. Calling the Mermaid JavaScript API
This method can be used with any common web server like `Apache`, `IIS`, `Nginx`, and `Node Express`.
You will also need a text editing tool like `Notepad++` to generate an `html` file. It is then deployed by a web browser, i.e. `Firefox`, `Chrome`, `Safari`.
> **Note**
> Internet Explorer is not supported.
The API works by pulling rendering instructions from the source `mermaid.js` in order to render diagrams on the page.
### Requirements for the Mermaid API.
### Requirements for the Mermaid API
When writing the .html file, we give two instructions inside the html code to the web browser:
When writing the `html` file, we give two instructions inside the `html code` to the `web browser`:
a. The mermaid code for the diagram we want to create.
a. The Mermaid code for the diagram we want to create.
b. The importing of mermaid library through the `mermaid.esm.mjs` or `mermaid.esm.min.mjs` and the `mermaid.initialize()` call, which dictates the appearance of diagrams and also starts the rendering process.
b. The importing of the Mermaid library through the `mermaid.esm.mjs` or `mermaid.esm.min.mjs`, and the `mermaid.initialize()` call, which dictates the appearance of diagrams and also starts the rendering process.
**a. The embedded mermaid diagram definition inside a `<pre class="mermaid">`:**
#### Examples
- This is an example of an embedded Mermaid diagram definition inside a `<pre class="mermaid">`:
```html
<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>
```
**Notes**: Every Mermaid chart/graph/diagram definition, should have separate `<pre>` tags.
> **Note**
> Every Mermaid chart/graph/diagram definition should have separate `<pre>` tags.
**b. The import of mermaid and the `mermaid.initialize()` call.**
- This is an example of a Mermaid import and the `mermaid.initialize()` call.
`mermaid.initialize()` call takes all the definitions contained in all the `<pre class="mermaid">` tags that it finds in the html body and renders them into diagrams. Example:
> **Note**
> A `mermaid.initialize()` call takes all the definitions contained within `<pre class="mermaid">` tags and renders them into diagrams.
```html
<body>
@ -134,8 +230,8 @@ b. The importing of mermaid library through the `mermaid.esm.mjs` or `mermaid.es
</body>
```
**Notes**:
Rendering in Mermaid is initialized by `mermaid.initialize()` call. However, doing the opposite lets you control when it starts looking for `<pre>` tags inside the web page with `mermaid.initialize()`. This is useful when you think that not all `<pre>` tags may have loaded on the execution of `mermaid.esm.min.mjs` file.
> **Note**
> Rendering in Mermaid is initialized by the `mermaid.initialize()` call. However, doing the opposite lets you control when it starts looking for `<pre>` tags inside the web page with `mermaid.initialize()`. This is useful when you think that not all `<pre>` tags may have loaded on the execution of `mermaid.esm.min.mjs` file.
`startOnLoad` is one of the parameters that can be defined by `mermaid.initialize()`
@ -143,9 +239,7 @@ Rendering in Mermaid is initialized by `mermaid.initialize()` call. However, doi
| ----------- | --------------------------------- | ------- | ----------- |
| startOnLoad | Toggle for Rendering upon loading | Boolean | true, false |
### Working Examples
**Here is a full working example of the mermaidAPI being called through the CDN:**
In this example, the `mermaidAPI` is being called through the `CDN`:
```html
<html>
@ -175,8 +269,7 @@ Rendering in Mermaid is initialized by `mermaid.initialize()` call. However, doi
</html>
```
**Another Option:**
In this example mermaid.js is referenced in `src` as a separate JavaScript file, in an example Path.
In this example, `mermaid.js` is referenced in `src` as a separate JavaScript file:
```html
<html lang="en">
@ -204,21 +297,30 @@ In this example mermaid.js is referenced in `src` as a separate JavaScript file,
</html>
```
---
## 5. Adding Mermaid as a dependency
## 4. Adding Mermaid as a dependency.
Below are the steps for adding Mermaid as a dependency:
1. install node v16, which would have npm
1. Install `node v16`
2. download yarn using npm by entering the command below:
npm install -g yarn
> **Note**
> To learn more about downloading and installing `Node.js` and `npm`, visit the [npm Docs website](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm).
3. After yarn installs, enter the following command:
yarn add mermaid
1. Install `yarn` using `npm` with this command:
4. To add Mermaid as a Dev Dependency
yarn add --dev mermaid
`npm install -g yarn`
**Comments from Knut Sveidqvist, creator of mermaid:**
2. After yarn installs, enter this command:
- In early versions of mermaid, the `<script>` tag was invoked in the `<head>` part of the web page. Nowadays we can place it in the `<body>` as seen above. Older parts of the documentation frequently reflect the previous way which still works.
`yarn add mermaid`
3. To add Mermaid as a dev dependency, enter this command:
`yarn add --dev mermaid`
## Closing note
> **Note**
> Comments from Knut Sveidqvist, creator of Mermaid:
>
> - In early versions of Mermaid, the `<script>` tag was invoked in the `<head>` part of the web page. Nowadays, we can place it in the `<body>` as seen above. Older parts of the documentation frequently reflect the previous way, which still works.

View File

@ -41,13 +41,13 @@ Diagramming and documentation costs precious developer time and gets outdated qu
But not having diagrams or docs ruins productivity and hurts organizational learning.<br/>
Mermaid addresses this problem by enabling users to create easily modifiable diagrams, it can also be made part of production scripts (and other pieces of code).<br/> <br/>
Mermaid allows even non-programmers to easily create detailed and diagrams through the [Mermaid Live Editor](https://mermaid.live/).<br/>
[Tutorials](../config/Tutorials.md) has video tutorials.
[Tutorials](../ecosystem/tutorials.md) has video tutorials.
Use Mermaid with your favorite applications, check out the list of [Community Integrations](../ecosystem/integrations-community.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-community.md)
🌐 [CDN](https://www.jsdelivr.com/package/npm/mermaid) | 📖 [Documentation](https://mermaidjs.github.io) | 🙌 [Contribution](../community/contributing.md) | 🔌 [Plug-Ins](../ecosystem/integrations-community.md)
> 🖖 Keep a steady pulse: mermaid needs more Collaborators, [Read More](https://github.com/knsv/mermaid/issues/866).
@ -378,7 +378,7 @@ Don't hesitate to contact me if you want to get involved!
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).
Detailed information about how to contribute can be found in the [contribution guideline](../community/contributing.md).
### Requirements

View File

@ -6,10 +6,27 @@
# Announcements
Check out our latest blog posts below. See more blog posts [here](blog.md).
## 🚀 Mermaid Chart's Visual Editor for Flowcharts
## [5 Reasons You Should Be Using Mermaid Chart As Your Diagram Generator](https://www.mermaidchart.com/blog/posts/5-reasons-you-should-be-using-mermaid-chart-as-your-diagram-generator/)
The Mermaid Chart team is excited to introduce a new Visual Editor for flowcharts, enabling users of all skill levels to create diagrams easily and efficiently, with both GUI and code-based editing options.
14 November 2023 · 5 mins
Create flowchart nodes, connect them with edges, update shapes, change colors, and edit labels with just a few clicks that automatically reflect in your diagrams code for easy customizability.
Mermaid Chart, a user-friendly, code-based diagram generator with AI integrations, templates, collaborative tools, and plugins for developers, streamlines the process of creating and sharing diagrams, enhancing both creativity and collaboration.
Read more about it in our latest [BLOG POST](https://www.mermaidchart.com/blog/posts/mermaid-chart-releases-new-visual-editor-for-flowcharts) and watch a [DEMO VIDEO](https://www.youtube.com/watch?v=5aja0gijoO0) on our YouTube page.
## 🎉 Mermaid Chart is running a Holiday promotion
### Use <span class="text-[#FE3470]">HOLIDAYS2023</span> to get a 14-day free trial and 25% off a Pro subscription
With a Pro subscription, you get access to:
- AI functionality
- Team collaboration and multi-user editing
- Unlimited diagrams and presentations
- And more!
Redeem the promo code on the [Mermaid Chart website](https://www.mermaidchart.com/app/user/billing/checkout?coupon=HOLIDAYS2023).
## 📖 Blog posts
Visit our [Blog](./blog.md) to see the latest blog posts.

View File

@ -6,6 +6,24 @@
# Blog
## [Introducing Mermaid Charts JetBrains IDE Extension](https://www.mermaidchart.com/blog/posts/introducing-mermaid-charts-jetbrains-ide-extension/)
20 December 2023 · 5 mins
Diagrams are essential for documenting your code.
## [Mermaid Chart Releases New Visual Editor For Flowcharts](https://www.mermaidchart.com/blog/posts/mermaid-chart-releases-new-visual-editor-for-flowcharts/)
14 December 2023 · 5 mins
Mermaid Chart introduces a new Visual Editor for flowcharts, enabling users of all skill levels to create diagrams easily and efficiently, with both GUI and code-based editing options.
## [7 best practices (+ examples) for good developer documentation](https://www.mermaidchart.com/blog/posts/7-best-practices-for-good-documentation/)
4 December 2023 · 11 min
Essential strategies for crafting grate developer documentation, with practical examples and insights from leading tech companies.
## [5 Reasons You Should Be Using Mermaid Chart As Your Diagram Generator](https://www.mermaidchart.com/blog/posts/5-reasons-you-should-be-using-mermaid-chart-as-your-diagram-generator/)
14 November 2023 · 5 mins

View File

@ -240,9 +240,9 @@ class BankAccount{
#### Generic Types
Members can be defined using generic types, such as `List<int>`, for fields, parameters, and return types by enclosing the type within `~` (**tilde**). **Nested** type declarations such as `List<List<int>>` are supported.
Generics can be representated as part of a class definition, and for class members/return types. In order to denote an item as generic, you enclose that type within `~` (**tilde**). **Nested** type declarations such as `List<List<int>>` are supported, though generics that include a comma are currently not supported. (such as `List<List<K, V>>`)
Generics can be represented as part of a class definition and also in the parameters or the return value of a method/function:
> _note_ when a generic is used within a class definition, the generic type is NOT considered part of the class name. i.e.: for any syntax which required you to reference the class name, you need to drop the type part of the definition. This also means that mermaid does not currently support having two classes with the same name, but different generic types.
```mermaid-example
classDiagram
@ -459,9 +459,9 @@ The different cardinality options are :
- `0..1` Zero or One
- `1..*` One or more
- `*` Many
- `n` n {where n>1}
- `0..n` zero to n {where n>1}
- `1..n` one to n {where n>1}
- `n` n (where n>1)
- `0..n` zero to n (where n>1)
- `1..n` one to n (where n>1)
Cardinality can be easily defined by placing the text option within quotes `"` before or after a given arrow. For example:
@ -766,9 +766,30 @@ Beginner's tip—a full example using interactive links in an HTML page:
## Styling
### Styling a node
### Styling a node (v10.7.0+)
It is possible to apply specific styles such as a thicker border or a different background color to individual nodes. This is done by predefining classes in css styles that can be applied from the graph definition using the `cssClass` statement or the `:::` short hand.
It is possible to apply specific styles such as a thicker border or a different background color to an individual node using the `style` keyword.
```mermaid-example
classDiagram
class Animal
class Mineral
style Animal fill:#f9f,stroke:#333,stroke-width:4px
style Mineral fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5
```
```mermaid
classDiagram
class Animal
class Mineral
style Animal fill:#f9f,stroke:#333,stroke-width:4px
style Mineral fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5
```
#### Classes
More convenient than defining the style every time is to define a class of styles and attach this class to the nodes that
should have a different look. This is done by predefining classes in css styles that can be applied from the graph definition using the `cssClass` statement or the `:::` short hand.
```html
<style>

View File

@ -11,6 +11,13 @@ Flowcharts are composed of **nodes** (geometric shapes) and **edges** (arrows or
> **Warning**
> If you are using the word "end" in a Flowchart node, capitalize the entire word or any of the letters (e.g., "End" or "END"), or apply this [workaround](https://github.com/mermaid-js/mermaid/issues/1444#issuecomment-639528897). Typing "end" in all lowercase letters will break the Flowchart.
> **Warning**
> If you are using the letter "o" or "x" as the first letter in a connecting Flowchart node, add a space before the letter or capitalize the letter (e.g., "dev--- ops", "dev---Ops").
>
> Typing "A---oB" will create a [circle edge](#circle-edge-example).
>
> Typing "A---xB" will create a [cross edge](#cross-edge-example).
### A node (default)
```mermaid-example
@ -488,23 +495,38 @@ flowchart TB
B --> D
```
### New arrow types
## New arrow types
There are new types of arrows supported as per below:
There are new types of arrows supported:
- circle edge
- cross edge
### Circle edge example
```mermaid-example
flowchart LR
A --o B
B --x C
```
```mermaid
flowchart LR
A --o B
B --x C
```
### Multi directional arrows
### Cross edge example
```mermaid-example
flowchart LR
A --x B
```
```mermaid
flowchart LR
A --x B
```
## Multi directional arrows
There is the possibility to use multidirectional arrows.

View File

@ -420,11 +420,21 @@ mermaid.ganttConfig can be set to a JSON string with config parameters or the co
```javascript
mermaid.ganttConfig = {
titleTopMargin: 25,
barHeight: 20,
barGap: 4,
topPadding: 75,
sidePadding: 75,
titleTopMargin: 25, // Margin top for the text over the diagram
barHeight: 20, // The height of the bars in the graph
barGap: 4, // The margin between the different activities in the gantt diagram
topPadding: 75, // Margin between title and gantt diagram and between axis and gantt diagram.
rightPadding: 75, // The space allocated for the section name to the right of the activities
leftPadding: 75, // The space allocated for the section name to the left of the activities
gridLineStartPadding: 10, // Vertical starting position of the grid lines
fontSize: 12, // Font size
sectionFontSize: 24, // Font size for sections
numberSectionStyles: 1, // The number of alternating section styles
axisFormat: '%d/%m', // Date/time format of the axis
tickInterval: '1 week', // Axis ticks
topAxis: true, // When this flag is set, date labels will be added to the top of the chart
displayMode: 'compact', // Turns compact mode on
weekday: 'sunday', // On which day a week-based interval should start
};
```

View File

@ -366,41 +366,49 @@ A few important rules to note here are:
1. You need to provide the `id` for an existing commit to be cherry-picked. If given commit id does not exist it will result in an error. For this, make use of the `commit id:$value` format of declaring commits. See the examples from above.
2. The given commit must not exist on the current branch. The cherry-picked commit must always be a different branch than the current branch.
3. Current branch must have at least one commit, before you can cherry-pick, otherwise it will cause an error is throw.
4. When cherry-picking a merge commit, providing a parent commit ID is mandatory. If the parent attribute is omitted or an invalid parent commit ID is provided, an error will be thrown.
5. The specified parent commit must be an immediate parent of the merge commit being cherry-picked.
Let see an example:
```mermaid-example
gitGraph
commit id: "ZERO"
branch develop
commit id:"A"
checkout main
commit id:"ONE"
checkout develop
commit id:"B"
checkout main
commit id:"TWO"
cherry-pick id:"A"
commit id:"THREE"
checkout develop
commit id:"C"
commit id: "ZERO"
branch develop
branch release
commit id:"A"
checkout main
commit id:"ONE"
checkout develop
commit id:"B"
checkout main
merge develop id:"MERGE"
commit id:"TWO"
checkout release
cherry-pick id:"MERGE" parent:"B"
commit id:"THREE"
checkout develop
commit id:"C"
```
```mermaid
gitGraph
commit id: "ZERO"
branch develop
commit id:"A"
checkout main
commit id:"ONE"
checkout develop
commit id:"B"
checkout main
commit id:"TWO"
cherry-pick id:"A"
commit id:"THREE"
checkout develop
commit id:"C"
commit id: "ZERO"
branch develop
branch release
commit id:"A"
checkout main
commit id:"ONE"
checkout develop
commit id:"B"
checkout main
merge develop id:"MERGE"
commit id:"TWO"
checkout release
cherry-pick id:"MERGE" parent:"B"
commit id:"THREE"
checkout develop
commit id:"C"
```
## Gitgraph specific configuration options

View File

@ -131,6 +131,14 @@ sequenceDiagram
Bob->>Alice: I agree
```
#### Unfixable actor/participant creation/deletion error
If an error of the following type occurs when creating or deleting an actor/participant:
> The destroyed participant **participant-name** does not have an associated destroying message after its declaration. Please check the sequence diagram.
And fixing diagram code does not get rid of this error and rendering of all other diagrams results in the same error, then you need to update the mermaid version to (v10.7.0+).
### Grouping / Box
The actor(s) can be grouped in vertical boxes. You can define a color (if not, it will be transparent) and/or a descriptive label using the following notation:

View File

@ -4,7 +4,7 @@
"version": "10.2.4",
"description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.",
"type": "module",
"packageManager": "pnpm@8.10.5",
"packageManager": "pnpm@8.14.1",
"keywords": [
"diagram",
"markdown",
@ -16,25 +16,25 @@
],
"scripts": {
"build": "pnpm build:esbuild && pnpm build:types",
"build:esbuild": "pnpm run -r clean && ts-node-esm --transpileOnly .esbuild/build.ts",
"build:esbuild": "pnpm run -r clean && tsx .esbuild/build.ts",
"build:mermaid": "pnpm build:esbuild --mermaid",
"build:viz": "pnpm build:esbuild --visualize",
"build:types": "ts-node-esm --transpileOnly .build/types.ts",
"build:types": "tsx .build/types.ts",
"build:types:watch": "tsc -p ./packages/mermaid/tsconfig.json --emitDeclarationOnly --watch",
"dev": "ts-node-esm --transpileOnly .esbuild/server.ts",
"dev:vite": "ts-node-esm --transpileOnly .vite/server.ts",
"dev": "tsx .esbuild/server.ts",
"dev:vite": "tsx .vite/server.ts",
"dev:coverage": "pnpm coverage:cypress:clean && VITE_COVERAGE=true pnpm dev:vite",
"release": "pnpm build",
"lint": "eslint --cache --cache-strategy content --ignore-path .gitignore . && pnpm lint:jison && prettier --cache --check .",
"lint:fix": "eslint --cache --cache-strategy content --fix --ignore-path .gitignore . && prettier --write . && ts-node-esm scripts/fixCSpell.ts",
"lint:jison": "ts-node-esm ./scripts/jison/lint.mts",
"contributors": "ts-node-esm scripts/updateContributors.ts",
"lint:fix": "eslint --cache --cache-strategy content --fix --ignore-path .gitignore . && prettier --write . && tsx scripts/fixCSpell.ts",
"lint:jison": "tsx ./scripts/jison/lint.mts",
"contributors": "tsx scripts/updateContributors.ts",
"cypress": "cypress run",
"cypress:open": "cypress open",
"e2e": "start-server-and-test dev http://localhost:9000/ cypress",
"e2e:coverage": "start-server-and-test dev:coverage http://localhost:9000/ cypress",
"coverage:cypress:clean": "rimraf .nyc_output coverage/cypress",
"coverage:merge": "ts-node-esm scripts/coverage.ts",
"coverage:merge": "tsx scripts/coverage.ts",
"coverage": "pnpm test:coverage --run && pnpm e2e:coverage && pnpm coverage:merge",
"ci": "vitest run",
"test": "pnpm lint && vitest run",
@ -118,14 +118,14 @@
"rimraf": "^5.0.0",
"rollup-plugin-visualizer": "^5.9.2",
"start-server-and-test": "^2.0.0",
"ts-node": "^10.9.1",
"tsx": "^4.6.2",
"typescript": "^5.1.3",
"vite": "^4.3.9",
"vite": "^4.4.12",
"vite-plugin-istanbul": "^4.1.0",
"vitest": "^0.34.0"
},
"volta": {
"node": "18.18.2"
"node": "18.19.0"
},
"nyc": {
"report-dir": "coverage/cypress"

View File

@ -11,6 +11,7 @@ import common from '../../mermaid/src/diagrams/common/common.js';
import { interpolateToCurve, getStylesFromArray } from '../../mermaid/src/utils.js';
import ELK from 'elkjs/lib/elk.bundled.js';
import { getLineFunctionsWithOffset } from '../../mermaid/src/utils/lineWithOffset.js';
import { addEdgeMarkers } from '../../mermaid/src/dagre-wrapper/edgeMarker.js';
const elk = new ELK();
@ -586,108 +587,7 @@ const addMarkersToEdge = function (svgPath, edgeData, diagramType, arrowMarkerAb
}
// look in edge data and decide which marker to use
switch (edgeData.arrowTypeStart) {
case 'arrow_cross':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-crossStart' + ')'
);
break;
case 'arrow_point':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-pointStart' + ')'
);
break;
case 'arrow_barb':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-barbStart' + ')'
);
break;
case 'arrow_circle':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-circleStart' + ')'
);
break;
case 'aggregation':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-aggregationStart' + ')'
);
break;
case 'extension':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-extensionStart' + ')'
);
break;
case 'composition':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-compositionStart' + ')'
);
break;
case 'dependency':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-dependencyStart' + ')'
);
break;
case 'lollipop':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-lollipopStart' + ')'
);
break;
default:
}
switch (edgeData.arrowTypeEnd) {
case 'arrow_cross':
svgPath.attr('marker-end', 'url(' + url + '#' + id + '_' + diagramType + '-crossEnd' + ')');
break;
case 'arrow_point':
svgPath.attr('marker-end', 'url(' + url + '#' + id + '_' + diagramType + '-pointEnd' + ')');
break;
case 'arrow_barb':
svgPath.attr('marker-end', 'url(' + url + '#' + id + '_' + diagramType + '-barbEnd' + ')');
break;
case 'arrow_circle':
svgPath.attr('marker-end', 'url(' + url + '#' + id + '_' + diagramType + '-circleEnd' + ')');
break;
case 'aggregation':
svgPath.attr(
'marker-end',
'url(' + url + '#' + id + '_' + diagramType + '-aggregationEnd' + ')'
);
break;
case 'extension':
svgPath.attr(
'marker-end',
'url(' + url + '#' + id + '_' + diagramType + '-extensionEnd' + ')'
);
break;
case 'composition':
svgPath.attr(
'marker-end',
'url(' + url + '#' + id + '_' + diagramType + '-compositionEnd' + ')'
);
break;
case 'dependency':
svgPath.attr(
'marker-end',
'url(' + url + '#' + id + '_' + diagramType + '-dependencyEnd' + ')'
);
break;
case 'lollipop':
svgPath.attr(
'marker-end',
'url(' + url + '#' + id + '_' + diagramType + '-lollipopEnd' + ')'
);
break;
default:
}
addEdgeMarkers(svgPath, edgeData, url, id, diagramType);
};
/**

View File

@ -2,7 +2,8 @@
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "../..",
"outDir": "./dist"
"outDir": "./dist",
"types": ["vitest/importMeta", "vitest/globals"]
},
"include": ["./src/**/*.ts"],
"typeRoots": ["./src/types"]

View File

@ -26,18 +26,18 @@
"clean": "rimraf dist",
"dev": "pnpm -w dev",
"docs:code": "typedoc src/defaultConfig.ts src/config.ts src/mermaidAPI.ts && prettier --write ./src/docs/config/setup",
"docs:build": "rimraf ../../docs && pnpm docs:spellcheck && pnpm docs:code && ts-node-esm scripts/docs.cli.mts",
"docs:verify": "pnpm docs:spellcheck && pnpm docs:code && ts-node-esm scripts/docs.cli.mts --verify",
"docs:pre:vitepress": "pnpm --filter ./src/docs prefetch && rimraf src/vitepress && pnpm docs:code && ts-node-esm scripts/docs.cli.mts --vitepress && pnpm --filter ./src/vitepress install --no-frozen-lockfile --ignore-scripts",
"docs:build": "rimraf ../../docs && pnpm docs:spellcheck && pnpm docs:code && tsx scripts/docs.cli.mts",
"docs:verify": "pnpm docs:spellcheck && pnpm docs:code && tsx scripts/docs.cli.mts --verify",
"docs:pre:vitepress": "pnpm --filter ./src/docs prefetch && rimraf src/vitepress && pnpm docs:code && tsx scripts/docs.cli.mts --vitepress && pnpm --filter ./src/vitepress install --no-frozen-lockfile --ignore-scripts",
"docs:build:vitepress": "pnpm docs:pre:vitepress && (cd src/vitepress && pnpm run build) && cpy --flat src/docs/landing/ ./src/vitepress/.vitepress/dist/landing",
"docs:dev": "pnpm docs:pre:vitepress && concurrently \"pnpm --filter ./src/vitepress dev\" \"ts-node-esm scripts/docs.cli.mts --watch --vitepress\"",
"docs:dev:docker": "pnpm docs:pre:vitepress && concurrently \"pnpm --filter ./src/vitepress dev:docker\" \"ts-node-esm scripts/docs.cli.mts --watch --vitepress\"",
"docs:dev": "pnpm docs:pre:vitepress && concurrently \"pnpm --filter ./src/vitepress dev\" \"tsx scripts/docs.cli.mts --watch --vitepress\"",
"docs:dev:docker": "pnpm docs:pre:vitepress && concurrently \"pnpm --filter ./src/vitepress dev:docker\" \"tsx scripts/docs.cli.mts --watch --vitepress\"",
"docs:serve": "pnpm docs:build:vitepress && vitepress serve src/vitepress",
"docs:spellcheck": "cspell --config ../../cSpell.json \"src/docs/**/*.md\"",
"docs:release-version": "ts-node-esm scripts/update-release-version.mts",
"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",
"docs:release-version": "tsx scripts/update-release-version.mts",
"docs:verify-version": "tsx scripts/update-release-version.mts --verify",
"types:build-config": "tsx scripts/create-types-from-json-schema.mts",
"types:verify-config": "tsx scripts/create-types-from-json-schema.mts --verify",
"checkCircle": "npx madge --circular ./src",
"release": "pnpm build",
"prepublishOnly": "cpy '../../README.*' ./ --cwd=. && pnpm docs:release-version && pnpm -w run build"

View File

@ -233,6 +233,23 @@ async function generateTypescript(mermaidConfigSchema: JSONSchemaType<MermaidCon
}
}
/**
* Workaround for type duplication when a $ref property has siblings.
*
* @param json - The input JSON object.
*
* @see https://github.com/bcherny/json-schema-to-typescript/issues/193
*/
function removeProp(json: any, name: string) {
for (const prop in json) {
if (prop === name) {
delete json[prop];
} else if (typeof json[prop] === 'object') {
removeProp(json[prop], name);
}
}
}
/** Main function */
async function main() {
if (verifyOnly) {
@ -243,6 +260,8 @@ async function main() {
const configJsonSchema = await loadJsonSchemaFromYaml();
removeProp(configJsonSchema, 'default');
validateSchema(configJsonSchema);
// Generate types from JSON Schema

View File

@ -60,13 +60,11 @@ const CDN_URL = 'https://cdn.jsdelivr.net/npm'; // 'https://unpkg.com';
const MERMAID_KEYWORD = 'mermaid';
const MERMAID_CODE_ONLY_KEYWORD = 'mermaid-example';
const MERMAID_DIAGRAM_ONLY = 'mermaid-nocode';
// These keywords will produce both a mermaid diagram and a code block with the diagram source
const MERMAID_EXAMPLE_KEYWORDS = [MERMAID_KEYWORD, 'mmd', MERMAID_CODE_ONLY_KEYWORD]; // 'mmd' is an old keyword that used to be used
// This keyword will only produce a mermaid diagram
const MERMAID_DIAGRAM_ONLY = 'mermaid-nocode';
// These will be transformed into block quotes
const BLOCK_QUOTE_KEYWORDS = ['note', 'tip', 'warning', 'danger'];

View File

@ -68,6 +68,11 @@ export interface MermaidConfig {
* The maximum allowed size of the users text diagram
*/
maxTextSize?: number;
/**
* Defines the maximum number of edges that can be drawn in a graph.
*
*/
maxEdges?: number;
darkMode?: boolean;
htmlLabels?: boolean;
/**
@ -768,8 +773,8 @@ export interface XYChartConfig extends BaseDiagramConfig {
* Should show the chart title
*/
showTitle?: boolean;
xAxis?: XYChartAxisConfig1;
yAxis?: XYChartAxisConfig2;
xAxis?: XYChartAxisConfig;
yAxis?: XYChartAxisConfig;
/**
* How to plot will be drawn horizontal or vertical
*/
@ -779,104 +784,6 @@ export interface XYChartConfig extends BaseDiagramConfig {
*/
plotReservedSpacePercent?: number;
}
/**
* This object contains configuration for XYChart axis config
*/
export interface XYChartAxisConfig1 {
/**
* Should show the axis labels (tick text)
*/
showLabel?: boolean;
/**
* font size of the axis labels (tick text)
*/
labelFontSize?: number;
/**
* top and bottom space from axis label (tick text)
*/
labelPadding?: number;
/**
* Should show the axis title
*/
showTitle?: boolean;
/**
* font size of the axis title
*/
titleFontSize?: number;
/**
* top and bottom space from axis title
*/
titlePadding?: number;
/**
* Should show the axis tick lines
*/
showTick?: boolean;
/**
* length of the axis tick lines
*/
tickLength?: number;
/**
* width of the axis tick lines
*/
tickWidth?: number;
/**
* Show line across the axis
*/
showAxisLine?: boolean;
/**
* Width of the axis line
*/
axisLineWidth?: number;
}
/**
* This object contains configuration for XYChart axis config
*/
export interface XYChartAxisConfig2 {
/**
* Should show the axis labels (tick text)
*/
showLabel?: boolean;
/**
* font size of the axis labels (tick text)
*/
labelFontSize?: number;
/**
* top and bottom space from axis label (tick text)
*/
labelPadding?: number;
/**
* Should show the axis title
*/
showTitle?: boolean;
/**
* font size of the axis title
*/
titleFontSize?: number;
/**
* top and bottom space from axis title
*/
titlePadding?: number;
/**
* Should show the axis tick lines
*/
showTick?: boolean;
/**
* length of the axis tick lines
*/
tickLength?: number;
/**
* width of the axis tick lines
*/
tickWidth?: number;
/**
* Show line across the axis
*/
showAxisLine?: boolean;
/**
* Width of the axis line
*/
axisLineWidth?: number;
}
/**
* The object containing configurations specific for entity relationship diagrams
*
@ -1396,6 +1303,14 @@ export interface FlowchartDiagramConfig extends BaseDiagramConfig {
* Margin top for the text over the diagram
*/
titleTopMargin?: number;
/**
* Defines a top/bottom margin for subgraph titles
*
*/
subGraphTitleMargin?: {
top?: number;
bottom?: number;
};
arrowMarkerAbsolute?: boolean;
/**
* The amount of padding around the diagram as a whole so that embedded
@ -1464,13 +1379,7 @@ export interface SankeyDiagramConfig extends BaseDiagramConfig {
*
*/
linkColor?: SankeyLinkColor | string;
/**
* Controls the alignment of the Sankey diagrams.
*
* See <https://github.com/d3/d3-sankey#alignments>.
*
*/
nodeAlignment?: 'left' | 'right' | 'center' | 'justify';
nodeAlignment?: SankeyNodeAlignment;
useMaxWidth?: boolean;
/**
* Toggle to display or hide values along with title.

View File

@ -5,9 +5,11 @@ import { createText } from '../rendering-util/createText.js';
import { select } from 'd3';
import { getConfig } from '../diagram-api/diagramAPI.js';
import { evaluate } from '../diagrams/common/common.js';
import { getSubGraphTitleMargins } from '../utils/subGraphTitleMargins.js';
const rect = (parent, node) => {
log.info('Creating subgraph rect for ', node.id, node);
const siteConfig = getConfig();
// Add outer g element
const shapeSvg = parent
@ -18,7 +20,7 @@ const rect = (parent, node) => {
// add the rect
const rect = shapeSvg.insert('rect', ':first-child');
const useHtmlLabels = evaluate(getConfig().flowchart.htmlLabels);
const useHtmlLabels = evaluate(siteConfig.flowchart.htmlLabels);
// Create the label and insert it after the rect
const label = shapeSvg.insert('g').attr('class', 'cluster-label');
@ -34,7 +36,7 @@ const rect = (parent, node) => {
// Get the size of the label
let bbox = text.getBBox();
if (evaluate(getConfig().flowchart.htmlLabels)) {
if (evaluate(siteConfig.flowchart.htmlLabels)) {
const div = text.children[0];
const dv = select(text);
bbox = div.getBoundingClientRect();
@ -63,17 +65,18 @@ const rect = (parent, node) => {
.attr('width', width)
.attr('height', node.height + padding);
const { subGraphTitleTopMargin } = getSubGraphTitleMargins(siteConfig);
if (useHtmlLabels) {
label.attr(
'transform',
// This puts the labal on top of the box instead of inside it
'translate(' + (node.x - bbox.width / 2) + ', ' + (node.y - node.height / 2) + ')'
`translate(${node.x - bbox.width / 2}, ${node.y - node.height / 2 + subGraphTitleTopMargin})`
);
} else {
label.attr(
'transform',
// This puts the labal on top of the box instead of inside it
'translate(' + node.x + ', ' + (node.y - node.height / 2) + ')'
`translate(${node.x}, ${node.y - node.height / 2 + subGraphTitleTopMargin})`
);
}
// Center the label
@ -127,6 +130,8 @@ const noteGroup = (parent, node) => {
return shapeSvg;
};
const roundedWithTitle = (parent, node) => {
const siteConfig = getConfig();
// Add outer g element
const shapeSvg = parent.insert('g').attr('class', node.classes).attr('id', node.id);
@ -143,7 +148,7 @@ const roundedWithTitle = (parent, node) => {
// Get the size of the label
let bbox = text.getBBox();
if (evaluate(getConfig().flowchart.htmlLabels)) {
if (evaluate(siteConfig.flowchart.htmlLabels)) {
const div = text.children[0];
const dv = select(text);
bbox = div.getBoundingClientRect();
@ -175,17 +180,17 @@ const roundedWithTitle = (parent, node) => {
.attr('width', width + padding)
.attr('height', node.height + padding - bbox.height - 3);
const { subGraphTitleTopMargin } = getSubGraphTitleMargins(siteConfig);
// Center the label
label.attr(
'transform',
'translate(' +
(node.x - bbox.width / 2) +
', ' +
(node.y -
node.height / 2 -
node.padding / 3 +
(evaluate(getConfig().flowchart.htmlLabels) ? 5 : 3)) +
')'
`translate(${node.x - bbox.width / 2}, ${
node.y -
node.height / 2 -
node.padding / 3 +
(evaluate(siteConfig.flowchart.htmlLabels) ? 5 : 3) +
subGraphTitleTopMargin
})`
);
const rectBox = rect.node().getBBox();

View File

@ -0,0 +1,79 @@
import type { Mocked } from 'vitest';
import type { SVG } from '../diagram-api/types.js';
import { addEdgeMarkers } from './edgeMarker.js';
describe('addEdgeMarker', () => {
const svgPath = {
attr: vitest.fn(),
} as unknown as Mocked<SVG>;
const url = 'http://example.com';
const id = 'test';
const diagramType = 'test';
beforeEach(() => {
svgPath.attr.mockReset();
});
it('should add markers for arrow_cross:arrow_point', () => {
const arrowTypeStart = 'arrow_cross';
const arrowTypeEnd = 'arrow_point';
addEdgeMarkers(svgPath, { arrowTypeStart, arrowTypeEnd }, url, id, diagramType);
expect(svgPath.attr).toHaveBeenCalledWith(
'marker-start',
`url(${url}#${id}_${diagramType}-crossStart)`
);
expect(svgPath.attr).toHaveBeenCalledWith(
'marker-end',
`url(${url}#${id}_${diagramType}-pointEnd)`
);
});
it('should add markers for aggregation:arrow_point', () => {
const arrowTypeStart = 'aggregation';
const arrowTypeEnd = 'arrow_point';
addEdgeMarkers(svgPath, { arrowTypeStart, arrowTypeEnd }, url, id, diagramType);
expect(svgPath.attr).toHaveBeenCalledWith(
'marker-start',
`url(${url}#${id}_${diagramType}-aggregationStart)`
);
expect(svgPath.attr).toHaveBeenCalledWith(
'marker-end',
`url(${url}#${id}_${diagramType}-pointEnd)`
);
});
it('should add markers for arrow_point:aggregation', () => {
const arrowTypeStart = 'arrow_point';
const arrowTypeEnd = 'aggregation';
addEdgeMarkers(svgPath, { arrowTypeStart, arrowTypeEnd }, url, id, diagramType);
expect(svgPath.attr).toHaveBeenCalledWith(
'marker-start',
`url(${url}#${id}_${diagramType}-pointStart)`
);
expect(svgPath.attr).toHaveBeenCalledWith(
'marker-end',
`url(${url}#${id}_${diagramType}-aggregationEnd)`
);
});
it('should add markers for aggregation:composition', () => {
const arrowTypeStart = 'aggregation';
const arrowTypeEnd = 'composition';
addEdgeMarkers(svgPath, { arrowTypeStart, arrowTypeEnd }, url, id, diagramType);
expect(svgPath.attr).toHaveBeenCalledWith(
'marker-start',
`url(${url}#${id}_${diagramType}-aggregationStart)`
);
expect(svgPath.attr).toHaveBeenCalledWith(
'marker-end',
`url(${url}#${id}_${diagramType}-compositionEnd)`
);
});
it('should not add invalid markers', () => {
const arrowTypeStart = 'this is an invalid marker';
const arrowTypeEnd = ') url(https://my-malicious-site.example)';
addEdgeMarkers(svgPath, { arrowTypeStart, arrowTypeEnd }, url, id, diagramType);
expect(svgPath.attr).not.toHaveBeenCalled();
});
});

View File

@ -0,0 +1,57 @@
import type { SVG } from '../diagram-api/types.js';
import { log } from '../logger.js';
import type { EdgeData } from '../types.js';
/**
* Adds SVG markers to a path element based on the arrow types specified in the edge.
*
* @param svgPath - The SVG path element to add markers to.
* @param edge - The edge data object containing the arrow types.
* @param url - The URL of the SVG marker definitions.
* @param id - The ID prefix for the SVG marker definitions.
* @param diagramType - The type of diagram being rendered.
*/
export const addEdgeMarkers = (
svgPath: SVG,
edge: Pick<EdgeData, 'arrowTypeStart' | 'arrowTypeEnd'>,
url: string,
id: string,
diagramType: string
) => {
if (edge.arrowTypeStart) {
addEdgeMarker(svgPath, 'start', edge.arrowTypeStart, url, id, diagramType);
}
if (edge.arrowTypeEnd) {
addEdgeMarker(svgPath, 'end', edge.arrowTypeEnd, url, id, diagramType);
}
};
const arrowTypesMap = {
arrow_cross: 'cross',
arrow_point: 'point',
arrow_barb: 'barb',
arrow_circle: 'circle',
aggregation: 'aggregation',
extension: 'extension',
composition: 'composition',
dependency: 'dependency',
lollipop: 'lollipop',
} as const;
const addEdgeMarker = (
svgPath: SVG,
position: 'start' | 'end',
arrowType: string,
url: string,
id: string,
diagramType: string
) => {
const endMarkerType = arrowTypesMap[arrowType as keyof typeof arrowTypesMap];
if (!endMarkerType) {
log.warn(`Unknown arrow type: ${arrowType}`);
return; // unknown arrow type, ignore
}
const suffix = position === 'start' ? 'Start' : 'End';
svgPath.attr(`marker-${position}`, `url(${url}#${id}_${diagramType}-${endMarkerType}${suffix})`);
};

View File

@ -6,6 +6,8 @@ import { getConfig } from '../diagram-api/diagramAPI.js';
import utils from '../utils.js';
import { evaluate } from '../diagrams/common/common.js';
import { getLineFunctionsWithOffset } from '../utils/lineWithOffset.js';
import { getSubGraphTitleMargins } from '../utils/subGraphTitleMargins.js';
import { addEdgeMarkers } from './edgeMarker.js';
let edgeLabels = {};
let terminalLabels = {};
@ -135,6 +137,8 @@ function setTerminalWidth(fo, value) {
export const positionEdgeLabel = (edge, paths) => {
log.info('Moving label abc78 ', edge.id, edge.label, edgeLabels[edge.id]);
let path = paths.updatedPath ? paths.updatedPath : paths.originalPath;
const siteConfig = getConfig();
const { subGraphTitleTotalMargin } = getSubGraphTitleMargins(siteConfig);
if (edge.label) {
const el = edgeLabels[edge.id];
let x = edge.x;
@ -158,7 +162,7 @@ export const positionEdgeLabel = (edge, paths) => {
y = pos.y;
}
}
el.attr('transform', 'translate(' + x + ', ' + y + ')');
el.attr('transform', `translate(${x}, ${y + subGraphTitleTotalMargin / 2})`);
}
//let path = paths.updatedPath ? paths.updatedPath : paths.originalPath;
@ -172,7 +176,7 @@ export const positionEdgeLabel = (edge, paths) => {
x = pos.x;
y = pos.y;
}
el.attr('transform', 'translate(' + x + ', ' + y + ')');
el.attr('transform', `translate(${x}, ${y})`);
}
if (edge.startLabelRight) {
const el = terminalLabels[edge.id].startRight;
@ -188,7 +192,7 @@ export const positionEdgeLabel = (edge, paths) => {
x = pos.x;
y = pos.y;
}
el.attr('transform', 'translate(' + x + ', ' + y + ')');
el.attr('transform', `translate(${x}, ${y})`);
}
if (edge.endLabelLeft) {
const el = terminalLabels[edge.id].endLeft;
@ -200,7 +204,7 @@ export const positionEdgeLabel = (edge, paths) => {
x = pos.x;
y = pos.y;
}
el.attr('transform', 'translate(' + x + ', ' + y + ')');
el.attr('transform', `translate(${x}, ${y})`);
}
if (edge.endLabelRight) {
const el = terminalLabels[edge.id].endRight;
@ -212,7 +216,7 @@ export const positionEdgeLabel = (edge, paths) => {
x = pos.x;
y = pos.y;
}
el.attr('transform', 'translate(' + x + ', ' + y + ')');
el.attr('transform', `translate(${x}, ${y})`);
}
};
@ -506,108 +510,8 @@ export const insertEdge = function (elem, e, edge, clusterDb, diagramType, graph
log.info('arrowTypeStart', edge.arrowTypeStart);
log.info('arrowTypeEnd', edge.arrowTypeEnd);
switch (edge.arrowTypeStart) {
case 'arrow_cross':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-crossStart' + ')'
);
break;
case 'arrow_point':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-pointStart' + ')'
);
break;
case 'arrow_barb':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-barbStart' + ')'
);
break;
case 'arrow_circle':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-circleStart' + ')'
);
break;
case 'aggregation':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-aggregationStart' + ')'
);
break;
case 'extension':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-extensionStart' + ')'
);
break;
case 'composition':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-compositionStart' + ')'
);
break;
case 'dependency':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-dependencyStart' + ')'
);
break;
case 'lollipop':
svgPath.attr(
'marker-start',
'url(' + url + '#' + id + '_' + diagramType + '-lollipopStart' + ')'
);
break;
default:
}
switch (edge.arrowTypeEnd) {
case 'arrow_cross':
svgPath.attr('marker-end', 'url(' + url + '#' + id + '_' + diagramType + '-crossEnd' + ')');
break;
case 'arrow_point':
svgPath.attr('marker-end', 'url(' + url + '#' + id + '_' + diagramType + '-pointEnd' + ')');
break;
case 'arrow_barb':
svgPath.attr('marker-end', 'url(' + url + '#' + id + '_' + diagramType + '-barbEnd' + ')');
break;
case 'arrow_circle':
svgPath.attr('marker-end', 'url(' + url + '#' + id + '_' + diagramType + '-circleEnd' + ')');
break;
case 'aggregation':
svgPath.attr(
'marker-end',
'url(' + url + '#' + id + '_' + diagramType + '-aggregationEnd' + ')'
);
break;
case 'extension':
svgPath.attr(
'marker-end',
'url(' + url + '#' + id + '_' + diagramType + '-extensionEnd' + ')'
);
break;
case 'composition':
svgPath.attr(
'marker-end',
'url(' + url + '#' + id + '_' + diagramType + '-compositionEnd' + ')'
);
break;
case 'dependency':
svgPath.attr(
'marker-end',
'url(' + url + '#' + id + '_' + diagramType + '-dependencyEnd' + ')'
);
break;
case 'lollipop':
svgPath.attr(
'marker-end',
'url(' + url + '#' + id + '_' + diagramType + '-lollipopEnd' + ')'
);
break;
default:
}
addEdgeMarkers(svgPath, edge, url, id, diagramType);
let paths = {};
if (pointsHasChanged) {
paths.updatedPath = points;

View File

@ -13,8 +13,10 @@ import { insertNode, positionNode, clear as clearNodes, setNodeElem } from './no
import { insertCluster, clear as clearClusters } from './clusters.js';
import { insertEdgeLabel, positionEdgeLabel, insertEdge, clear as clearEdges } from './edges.js';
import { log } from '../logger.js';
import { getSubGraphTitleMargins } from '../utils/subGraphTitleMargins.js';
import { getConfig } from '../diagram-api/diagramAPI.js';
const recursiveRender = async (_elem, graph, diagramtype, id, parentCluster) => {
const recursiveRender = async (_elem, graph, diagramtype, id, parentCluster, siteConfig) => {
log.info('Graph in recursive render: XXX', graphlibJson.write(graph), parentCluster);
const dir = graph.graph().rankdir;
log.trace('Dir in recursive render - dir:', dir);
@ -52,7 +54,14 @@ const recursiveRender = async (_elem, graph, diagramtype, id, parentCluster) =>
if (node && node.clusterNode) {
// const children = graph.children(v);
log.info('Cluster identified', v, node.width, graph.node(v));
const o = await recursiveRender(nodes, node.graph, diagramtype, id, graph.node(v));
const o = await recursiveRender(
nodes,
node.graph,
diagramtype,
id,
graph.node(v),
siteConfig
);
const newEl = o.elem;
updateNodeBounds(node, newEl);
node.diff = o.diff || 0;
@ -101,6 +110,7 @@ const recursiveRender = async (_elem, graph, diagramtype, id, parentCluster) =>
log.info('Graph after layout:', graphlibJson.write(graph));
// Move the nodes to the correct place
let diff = 0;
const { subGraphTitleTotalMargin } = getSubGraphTitleMargins(siteConfig);
sortNodesByHierarchy(graph).forEach(function (v) {
const node = graph.node(v);
log.info('Position ' + v + ': ' + JSON.stringify(graph.node(v)));
@ -114,16 +124,18 @@ const recursiveRender = async (_elem, graph, diagramtype, id, parentCluster) =>
);
if (node && node.clusterNode) {
// clusterDb[node.id].node = node;
node.y += subGraphTitleTotalMargin;
positionNode(node);
} else {
// Non cluster node
if (graph.children(v).length > 0) {
// A cluster in the non-recursive way
// positionCluster(node);
node.height += subGraphTitleTotalMargin;
insertCluster(clusters, node);
clusterDb[node.id].node = node;
} else {
node.y += subGraphTitleTotalMargin / 2;
positionNode(node);
}
}
@ -134,6 +146,7 @@ const recursiveRender = async (_elem, graph, diagramtype, id, parentCluster) =>
const edge = graph.edge(e);
log.info('Edge ' + e.v + ' -> ' + e.w + ': ' + JSON.stringify(edge), edge);
edge.points.forEach((point) => (point.y += subGraphTitleTotalMargin / 2));
const paths = insertEdge(edgePaths, e, edge, clusterDb, diagramtype, graph, id);
positionEdgeLabel(edge, paths);
});
@ -159,7 +172,8 @@ export const render = async (elem, graph, markers, diagramtype, id) => {
adjustClustersAndEdges(graph);
log.warn('Graph after:', JSON.stringify(graphlibJson.write(graph)));
// log.warn('Graph ever after:', graphlibJson.write(graph.node('A').graph));
await recursiveRender(elem, graph, diagramtype, id);
const siteConfig = getConfig();
await recursiveRender(elem, graph, diagramtype, id, undefined, siteConfig);
};
// const shapeDefinitions = {};

View File

@ -1013,6 +1013,7 @@ const class_box = (parent, node) => {
});
rect
.attr('style', node.style)
.attr('class', 'outer title-state')
.attr('x', -maxWidth / 2 - halfPadding)
.attr('y', -(maxHeight / 2) - halfPadding)

View File

@ -80,7 +80,9 @@ export const labelHelper = async (parent, node, _classes, isNode) => {
? getConfig().fontSize
: window.getComputedStyle(document.body).fontSize;
const enlargingFactor = 5;
img.style.width = parseInt(bodyFontSize, 10) * enlargingFactor + 'px';
const width = parseInt(bodyFontSize, 10) * enlargingFactor + 'px';
img.style.minWidth = width;
img.style.maxWidth = width;
} else {
img.style.width = '100%';
}

View File

@ -84,6 +84,7 @@ export const addClass = function (_id: string) {
methods: [],
members: [],
annotations: [],
styles: [],
domId: MERMAID_DOM_ID_PREFIX + name + '-' + classCounter,
} as ClassNode;
@ -214,7 +215,7 @@ export const cleanupLabel = function (label: string) {
};
/**
* Called by parser when a special node is found, e.g. a clickable element.
* Called by parser when assigning cssClass to a class
*
* @param ids - Comma separated list of ids
* @param className - Class to add
@ -446,11 +447,27 @@ const getNamespaces = function (): NamespaceMap {
* @public
*/
export const addClassesToNamespace = function (id: string, classNames: string[]) {
if (namespaces[id] !== undefined) {
classNames.map((className) => {
classes[className].parent = id;
namespaces[id].classes[className] = classes[className];
});
if (namespaces[id] === undefined) {
return;
}
for (const name of classNames) {
const { className } = splitClassNameAndType(name);
classes[className].parent = id;
namespaces[id].classes[className] = classes[className];
}
};
export const setCssStyle = function (id: string, styles: string[]) {
const thisClass = classes[id];
if (!styles || !thisClass) {
return;
}
for (const s of styles) {
if (s.includes(',')) {
thisClass.styles.push(...s.split(','));
} else {
thisClass.styles.push(s);
}
}
};
@ -490,4 +507,5 @@ export default {
addClassesToNamespace,
getNamespace,
getNamespaces,
setCssStyle,
};

View File

@ -56,5 +56,18 @@ describe('class diagram, ', function () {
expect(parser.yy.getClass('Class01').cssClasses[0]).toBe('exClass');
expect(parser.yy.getClass('Class02').cssClasses[0]).toBe('exClass');
});
it('should be possible to apply a style to an individual node', function () {
const str =
'classDiagram\n' +
'class Class01\n class Class02\n style Class01 fill:#f9f,stroke:#333,stroke-width:4px';
parser.parse(str);
const styleElements = parser.yy.getClass('Class01').styles;
expect(styleElements[0]).toBe('fill:#f9f');
expect(styleElements[1]).toBe('stroke:#333');
expect(styleElements[2]).toBe('stroke-width:4px');
});
});
});

View File

@ -409,6 +409,7 @@ class C13["With Città foreign language"]
},
],
"methods": [],
"styles": [],
"type": "",
}
`);
@ -1043,6 +1044,19 @@ foo()
`;
parser.parse(str);
});
it('should handle namespace with generic types', () => {
parser.parse(`classDiagram
namespace space {
class Square~Shape~{
int id
List~int~ position
setPoints(List~int~ points)
getPoints() List~int~
}
}`);
});
});
});

View File

@ -104,7 +104,7 @@ export const addClasses = function (
*/
const cssClassStr = vertex.cssClasses.join(' ');
const styles = { labelStyle: '', style: '' }; //getStylesFromArray(vertex.styles);
const styles = getStylesFromArray(vertex.styles);
// Use vertex id as text in the box if no text is provided by the graph definition
const vertexText = vertex.label ?? vertex.id;

View File

@ -10,6 +10,7 @@ export interface ClassNode {
members: ClassMember[];
annotations: string[];
domId: string;
styles: string[];
parent?: string;
link?: string;
linkTarget?: string;

View File

@ -60,6 +60,7 @@ Function arguments are optional: 'call <callback_name>()' simply executes 'callb
<string>["] this.popState();
<string>[^"]* return "STR";
<*>["] this.begin("string");
"style" return 'STYLE';
<INITIAL,namespace>"namespace" { this.begin('namespace'); return 'NAMESPACE'; }
<namespace>\s*(\r?\n)+ { this.popState(); return 'NEWLINE'; }
@ -127,6 +128,10 @@ line was introduced with 'click'.
<*>\- return 'MINUS';
<*>"." return 'DOT';
<*>\+ return 'PLUS';
":" return 'COLON';
"," return 'COMMA';
\# return 'BRKT';
"#" return 'BRKT';
<*>\% return 'PCT';
<*>"=" return 'EQUALS';
<*>\= return 'EQUALS';
@ -198,6 +203,7 @@ line was introduced with 'click'.
[\uFFD2-\uFFD7\uFFDA-\uFFDC]
return 'UNICODE_TEXT';
<*>\s return 'SPACE';
\s return 'SPACE';
<*><<EOF>> return 'EOF';
/lex
@ -254,6 +260,7 @@ statement
| memberStatement
| annotationStatement
| clickStatement
| styleStatement
| cssClassStatement
| noteStatement
| direction
@ -365,10 +372,26 @@ clickStatement
| CLICK className HREF STR STR LINK_TARGET {$$ = $1;yy.setLink($2, $4, $6);yy.setTooltip($2, $5);}
;
cssClassStatement
: CSSCLASS STR alphaNumToken {yy.setCssClass($2, $3);}
styleStatement
:STYLE ALPHA stylesOpt {$$ = $STYLE;yy.setCssStyle($2,$stylesOpt);}
;
cssClassStatement
: CSSCLASS STR ALPHA {yy.setCssClass($2, $3);}
;
stylesOpt
: style {$$ = [$style]}
| stylesOpt COMMA style {$stylesOpt.push($style);$$ = $stylesOpt;}
;
style
: styleComponent
| style styleComponent {$$ = $style + $styleComponent;}
;
styleComponent: ALPHA | NUM | COLON | UNIT | SPACE | BRKT | STYLE | PCT | LABEL;
commentToken : textToken | graphCodeTokens ;
textToken : textNoTagsToken | TAGSTART | TAGEND | '==' | '--' | PCT | DEFAULT;

View File

@ -145,6 +145,7 @@ g.classGroup line {
.edgeTerminals {
font-size: 11px;
line-height: initial;
}
.classTitleText {

View File

@ -14,8 +14,6 @@ import {
} from '../common/commonDb.js';
import type { FlowVertex, FlowClass, FlowSubGraph, FlowText, FlowEdge, FlowLink } from './types.js';
const MAX_EDGE_COUNT = 280;
const MERMAID_DOM_ID_PREFIX = 'flowchart-';
let vertexCounter = 0;
let config = getConfig();
@ -87,7 +85,6 @@ export const addVertex = function (
if (txt[0] === '"' && txt[txt.length - 1] === '"') {
txt = txt.substring(1, txt.length - 1);
}
vertices[id].text = txt;
} else {
if (vertices[id].text === undefined) {
@ -144,9 +141,20 @@ export const addSingleLink = function (_start: string, _end: string, type: any)
edge.stroke = type.stroke;
edge.length = type.length > 10 ? 10 : type.length;
}
if (edge?.length && edge.length > 10) {
edge.length = 10;
}
if (edges.length < (config.maxEdges ?? 500)) {
log.info('abc78 pushing edge...');
edges.push(edge);
} else {
throw new Error(
`Edge limit exceeded. ${edges.length} edges found, but the limit is ${config.maxEdges}.
if (edges.length > MAX_EDGE_COUNT) {
throw new Error('Too many edges');
Initialize mermaid with maxEdges set to a higher number to allow more edges.
You cannot set this config via configuration inside the diagram as it is a secure config.
You have to call mermaid.initialize.`
);
}
log.info('Pushing edge...');
@ -442,6 +450,7 @@ export const clear = function (ver = 'gen-1') {
tooltips = {};
firstGraphFlag = true;
version = ver;
config = getConfig();
commonClear();
};

View File

@ -255,11 +255,12 @@ export const merge = function (otherBranch, custom_id, override_type, custom_tag
log.debug('in mergeBranch');
};
export const cherryPick = function (sourceId, targetId, tag) {
export const cherryPick = function (sourceId, targetId, tag, parentCommitId) {
log.debug('Entering cherryPick:', sourceId, targetId, tag);
sourceId = common.sanitizeText(sourceId, getConfig());
targetId = common.sanitizeText(targetId, getConfig());
tag = common.sanitizeText(tag, getConfig());
parentCommitId = common.sanitizeText(parentCommitId, getConfig());
if (!sourceId || commits[sourceId] === undefined) {
let error = new Error(
@ -274,20 +275,21 @@ export const cherryPick = function (sourceId, targetId, tag) {
};
throw error;
}
let sourceCommit = commits[sourceId];
let sourceCommitBranch = sourceCommit.branch;
if (sourceCommit.type === commitType.MERGE) {
if (
parentCommitId &&
!(Array.isArray(sourceCommit.parents) && sourceCommit.parents.includes(parentCommitId))
) {
let error = new Error(
'Incorrect usage of "cherryPick". Source commit should not be a merge commit'
'Invalid operation: The specified parent commit is not an immediate parent of the cherry-picked commit.'
);
throw error;
}
if (sourceCommit.type === commitType.MERGE && !parentCommitId) {
let error = new Error(
'Incorrect usage of cherry-pick: If the source commit is a merge commit, an immediate parent commit must be specified.'
);
error.hash = {
text: 'cherryPick ' + sourceId + ' ' + targetId,
token: 'cherryPick ' + sourceId + ' ' + targetId,
line: '1',
loc: { first_line: 1, last_line: 1, first_column: 1, last_column: 1 },
expected: ['cherry-pick abc'],
};
throw error;
}
if (!targetId || commits[targetId] === undefined) {
@ -327,7 +329,11 @@ export const cherryPick = function (sourceId, targetId, tag) {
parents: [head == null ? null : head.id, sourceCommit.id],
branch: curBranch,
type: commitType.CHERRY_PICK,
tag: tag ?? 'cherry-pick:' + sourceCommit.id,
tag:
tag ??
`cherry-pick:${sourceCommit.id}${
sourceCommit.type === commitType.MERGE ? `|parent:${parentCommitId}` : ''
}`,
};
head = commit;
commits[commit.id] = commit;

View File

@ -673,6 +673,145 @@ describe('when parsing a gitGraph', function () {
expect(commits[cherryPickCommitID].branch).toBe('main');
});
it('should support cherry-picking of merge commits', function () {
const str = `gitGraph
commit id: "ZERO"
branch feature
branch release
checkout feature
commit id: "A"
commit id: "B"
checkout main
merge feature id: "M"
checkout release
cherry-pick id: "M" parent:"B"
`;
parser.parse(str);
const commits = parser.yy.getCommits();
const cherryPickCommitID = Object.keys(commits)[4];
expect(commits[cherryPickCommitID].tag).toBe('cherry-pick:M|parent:B');
expect(commits[cherryPickCommitID].branch).toBe('release');
});
it('should support cherry-picking of merge commits with tag', function () {
const str = `gitGraph
commit id: "ZERO"
branch feature
branch release
checkout feature
commit id: "A"
commit id: "B"
checkout main
merge feature id: "M"
checkout release
cherry-pick id: "M" parent:"ZERO" tag: "v1.0"
`;
parser.parse(str);
const commits = parser.yy.getCommits();
const cherryPickCommitID = Object.keys(commits)[4];
expect(commits[cherryPickCommitID].tag).toBe('v1.0');
expect(commits[cherryPickCommitID].branch).toBe('release');
});
it('should support cherry-picking of merge commits with additional commit', function () {
const str = `gitGraph
commit id: "ZERO"
branch feature
branch release
checkout feature
commit id: "A"
commit id: "B"
checkout main
merge feature id: "M"
checkout release
commit id: "C"
cherry-pick id: "M" tag: "v2.1:ZERO" parent:"ZERO"
commit id: "D"
`;
parser.parse(str);
const commits = parser.yy.getCommits();
const cherryPickCommitID = Object.keys(commits)[5];
expect(commits[cherryPickCommitID].tag).toBe('v2.1:ZERO');
expect(commits[cherryPickCommitID].branch).toBe('release');
});
it('should support cherry-picking of merge commits with empty tag', function () {
const str = `gitGraph
commit id: "ZERO"
branch feature
branch release
checkout feature
commit id: "A"
commit id: "B"
checkout main
merge feature id: "M"
checkout release
commit id: "C"
cherry-pick id:"M" parent: "ZERO" tag:""
commit id: "D"
cherry-pick id:"M" tag:"" parent: "B"
`;
parser.parse(str);
const commits = parser.yy.getCommits();
const cherryPickCommitID = Object.keys(commits)[5];
const cherryPickCommitID2 = Object.keys(commits)[7];
expect(commits[cherryPickCommitID].tag).toBe('');
expect(commits[cherryPickCommitID2].tag).toBe('');
expect(commits[cherryPickCommitID].branch).toBe('release');
});
it('should fail cherry-picking of merge commits if the parent of merge commits is not specified', function () {
expect(() =>
parser
.parse(
`gitGraph
commit id: "ZERO"
branch feature
branch release
checkout feature
commit id: "A"
commit id: "B"
checkout main
merge feature id: "M"
checkout release
commit id: "C"
cherry-pick id:"M"
`
)
.toThrow(
'Incorrect usage of cherry-pick: If the source commit is a merge commit, an immediate parent commit must be specified.'
)
);
});
it('should fail cherry-picking of merge commits when the parent provided is not an immediate parent of cherry picked commit', function () {
expect(() =>
parser
.parse(
`gitGraph
commit id: "ZERO"
branch feature
branch release
checkout feature
commit id: "A"
commit id: "B"
checkout main
merge feature id: "M"
checkout release
commit id: "C"
cherry-pick id:"M" parent: "A"
`
)
.toThrow(
'Invalid operation: The specified parent commit is not an immediate parent of the cherry-picked commit.'
)
);
});
it('should throw error when try to branch existing branch: main', function () {
const str = `gitGraph
commit

View File

@ -39,6 +39,7 @@ branch(?=\s|$) return 'BRANCH';
"order:" return 'ORDER';
merge(?=\s|$) return 'MERGE';
cherry\-pick(?=\s|$) return 'CHERRY_PICK';
"parent:" return 'PARENT_COMMIT'
// "reset" return 'RESET';
checkout(?=\s|$) return 'CHECKOUT';
"LR" return 'DIR';
@ -109,10 +110,17 @@ branchStatement
cherryPickStatement
: CHERRY_PICK COMMIT_ID STR {yy.cherryPick($3, '', undefined)}
| CHERRY_PICK COMMIT_ID STR PARENT_COMMIT STR {yy.cherryPick($3, '', undefined,$5)}
| CHERRY_PICK COMMIT_ID STR COMMIT_TAG STR {yy.cherryPick($3, '', $5)}
| CHERRY_PICK COMMIT_ID STR COMMIT_TAG EMPTYSTR {yy.cherryPick($3, '', '')}
| CHERRY_PICK COMMIT_ID STR PARENT_COMMIT STR COMMIT_TAG STR {yy.cherryPick($3, '', $7,$5)}
| CHERRY_PICK COMMIT_ID STR COMMIT_TAG STR PARENT_COMMIT STR {yy.cherryPick($3, '', $5,$7)}
| CHERRY_PICK COMMIT_TAG STR COMMIT_ID STR {yy.cherryPick($5, '', $3)}
| CHERRY_PICK COMMIT_TAG EMPTYSTR COMMIT_ID STR {yy.cherryPick($3, '', '')}
| CHERRY_PICK COMMIT_TAG EMPTYSTR COMMIT_ID STR {yy.cherryPick($5, '', '')}
| CHERRY_PICK COMMIT_ID STR COMMIT_TAG EMPTYSTR {yy.cherryPick($3, '', '')}
| CHERRY_PICK COMMIT_ID STR PARENT_COMMIT STR COMMIT_TAG EMPTYSTR {yy.cherryPick($3, '', '',$5)}
| CHERRY_PICK COMMIT_ID STR COMMIT_TAG EMPTYSTR PARENT_COMMIT STR {yy.cherryPick($3, '', '',$7)}
| CHERRY_PICK COMMIT_TAG STR COMMIT_ID STR PARENT_COMMIT STR {yy.cherryPick($5, '', $3,$7)}
| CHERRY_PICK COMMIT_TAG EMPTYSTR COMMIT_ID STR PARENT_COMMIT STR{yy.cherryPick($5, '', '',$7)}
;
mergeStatement

View File

@ -1,6 +1,5 @@
import type d3 from 'd3';
import { scaleOrdinal, pie as d3pie, arc } from 'd3';
import { log } from '../../logger.js';
import { configureSvgSize } from '../../setupGraphViewbox.js';
import { getConfig } from '../../diagram-api/diagramAPI.js';
@ -38,33 +37,25 @@ const createPieArcs = (sections: Sections): d3.PieArcDatum<D3Sections>[] => {
*/
export const draw: DrawDefinition = (text, id, _version, diagObj) => {
log.debug('rendering pie chart\n' + text);
const db = diagObj.db as PieDB;
const globalConfig: MermaidConfig = getConfig();
const pieConfig: Required<PieDiagramConfig> = cleanAndMerge(db.getConfig(), globalConfig.pie);
const height = 450;
// TODO: remove document width
const width: number =
document.getElementById(id)?.parentElement?.offsetWidth ?? pieConfig.useWidth;
const svg: SVG = selectSvgElement(id);
// Set viewBox
svg.attr('viewBox', `0 0 ${width} ${height}`);
configureSvgSize(svg, height, width, pieConfig.useMaxWidth);
const MARGIN = 40;
const LEGEND_RECT_SIZE = 18;
const LEGEND_SPACING = 4;
const height = 450;
const pieWidth: number = height;
const svg: SVG = selectSvgElement(id);
const group: Group = svg.append('g');
group.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
const sections: Sections = db.getSections();
group.attr('transform', 'translate(' + pieWidth / 2 + ',' + height / 2 + ')');
const { themeVariables } = globalConfig;
let [outerStrokeWidth] = parseFontSize(themeVariables.pieOuterStrokeWidth);
outerStrokeWidth ??= 2;
const textPosition: number = pieConfig.textPosition;
const radius: number = Math.min(width, height) / 2 - MARGIN;
const radius: number = Math.min(pieWidth, height) / 2 - MARGIN;
// Shape helper to build arcs:
const arcGenerator: d3.Arc<unknown, d3.PieArcDatum<D3Sections>> = arc<
d3.PieArcDatum<D3Sections>
@ -84,7 +75,6 @@ export const draw: DrawDefinition = (text, id, _version, diagObj) => {
.attr('r', radius + outerStrokeWidth / 2)
.attr('class', 'pieOuterCircle');
const sections: Sections = db.getSections();
const arcs: d3.PieArcDatum<D3Sections>[] = createPieArcs(sections);
const myGeneratedColors = [
@ -177,6 +167,19 @@ export const draw: DrawDefinition = (text, id, _version, diagObj) => {
}
return label;
});
const longestTextWidth = Math.max(
...legend
.selectAll('text')
.nodes()
.map((node) => (node as Element)?.getBoundingClientRect().width ?? 0)
);
const totalWidth = pieWidth + MARGIN + LEGEND_RECT_SIZE + LEGEND_SPACING + longestTextWidth;
// Set viewBox
svg.attr('viewBox', `0 0 ${totalWidth} ${height}`);
configureSvgSize(svg, height, totalWidth, pieConfig.useMaxWidth);
};
export const renderer = { draw };

View File

@ -16,7 +16,7 @@ import {
sankeyCenter as d3SankeyCenter,
sankeyJustify as d3SankeyJustify,
} from 'd3-sankey';
import { configureSvgSize } from '../../setupGraphViewbox.js';
import { setupGraphViewbox } from '../../setupGraphViewbox.js';
import { Uid } from '../../rendering-util/uid.js';
import type { SankeyNodeAlignment } from '../../config.type.js';
@ -70,12 +70,6 @@ export const draw = function (text: string, id: string, _version: string, diagOb
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)`
//
// @ts-ignore TODO: svg type vs selection mismatch
configureSvgSize(svg, height, width, useMaxWidth);
// Prepare data for construction based on diagObj.db
// This must be a mutable object with `nodes` and `links` properties:
//
@ -208,6 +202,8 @@ export const draw = function (text: string, id: string, _version: string, diagOb
.attr('d', d3SankeyLinkHorizontal())
.attr('stroke', coloring)
.attr('stroke-width', (d: any) => Math.max(1, d.width));
setupGraphViewbox(undefined, svg, 0, useMaxWidth);
};
export default {

View File

@ -2,57 +2,60 @@ import { getConfig } from '../../diagram-api/diagramAPI.js';
import { log } from '../../logger.js';
import { sanitizeText } from '../common/common.js';
import {
setAccTitle,
getAccTitle,
setDiagramTitle,
getDiagramTitle,
getAccDescription,
setAccDescription,
clear as commonClear,
getAccDescription,
getAccTitle,
getDiagramTitle,
setAccDescription,
setAccTitle,
setDiagramTitle,
} from '../common/commonDb.js';
import { ImperativeState } from '../../utils/imperativeState.js';
let prevActor = undefined;
let actors = {};
let createdActors = {};
let destroyedActors = {};
let boxes = [];
let messages = [];
const notes = [];
let sequenceNumbersEnabled = false;
let wrapEnabled;
let currentBox = undefined;
let lastCreated = undefined;
let lastDestroyed = undefined;
const state = new ImperativeState(() => ({
prevActor: undefined,
actors: {},
createdActors: {},
destroyedActors: {},
boxes: [],
messages: [],
notes: [],
sequenceNumbersEnabled: false,
wrapEnabled: undefined,
currentBox: undefined,
lastCreated: undefined,
lastDestroyed: undefined,
}));
export const addBox = function (data) {
boxes.push({
state.records.boxes.push({
name: data.text,
wrap: (data.wrap === undefined && autoWrap()) || !!data.wrap,
fill: data.color,
actorKeys: [],
});
currentBox = boxes.slice(-1)[0];
state.records.currentBox = state.records.boxes.slice(-1)[0];
};
export const addActor = function (id, name, description, type) {
let assignedBox = currentBox;
const old = actors[id];
let assignedBox = state.records.currentBox;
const old = state.records.actors[id];
if (old) {
// If already set and trying to set to a new one throw error
if (currentBox && old.box && currentBox !== old.box) {
if (state.records.currentBox && old.box && state.records.currentBox !== old.box) {
throw new Error(
'A same participant should only be defined in one Box: ' +
old.name +
" can't be in '" +
old.box.name +
"' and in '" +
currentBox.name +
state.records.currentBox.name +
"' at the same time."
);
}
// Don't change the box if already
assignedBox = old.box ? old.box : currentBox;
assignedBox = old.box ? old.box : state.records.currentBox;
old.box = assignedBox;
// Don't allow description nulling
@ -69,36 +72,42 @@ export const addActor = function (id, name, description, type) {
description = { text: name, wrap: null, type };
}
actors[id] = {
state.records.actors[id] = {
box: assignedBox,
name: name,
description: description.text,
wrap: (description.wrap === undefined && autoWrap()) || !!description.wrap,
prevActor: prevActor,
prevActor: state.records.prevActor,
links: {},
properties: {},
actorCnt: null,
rectData: null,
type: type || 'participant',
};
if (prevActor && actors[prevActor]) {
actors[prevActor].nextActor = id;
if (state.records.prevActor && state.records.actors[state.records.prevActor]) {
state.records.actors[state.records.prevActor].nextActor = id;
}
if (currentBox) {
currentBox.actorKeys.push(id);
if (state.records.currentBox) {
state.records.currentBox.actorKeys.push(id);
}
prevActor = id;
state.records.prevActor = id;
};
const activationCount = (part) => {
let i;
let count = 0;
for (i = 0; i < messages.length; i++) {
if (messages[i].type === LINETYPE.ACTIVE_START && messages[i].from.actor === part) {
for (i = 0; i < state.records.messages.length; i++) {
if (
state.records.messages[i].type === LINETYPE.ACTIVE_START &&
state.records.messages[i].from.actor === part
) {
count++;
}
if (messages[i].type === LINETYPE.ACTIVE_END && messages[i].from.actor === part) {
if (
state.records.messages[i].type === LINETYPE.ACTIVE_END &&
state.records.messages[i].from.actor === part
) {
count--;
}
}
@ -106,7 +115,7 @@ const activationCount = (part) => {
};
export const addMessage = function (idFrom, idTo, message, answer) {
messages.push({
state.records.messages.push({
from: idFrom,
to: idTo,
message: message.text,
@ -137,7 +146,7 @@ export const addSignal = function (
throw error;
}
}
messages.push({
state.records.messages.push({
from: idFrom,
to: idTo,
message: message.text,
@ -149,63 +158,58 @@ export const addSignal = function (
};
export const hasAtLeastOneBox = function () {
return boxes.length > 0;
return state.records.boxes.length > 0;
};
export const hasAtLeastOneBoxWithTitle = function () {
return boxes.some((b) => b.name);
return state.records.boxes.some((b) => b.name);
};
export const getMessages = function () {
return messages;
return state.records.messages;
};
export const getBoxes = function () {
return boxes;
return state.records.boxes;
};
export const getActors = function () {
return actors;
return state.records.actors;
};
export const getCreatedActors = function () {
return createdActors;
return state.records.createdActors;
};
export const getDestroyedActors = function () {
return destroyedActors;
return state.records.destroyedActors;
};
export const getActor = function (id) {
return actors[id];
return state.records.actors[id];
};
export const getActorKeys = function () {
return Object.keys(actors);
return Object.keys(state.records.actors);
};
export const enableSequenceNumbers = function () {
sequenceNumbersEnabled = true;
state.records.sequenceNumbersEnabled = true;
};
export const disableSequenceNumbers = function () {
sequenceNumbersEnabled = false;
state.records.sequenceNumbersEnabled = false;
};
export const showSequenceNumbers = () => sequenceNumbersEnabled;
export const showSequenceNumbers = () => state.records.sequenceNumbersEnabled;
export const setWrap = function (wrapSetting) {
wrapEnabled = wrapSetting;
state.records.wrapEnabled = wrapSetting;
};
export const autoWrap = () => {
// if setWrap has been called, use that value, otherwise use the value from the config
// TODO: refactor, always use the config value let setWrap update the config value
if (wrapEnabled !== undefined) {
return wrapEnabled;
if (state.records.wrapEnabled !== undefined) {
return state.records.wrapEnabled;
}
return getConfig().sequence.wrap;
};
export const clear = function () {
actors = {};
createdActors = {};
destroyedActors = {};
boxes = [];
messages = [];
sequenceNumbersEnabled = false;
state.reset();
commonClear();
};
@ -247,7 +251,7 @@ export const parseBoxData = function (str) {
}
}
const boxData = {
return {
color: color,
text:
title !== undefined
@ -262,7 +266,6 @@ export const parseBoxData = function (str) {
: undefined
: undefined,
};
return boxData;
};
export const LINETYPE = {
@ -321,8 +324,8 @@ export const addNote = function (actor, placement, message) {
// eslint-disable-next-line unicorn/prefer-spread
const actors = [].concat(actor, actor);
notes.push(note);
messages.push({
state.records.notes.push(note);
state.records.messages.push({
from: actors[0],
to: actors[1],
message: message.text,
@ -414,7 +417,7 @@ function insertProperties(actor, properties) {
*
*/
function boxEnd() {
currentBox = undefined;
state.records.currentBox = undefined;
}
export const addDetails = function (actorId, text) {
@ -468,7 +471,7 @@ export const apply = function (param) {
} else {
switch (param.type) {
case 'sequenceIndex':
messages.push({
state.records.messages.push({
from: undefined,
to: undefined,
message: {
@ -484,18 +487,18 @@ export const apply = function (param) {
addActor(param.actor, param.actor, param.description, param.draw);
break;
case 'createParticipant':
if (actors[param.actor]) {
if (state.records.actors[param.actor]) {
throw new Error(
"It is not possible to have actors with the same id, even if one is destroyed before the next is created. Use 'AS' aliases to simulate the behavior"
);
}
lastCreated = param.actor;
state.records.lastCreated = param.actor;
addActor(param.actor, param.actor, param.description, param.draw);
createdActors[param.actor] = messages.length;
state.records.createdActors[param.actor] = state.records.messages.length;
break;
case 'destroyParticipant':
lastDestroyed = param.actor;
destroyedActors[param.actor] = messages.length;
state.records.lastDestroyed = param.actor;
state.records.destroyedActors[param.actor] = state.records.messages.length;
break;
case 'activeStart':
addSignal(param.actor, undefined, undefined, param.signalType);
@ -519,25 +522,28 @@ export const apply = function (param) {
addDetails(param.actor, param.text);
break;
case 'addMessage':
if (lastCreated) {
if (param.to !== lastCreated) {
if (state.records.lastCreated) {
if (param.to !== state.records.lastCreated) {
throw new Error(
'The created participant ' +
lastCreated +
state.records.lastCreated +
' does not have an associated creating message after its declaration. Please check the sequence diagram.'
);
} else {
lastCreated = undefined;
state.records.lastCreated = undefined;
}
} else if (lastDestroyed) {
if (param.to !== lastDestroyed && param.from !== lastDestroyed) {
} else if (state.records.lastDestroyed) {
if (
param.to !== state.records.lastDestroyed &&
param.from !== state.records.lastDestroyed
) {
throw new Error(
'The destroyed participant ' +
lastDestroyed +
state.records.lastDestroyed +
' does not have an associated destroying message after its declaration. Please check the sequence diagram.'
);
} else {
lastDestroyed = undefined;
state.records.lastDestroyed = undefined;
}
}
addSignal(param.from, param.to, param.msg, param.signalType, param.activate);

View File

@ -829,11 +829,6 @@ export const draw = function (_text: string, id: string, _version: string, diagO
bounds.insert(activationData.startx, verticalPos - 10, activationData.stopx, verticalPos);
}
log.debug('createdActors', createdActors);
log.debug('destroyedActors', destroyedActors);
drawActors(diagram, actors, actorKeys, false);
// Draw the messages/signals
let sequenceIndex = 1;
let sequenceIndexStep = 1;
@ -1033,12 +1028,14 @@ export const draw = function (_text: string, id: string, _version: string, diagO
}
});
messagesToDraw.forEach((e) => drawMessage(diagram, e.messageModel, e.lineStartY, diagObj));
log.debug('createdActors', createdActors);
log.debug('destroyedActors', destroyedActors);
drawActors(diagram, actors, actorKeys, false);
messagesToDraw.forEach((e) => drawMessage(diagram, e.messageModel, e.lineStartY, diagObj));
if (conf.mirrorActors) {
drawActors(diagram, actors, actorKeys, true);
}
backgrounds.forEach((e) => svgDraw.drawBackgroundRect(diagram, e));
fixLifeLineHeights(diagram, actors, actorKeys, conf);

View File

@ -324,7 +324,7 @@ const drawActorTypeParticipant = function (elem, actor, conf, isFooter) {
const center = actor.x + actor.width / 2;
const centerY = actorY + 5;
const boxpluslineGroup = elem.append('g');
const boxpluslineGroup = elem.append('g').lower();
var g = boxpluslineGroup;
if (!isFooter) {

View File

@ -2,13 +2,25 @@
<div
class="w-full top-bar bg-gradient-to-r from-[#bd34fe] to-[#ff3670] flex items-center text-center justify-center p-1 text-white"
>
<a
href="https://www.producthunt.com/posts/mermaid-chart?utm_source=badge-featured&amp;utm_medium=badge&amp;utm_souce=badge-mermaid-chart"
target="_blank"
>
We've made our Product Hunt debut! &nbsp;
<span class="underline">Show us some love and help spread the word</span>, plus receive 25%
off on annual Pro subscription!</a
>
<p class="flex-grow text-center tracking-wide text-text">
<a
href="https://www.mermaidchart.com/app/user/billing/checkout"
target="_blank"
class="unstyled flex-grow tracking-wide plausible-event-name=bannerClick"
>
<span class="text-primary-50 font-semibold">{{
[
'Try diagramming with ChatGPT at Mermaid Chart',
'Try Mermaids Visual Editor at Mermaid Chart',
'Enjoy live collaboration with teammates at Mermaid Chart',
][Math.floor(Math.random() * 3)]
}}</span>
<button
class="ml-4 rounded bg-[#111113] p-1 px-2 text-sm font-semibold tracking-wide text-white"
>
Try it now
</button>
</a>
</p>
</div>
</template>

View File

@ -31,7 +31,7 @@ export default defineConfig({
defer: 'true',
'data-domain': 'mermaid.js.org',
// All tracked stats are public and available at https://p.mermaid.live/mermaid.js.org
src: 'https://p.mermaid.live/js/script.js',
src: 'https://p.mermaid.live/js/script.tagged-events.outbound-links.js',
},
],
],
@ -49,6 +49,9 @@ export default defineConfig({
sidebar: {
'/': sidebarAll(),
},
outline: {
level: 'deep',
},
socialLinks: [
{ icon: 'github', link: 'https://github.com/mermaid-js/mermaid' },
{
@ -71,17 +74,17 @@ function nav() {
{ text: 'Docs', link: '/intro/', activeMatch: '/intro/' },
{
text: 'Tutorials',
link: '/config/Tutorials',
activeMatch: '/config/',
link: '/ecosystem/tutorials',
activeMatch: '/ecosystem/tutorials',
},
{
text: 'Integrations',
link: '/ecosystem/integrations-community',
activeMatch: '/ecosystem/',
activeMatch: '/ecosystem/integrations-community',
},
{
text: 'Contributing',
link: '/community/development.html',
link: '/community/intro',
activeMatch: '/community/',
},
{
@ -96,10 +99,6 @@ function nav() {
text: 'Changelog',
link: 'https://github.com/mermaid-js/mermaid/releases',
},
{
text: 'Contributing',
link: '/community/development',
},
],
},
{
@ -167,7 +166,6 @@ function sidebarConfig() {
collapsed: false,
items: [
{ text: 'Configuration', link: '/config/configuration' },
{ text: 'Tutorials', link: '/config/Tutorials' },
{ text: 'API-Usage', link: '/config/usage' },
{ text: 'Mermaid API Configuration', link: '/config/setup/README' },
{ text: 'Mermaid Configuration Options', link: '/config/schema-docs/config' },
@ -175,7 +173,6 @@ function sidebarConfig() {
{ text: 'Theming', link: '/config/theming' },
{ text: 'Accessibility', link: '/config/accessibility' },
{ text: 'Mermaid CLI', link: '/config/mermaidCLI' },
{ text: 'Advanced usage', link: '/config/advanced' },
{ text: 'FAQ', link: '/config/faq' },
],
},
@ -189,6 +186,7 @@ function sidebarEcosystem() {
collapsed: false,
items: [
{ text: 'Mermaid Chart', link: '/ecosystem/mermaid-chart' },
{ text: 'Tutorials', link: '/ecosystem/tutorials' },
{ text: 'Integrations - Community', link: '/ecosystem/integrations-community' },
{ text: 'Integrations - Create', link: '/ecosystem/integrations-create' },
],
@ -199,14 +197,13 @@ function sidebarEcosystem() {
function sidebarCommunity() {
return [
{
text: '🙌 Contributions and Community',
text: '🙌 Contributing',
collapsed: false,
items: [
{ text: 'Contributing to Mermaid', link: '/community/development' },
{ text: 'Contributing Code', link: '/community/code' },
{ text: 'Contributing Documentation', link: '/community/documentation' },
{ text: 'Getting Started', link: '/community/intro' },
{ text: 'Contributing to Mermaid', link: '/community/contributing' },
{ text: 'Adding Diagrams', link: '/community/new-diagram' },
{ text: 'Questions and Suggestions', link: '/community/questions-and-suggestions' },
{ text: 'Adding Diagrams', link: '/community/newDiagram' },
{ text: 'Security', link: '/community/security' },
],
},

View File

@ -6,8 +6,8 @@ import Mermaid from './Mermaid.vue';
import Contributors from '../components/Contributors.vue';
// @ts-ignore
import HomePage from '../components/HomePage.vue';
// // @ts-ignore
// import TopBar from '../components/TopBar.vue';
// @ts-ignore
import TopBar from '../components/TopBar.vue';
import { getRedirect } from './redirect.js';
@ -22,7 +22,7 @@ export default {
Layout() {
return h(Theme.Layout, null, {
// Keeping this as comment as it took a lot of time to figure out how to add a component to the top bar.
// 'home-hero-before': () => h(TopBar),
'home-hero-before': () => h(TopBar),
'home-features-after': () => h(HomePage),
});
},

View File

@ -38,6 +38,20 @@ test.each([
['https://mermaid.js.org/#/flowchart.md', 'syntax/flowchart.html'],
// New docs, without base path, new domain
['https://mermaid.js.org/misc/faq.html', 'configure/faq.html'],
['https://mermaid.js.org/community/newDiagram.html', 'community/new-diagram.html'],
[
'https://mermaid.js.org/community/development.html',
'community/contributing.html#initial-setup',
],
[
'https://mermaid.js.org/community/docker-development.html',
'community/contributing.html#initial-setup',
],
['https://mermaid.js.org/community/code.html', 'community/contributing.html#contributing-code'],
[
'https://mermaid.js.org/community/documentation.html',
'community/contributing.html#contributing-documentation',
],
[
'https://mermaid.js.org/misc/faq.html#frequently-asked-questions',
'configure/faq.html#frequently-asked-questions',

View File

@ -58,7 +58,7 @@ const idRedirectMap: Record<string, string> = {
'n00b-gettingstarted': 'intro/getting-started',
'n00b-overview': 'intro/getting-started',
'n00b-syntaxreference': 'intro/syntax-reference',
newdiagram: 'community/newDiagram',
newdiagram: 'community/new-diagram',
pie: 'syntax/pie',
plugins: '',
quickstart: 'intro/getting-started',
@ -69,7 +69,7 @@ const idRedirectMap: Record<string, string> = {
statediagram: 'syntax/stateDiagram',
themes: 'config/theming',
theming: 'config/theming',
tutorials: 'config/Tutorials',
tutorials: 'ecosystem/tutorials',
upgrading: '',
usage: 'config/usage',
'user-journey': 'syntax/userJourney',
@ -88,10 +88,15 @@ const urlRedirectMap: Record<string, string> = {
'/syntax/c4c.html': 'syntax/c4.html',
'/ecosystem/integrations.html': 'ecosystem/integrations-community.html',
'/ecosystem/showcases.html': 'ecosystem/integrations-create',
'/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',
'/config/n00b-advanced.html': 'config/configuration.html',
'/intro/n00b-gettingStarted.html': 'intro/getting-started.html',
'/intro/n00b-syntaxReference.html': 'intro/syntax-reference.html',
'/community/n00b-overview.html': 'intro/getting-started.html',
'/community/newDiagram.html': 'community/new-diagram.html',
'/community/development.html': 'community/contributing.html#initial-setup',
'/community/docker-development.html': 'community/contributing.html#initial-setup',
'/community/code.html': 'community/contributing.html#contributing-code',
'/community/documentation.html': 'community/contributing.html#contributing-documentation',
};
/**

View File

@ -1,165 +0,0 @@
# 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 following 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

@ -0,0 +1,523 @@
# Mermaid Contributing Guide
You decided to take part in the development? Welcome!
We are trying to make our guidelines for you as explicit and detailed as possible.
## Initial Setup
Initial setup consists of 3 main steps:
```mermaid-nocode
flowchart LR
source --> requirements --> setup
source[Get the Source Code]
requirements[Install the Requirements]
setup[Install Packages]
```
### Get the Source Code
In GitHub, you first [**fork a mermaid repository**](https://github.com/mermaid-js/mermaid/fork) 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.
```tip
[Here is a GitHub document that gives an overview of the process](https://docs.github.com/en/get-started/quickstart/fork-a-repo).
```
```bash
git clone git@github.com/your-fork/mermaid
```
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
```
### Install Requirements
We support **development within Docker** environment along with **host setup**. You may choose it up to your preferences.
**Host**
These are the tools we use for working with the code and documentation:
- [Node.js](https://nodejs.org/en/).
- [pnpm](https://pnpm.io/) package manager.
The following commands must be sufficient enough to start with:
```bash
curl -fsSL https://get.pnpm.io/install.sh | sh -
pnpm env use --global 18
```
You may also need to reload `.shrc` or `.bashrc` afterwards.
**Docker**
[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.
### Install Packages
**Host**
Install packages:
```bash
pnpm install
```
**Docker**
For development using Docker there is a self-documented `run` bash script, which provides convenient aliases for `docker compose` commands.
Make sure that `./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.
```
Then install packages:
```bash
./run pnpm install
```
### Verify Everything Works
This step is optional, but it helps to make sure that everything in development branch was OK before you started making any changes.
You can run the `test` script to verify that pnpm is working _and_ that the repository has been cloned correctly:
**Host**
```bash
pnpm test
```
**Docker**
```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.
```note
You might see _lint_ or _formatting_ warnings. Those are ok during this step.
```
## Workflow
Contributing process is very simple and strightforward:
```mermaid-nocode
flowchart LR
branch --> changes --> submit
branch[Checkout a New Branch]
changes[Make Changes]
submit[Submit a PR]
```
Mermaid uses a [Git Flow](https://guides.github.com/introduction/flow/)inspired approach to branching.
Development is done in the `develop` branch.
```mermaid-nocode
---
config:
gitGraph:
mainBranchName: develop
---
gitGraph LR:
commit
commit
branch "docs/2910_update-guidelines" order: 1
commit
commit
commit
checkout develop
merge "docs/2910_update-guidelines"
commit
```
To prepare a new version for release the maintainers 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.
## Checkout a New Branch
```tip
All new work should be based on the `develop` branch.
```
Make sure you have the most up-to-date version of the `develop` branch.
Check out the `develop` branch, then `fetch` or `pull` to update it:
```bash
git checkout develop
git fetch # or `git pull`
```
Create a new branch for your work:
```bash
git checkout -b docs/2910_update-contributing-guidelines
```
We use the following naming convention for branches:
```txt
[feature | bug | chore | docs]/[issue number]_[short-description]
```
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`, `docs`
- followed by a **slash** (`/`),which helps to group like types together in many git tools
- followed by the **issue number**, e.g. `2910`
- followed by an **underscore** (`_`)
- followed by a **short description** with dashes (`-`) or underscores (`_`) instead of spaces
```mermaid-nocode
flowchart LR
feature --> slash
bug --> slash
chore --> slash
docs --> slash
slash --> 2945 --> underscore
slash --> 1123 --> underscore
underscore --> short_description_1
underscore --> short_description_2
underscore["_"]
slash["/"]
short_description_1["state-diagram-new-arrow-florbs"]
short_description_2["fix_random_ugly_red_text"]
```
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 by a diagram type.
```note
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`
```
```tip
A bug described in issue 1123 that causes random ugly red text in multiple diagram types
`bug/1123_fix_random_ugly_red_text`
```
## Contributing Code
Code is the heart of every software project. We strive to make it better. Who if not us?
### Where is the Code Located?
The core of Mermaid is located under `packages/mermaid/src`.
### Running Mermaid Locally
**Host**
```bash
pnpm run dev
```
**Docker**
```bash
./run dev
```
After starting the dev server open <http://localhost:9000> in your browser.
Now you are ready to make your changes!
### Make Changes
Have a look at <http://localhost:9000>. 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 and automatically reload the page.
Edit files in `packages/mermaid/src` as required.
### 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 for all code except the renderers. (The renderers are tested with integration tests.)
We use [Vitest](https://vitest.dev) to run unit tests.
**Host**
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
```
**Docker**
When using Docker prepend your command with `./run`:
```sh
./run pnpm test
```
#### 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:
**Host**
- Run `pnpm dev` to start the dev server
- Start **Cypress** by running `pnpm cypress:open`
**Docker**
- Enable local connections for x11 server `xhost +local:`
- Run `./run pnpm dev` to start the dev server
- Start **Cypress** by running `./run pnpm cypress:open --project .`
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 }
);
});
```
<!-- **_[TODO - running the tests against what is expected in development. ]_** -->
<!-- **_[TODO - how to generate new screenshots]_** -->
### Update Documentation
```tip
Our documentation is managed in `packages/mermaid/src/docs`. Details on how to edit is in the [documentation section](#contributing-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 for users to know that things have been 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.
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!)
## Contributing Documentation
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?
### Where is the Documentation Located?
```warning
DO NOT CHANGE FILES IN `/docs`
The `docs` folder will be automatically generated when committing to `packages/mermaid/src/docs` and **should not** be edited manually.
```
Documentation is located in the [`packages/mermaid/src/docs`](https://github.com/mermaid-js/mermaid/tree/develop/packages/mermaid/src/docs) folder. 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.
```mermaid
flowchart LR
classDef default fill:#fff,color:black,stroke:black
source["Edit /packages/mermaid/src/docs"] -- automatic processing--> published["View /docs which will be publised on Official Website"]
```
### Running the Documentation Website Locally
**[The mermaid documentation site](https://mermaid.js.org/) is powered by [Vitepress](https://vitepress.vuejs.org/).**
Start development server for the documentation site
**Host**
```bash
pnpm --filter mermaid run docs:dev
```
or
```bash
cd packages/mermaid
pnpm docs:dev
```
**Docker**
```bash
./run docs:dev
```
Open [http://localhost:3333/](http://localhost:3333/) in your browser.
### Formatting
The documentation is written in Markdown. To get acquainted with its syntax [see the GitHub Markdown help page](https://help.github.com/en/github/writing-on-github/basic-writing-and-formatting-syntax).
You can use `note`, `tip`, `warning` and `danger` in triple backticks to add a note, tip, warning or danger box.
```danger
Do not use vitepress specific markdown syntax `::: warning` as it will not be processed correctly.
```
Here are a few examples:
````markdown
```note
This is a note
```
```tip
This is a tip
```
```warning
This is a warning
```
```danger
This is a danger alert
```
````
```note
This is a note
```
```tip
This is a tip
```
```warning
This is a warning
```
```danger
This is a danger alert
```
### 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**, which is defined in [the vitepress config](../.vitepress/config.ts). The same goes to **topbar**.
### Build Docs
The content of `/docs` folder is built with Github Actions.
```warning
So as to allow automatic compilation of documentation pages you have to enable Github Actions on your fork first
```
## Submit your pull request
````note
Do not forget to push your changes
```bash
git push -u origin docs/2910_update-guidelines
```
````
We make all changes via Pull Requests (PRs). Open a new one.
Right now we are not following any strict rules about naming PRs. Give it a representative title and short description. There is also a [pull request template](https://github.com/mermaid-js/mermaid/blob/develop/.github/pull_request_template.md) which will help you with it.
In case in its description contains a [magic comment](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) your PR will be automatically attached to the issue:
```markdown
Resolves #<your issue ID here>
```
## Congratulations
You have successfully submitted your improvements! What is next?
- 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.
Thanks for you help!

View File

@ -1,90 +0,0 @@
# Contributing to Mermaid
> 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!
![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 documentation, 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.](#install-packages)
Follow the setup steps below to install them and start the development.
## 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
```
### Install packages
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
```
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

@ -1,104 +0,0 @@
# 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 documentation, 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)

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