Merge develop into HEAD; install; lint:fix

This commit is contained in:
Ashley Engelund (weedySeaDragon @ github)
2022-11-25 10:40:04 -08:00
parent ee0f872b5b
commit 3eb2bb9c0b
105 changed files with 2108 additions and 597 deletions

View File

@@ -21,7 +21,16 @@
"plugin:@cspell/recommended", "plugin:@cspell/recommended",
"prettier" "prettier"
], ],
"plugins": ["@typescript-eslint", "no-only-tests", "html", "jest", "jsdoc", "json", "@cspell"], "plugins": [
"@typescript-eslint",
"no-only-tests",
"html",
"jest",
"jsdoc",
"json",
"@cspell",
"lodash"
],
"rules": { "rules": {
"curly": "error", "curly": "error",
"no-console": "error", "no-console": "error",
@@ -53,7 +62,8 @@
"allowEmptyCatch": true "allowEmptyCatch": true
} }
], ],
"no-only-tests/no-only-tests": "error" "no-only-tests/no-only-tests": "error",
"lodash/import-scope": ["error", "method"]
}, },
"overrides": [ "overrides": [
{ {

View File

@@ -1,28 +0,0 @@
name: Documentation Checks
on:
push:
branches:
- develop
paths:
- 'packages/mermaid/src/docs/**/*'
pull_request:
branches:
- develop
paths:
- 'packages/mermaid/src/docs/**/*'
jobs:
spellcheck:
name: 'Docs: Spellcheck'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
name: Check out the code
- uses: actions/setup-node@v3
name: Setup node
with:
node-version: '18'
- run: npm install -g cspell
name: Install cSpell
- run: cspell --config ./cSpell.json "packages/mermaid/src/docs/**/*.md" --no-progress
name: Run cSpell

View File

@@ -36,7 +36,7 @@ jobs:
restore-keys: cache-lychee- restore-keys: cache-lychee-
- name: Link Checker - name: Link Checker
uses: lycheeverse/lychee-action@v1.5.2 uses: lycheeverse/lychee-action@v1.5.4
with: with:
args: --verbose --no-progress --cache --max-cache-age 1d packages/mermaid/src/docs/**/*.md README.md README.zh-CN.md args: --verbose --no-progress --cache --max-cache-age 1d packages/mermaid/src/docs/**/*.md README.md README.zh-CN.md
fail: true fail: true

1
.gitignore vendored
View File

@@ -35,3 +35,4 @@ tsconfig.tsbuildinfo
knsv*.html knsv*.html
local*.html local*.html
stats/

View File

@@ -1,4 +0,0 @@
{
"!(docs/**/*)*.{ts,js,json,html,md,mts}": ["eslint --fix", "prettier --write"],
"cSpell.json": ["ts-node-esm scripts/fixCSpell.ts"]
}

5
.lintstagedrc.mjs Normal file
View File

@@ -0,0 +1,5 @@
export default {
'!(docs/**/*)*.{ts,js,json,html,md,mts}': ['eslint --fix', 'prettier --write'],
'cSpell.json': ['ts-node-esm scripts/fixCSpell.ts'],
'**/*.jison': ['pnpm -w run lint:jison'],
};

View File

@@ -3,4 +3,5 @@ cypress/platform/xss3.html
.cache .cache
coverage coverage
# Autogenerated by PNPM # Autogenerated by PNPM
pnpm-lock.yaml pnpm-lock.yaml
stats

View File

@@ -1,9 +1,12 @@
import { build, InlineConfig } from 'vite'; import { build, InlineConfig, type PluginOption } from 'vite';
import { resolve } from 'path'; import { resolve } from 'path';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
import jisonPlugin from './jisonPlugin.js'; import jisonPlugin from './jisonPlugin.js';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { visualizer } from 'rollup-plugin-visualizer';
import type { TemplateType } from 'rollup-plugin-visualizer/dist/plugin/template-types.js';
const visualize = process.argv.includes('--visualize');
const watch = process.argv.includes('--watch'); const watch = process.argv.includes('--watch');
const mermaidOnly = process.argv.includes('--mermaid'); const mermaidOnly = process.argv.includes('--mermaid');
const __dirname = fileURLToPath(new URL('.', import.meta.url)); const __dirname = fileURLToPath(new URL('.', import.meta.url));
@@ -13,6 +16,20 @@ type OutputOptions = Exclude<
undefined undefined
>['output']; >['output'];
const visualizerOptions = (packageName: string, core = false): PluginOption[] => {
if (packageName !== 'mermaid' || !visualize) {
return [];
}
return ['network', 'treemap', 'sunburst'].map((chartType) =>
visualizer({
filename: `./stats/${chartType}${core ? '.core' : ''}.html`,
template: chartType as TemplateType,
gzipSize: true,
brotliSize: true,
})
);
};
const packageOptions = { const packageOptions = {
mermaid: { mermaid: {
name: 'mermaid', name: 'mermaid',
@@ -39,7 +56,7 @@ interface BuildOptions {
} }
export const getBuildConfig = ({ minify, core, watch, entryName }: BuildOptions): InlineConfig => { export const getBuildConfig = ({ minify, core, watch, entryName }: BuildOptions): InlineConfig => {
const external = ['require', 'fs', 'path']; const external: (string | RegExp)[] = ['require', 'fs', 'path'];
console.log(entryName, packageOptions[entryName]); console.log(entryName, packageOptions[entryName]);
const { name, file, packageName } = packageOptions[entryName]; const { name, file, packageName } = packageOptions[entryName];
let output: OutputOptions = [ let output: OutputOptions = [
@@ -63,7 +80,9 @@ export const getBuildConfig = ({ minify, core, watch, entryName }: BuildOptions)
); );
// Core build is used to generate file without bundled dependencies. // Core build is used to generate file without bundled dependencies.
// This is used by downstream projects to bundle dependencies themselves. // This is used by downstream projects to bundle dependencies themselves.
external.push(...Object.keys(dependencies)); // Ignore dependencies and any dependencies of dependencies
// Adapted from the RegEx used by `rollup-plugin-node`
external.push(new RegExp('^(?:' + Object.keys(dependencies).join('|') + ')(?:/.+)?$'));
// This needs to be an array. Otherwise vite will build esm & umd with same name and overwrite esm with umd. // This needs to be an array. Otherwise vite will build esm & umd with same name and overwrite esm with umd.
output = [ output = [
{ {
@@ -95,7 +114,7 @@ export const getBuildConfig = ({ minify, core, watch, entryName }: BuildOptions)
resolve: { resolve: {
extensions: ['.jison', '.js', '.ts', '.json'], extensions: ['.jison', '.js', '.ts', '.json'],
}, },
plugins: [jisonPlugin()], plugins: [jisonPlugin(), ...visualizerOptions(packageName, core)],
}; };
if (watch && config.build) { if (watch && config.build) {
@@ -121,7 +140,7 @@ const buildPackage = async (entryName: keyof typeof packageOptions) => {
const main = async () => { const main = async () => {
const packageNames = Object.keys(packageOptions) as (keyof typeof packageOptions)[]; const packageNames = Object.keys(packageOptions) as (keyof typeof packageOptions)[];
for (const pkg of packageNames) { for (const pkg of packageNames.filter((pkg) => !mermaidOnly || pkg === 'mermaid')) {
await buildPackage(pkg); await buildPackage(pkg);
} }
}; };
@@ -132,6 +151,9 @@ if (watch) {
build(getBuildConfig({ minify: false, watch, entryName: 'mermaid-mindmap' })); build(getBuildConfig({ minify: false, watch, entryName: 'mermaid-mindmap' }));
// build(getBuildConfig({ minify: false, watch, entryName: 'mermaid-example-diagram' })); // build(getBuildConfig({ minify: false, watch, entryName: 'mermaid-example-diagram' }));
} }
} else if (visualize) {
await build(getBuildConfig({ minify: false, core: true, entryName: 'mermaid' }));
await build(getBuildConfig({ minify: false, core: false, entryName: 'mermaid' }));
} else { } else {
void main(); void main();
} }

View File

@@ -1,23 +1,6 @@
# mermaid # mermaid
[![Build CI Status](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml/badge.svg)](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml) [![NPM](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid) [![Coverage Status](https://coveralls.io/repos/github/mermaid-js/mermaid/badge.svg?branch=master)](https://coveralls.io/github/mermaid-js/mermaid?branch=master) [![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid) [![NPM](https://img.shields.io/npm/dm/mermaid)](https://www.npmjs.com/package/mermaid) [![Join our Slack!](https://img.shields.io/static/v1?message=join%20chat&color=9cf&logo=slack&label=slack)](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE) [![Twitter Follow](https://img.shields.io/twitter/follow/mermaidjs_?style=social)](https://twitter.com/mermaidjs_) [![Build CI Status](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml/badge.svg)](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml) [![NPM](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid) [![npm minified gzipped bundle size](https://img.shields.io/bundlephobia/minzip/mermaid)](https://bundlephobia.com/package/mermaid) [![Coverage Status](https://coveralls.io/repos/github/mermaid-js/mermaid/badge.svg?branch=master)](https://coveralls.io/github/mermaid-js/mermaid?branch=master) [![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid) [![NPM](https://img.shields.io/npm/dm/mermaid)](https://www.npmjs.com/package/mermaid) [![Join our Slack!](https://img.shields.io/static/v1?message=join%20chat&color=9cf&logo=slack&label=slack)](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE) [![Twitter Follow](https://img.shields.io/twitter/follow/mermaidjs_?style=social)](https://twitter.com/mermaidjs_)
# Whoa, what's going on here?
We are transforming the Mermaid repository to a so called mono-repo. This is a part of the effort to decouple the diagrams from the core of mermaid. This will:
- Make it possible to select which diagrams to include on your site
- Open up for lazy loading
- Make it possible to add diagrams from outside of the Mermaid repository
- Separate the release flow between different diagrams and the Mermaid core
As such be aware of some changes..
# We use pnpm now
# The source code has moved
It is now located in the src folder for each respective package located as subfolders in packages.
English | [简体中文](./README.zh-CN.md) English | [简体中文](./README.zh-CN.md)

View File

@@ -1,6 +1,6 @@
# mermaid # mermaid
[![Build CI Status](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml/badge.svg)](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml) [![NPM](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid) [![Coverage Status](https://coveralls.io/repos/github/mermaid-js/mermaid/badge.svg?branch=master)](https://coveralls.io/github/mermaid-js/mermaid?branch=master) [![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid) [![NPM](https://img.shields.io/npm/dm/mermaid)](https://www.npmjs.com/package/mermaid) [![Join our Slack!](https://img.shields.io/static/v1?message=join%20chat&color=9cf&logo=slack&label=slack)](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE) [![Twitter Follow](https://img.shields.io/twitter/follow/mermaidjs_?style=social)](https://twitter.com/mermaidjs_) [![Build CI Status](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml/badge.svg)](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml) [![NPM](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid) [![npm minified gzipped bundle size](https://img.shields.io/bundlephobia/minzip/mermaid)](https://bundlephobia.com/package/mermaid) [![Coverage Status](https://coveralls.io/repos/github/mermaid-js/mermaid/badge.svg?branch=master)](https://coveralls.io/github/mermaid-js/mermaid?branch=master) [![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid) [![NPM](https://img.shields.io/npm/dm/mermaid)](https://www.npmjs.com/package/mermaid) [![Join our Slack!](https://img.shields.io/static/v1?message=join%20chat&color=9cf&logo=slack&label=slack)](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE) [![Twitter Follow](https://img.shields.io/twitter/follow/mermaidjs_?style=social)](https://twitter.com/mermaidjs_)
[English](./README.md) | 简体中文 [English](./README.md) | 简体中文

View File

@@ -53,6 +53,18 @@ export const MockD3 = (name, parent) => {
get __parent() { get __parent() {
return parent; return parent;
}, },
node() {
return {
getBBox() {
return {
x: 5,
y: 10,
height: 15,
width: 20,
};
},
};
},
}; };
elem.append = (name) => { elem.append = (name) => {
const mockElem = MockD3(name, elem); const mockElem = MockD3(name, elem);

View File

@@ -496,4 +496,16 @@ describe('Class diagram V2', () => {
); );
cy.get('svg'); cy.get('svg');
}); });
it('1433: should render a simple class with a title', () => {
imgSnapshotTest(
`---
title: simple class diagram
---
classDiagram-v2
class Class10
`,
{}
);
});
}); });

View File

@@ -273,4 +273,17 @@ describe('Entity Relationship Diagram', () => {
); );
cy.get('svg'); cy.get('svg');
}); });
it('1433: should render a simple ER diagram with a title', () => {
imgSnapshotTest(
`---
title: simple ER diagram
---
erDiagram
CUSTOMER ||--o{ ORDER : places
ORDER ||--|{ LINE-ITEM : contains
`,
{}
);
});
}); });

View File

@@ -663,4 +663,15 @@ flowchart RL
{ htmlLabels: true, flowchart: { htmlLabels: true }, securityLevel: 'loose' } { htmlLabels: true, flowchart: { htmlLabels: true }, securityLevel: 'loose' }
); );
}); });
it('1433: should render a titled flowchart with titleTopMargin set to 0', () => {
imgSnapshotTest(
`---
title: Simple flowchart
---
flowchart TD
A --> B
`,
{ titleTopMargin: 0 }
);
});
}); });

View File

@@ -322,4 +322,15 @@ describe('Git Graph diagram', () => {
{} {}
); );
}); });
it('1433: should render a simple gitgraph with a title', () => {
imgSnapshotTest(
`---
title: simple gitGraph
---
gitGraph
commit
`,
{}
);
});
}); });

View File

@@ -1,75 +0,0 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
describe('Mindmap', () => {
it('square shape', () => {
imgSnapshotTest(
`
mindmap
root[
The root
]
`,
{}
);
cy.get('svg');
});
it('rounded rect shape', () => {
imgSnapshotTest(
`
mindmap
root((
The root
))
`,
{}
);
cy.get('svg');
});
it('circle shape', () => {
imgSnapshotTest(
`
mindmap
root(
The root
)
`,
{}
);
cy.get('svg');
});
it('default shape', () => {
imgSnapshotTest(
`
mindmap
The root
`,
{}
);
cy.get('svg');
});
it('adding children', () => {
imgSnapshotTest(
`
mindmap
The root
child1
child2
`,
{}
);
cy.get('svg');
});
it('adding grand children', () => {
imgSnapshotTest(
`
mindmap
The root
child1
child2
child3
`,
{}
);
cy.get('svg');
});
});

View File

@@ -1,115 +0,0 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
describe('Mindmaps', () => {
it('Only a root', () => {
imgSnapshotTest(
`mindmap
root
`,
{}
);
});
it('a root with a shape', () => {
imgSnapshotTest(
`mindmap
root[root]
`,
{}
);
});
it('a root with wrapping text and a shape', () => {
imgSnapshotTest(
`mindmap
root[A root with a long text that wraps to keep the node size in check]
`,
{}
);
});
it('a root with an icon', () => {
imgSnapshotTest(
`mindmap
root[root]
::icon(mdi mdi-fire)
`,
{}
);
});
it('Blang and cloud shape', () => {
imgSnapshotTest(
`mindmap
root))bang((
::icon(mdi mdi-fire)
a))Another bang((
::icon(mdi mdi-fire)
a)A cloud(
::icon(mdi mdi-fire)
`,
{}
);
});
it('Blang and cloud shape with icons', () => {
imgSnapshotTest(
`mindmap
root))bang((
a))Another bang((
a)A cloud(
`,
{}
);
});
it('braches', () => {
imgSnapshotTest(
`mindmap
root
child1
grandchild 1
grandchild 2
child2
grandchild 3
grandchild 4
child3
grandchild 5
grandchild 6
`,
{}
);
});
it('braches with shapes and labels', () => {
imgSnapshotTest(
`mindmap
root
child1((Circle))
grandchild 1
grandchild 2
child2(Round rectangle)
grandchild 3
grandchild 4
child3[Square]
grandchild 5
::icon(mdi mdi-fire)
gc6((grand<br/>child 6))
::icon(mdi mdi-fire)
`,
{}
);
});
it('text shouhld wrap with icon', () => {
imgSnapshotTest(
`mindmap
root
Child3(A node with an icon and with a long text that wraps to keep the node size in check)
`,
{}
);
});
/* The end */
});

View File

@@ -0,0 +1,233 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
/**
* Check whether the SVG Element has a Mindmap root
*
* Sometimes, Cypress takes a snapshot before the mermaid mindmap has finished
* generating the SVG.
*
* @param $p - The element to check.
*/
function shouldHaveRoot($p: JQuery<SVGSVGElement>) {
// get HTML Element from jquery element
const svgElement = $p[0];
expect(svgElement.nodeName).equal('svg');
const sectionRoots = svgElement.getElementsByClassName('mindmap-node section-root');
// mindmap should have at least one root section
expect(sectionRoots).to.have.lengthOf.at.least(1);
}
describe('Mindmaps', () => {
it('Only a root', () => {
imgSnapshotTest(
`mindmap
root
`,
{},
undefined,
shouldHaveRoot
);
});
it('a root with a shape', () => {
imgSnapshotTest(
`mindmap
root[root]
`,
{},
undefined,
shouldHaveRoot
);
});
it('a root with wrapping text and a shape', () => {
imgSnapshotTest(
`mindmap
root[A root with a long text that wraps to keep the node size in check]
`,
{},
undefined,
shouldHaveRoot
);
});
it('a root with an icon', () => {
imgSnapshotTest(
`mindmap
root[root]
::icon(mdi mdi-fire)
`,
{},
undefined,
shouldHaveRoot
);
});
it('Blang and cloud shape', () => {
imgSnapshotTest(
`mindmap
root))bang((
::icon(mdi mdi-fire)
a))Another bang((
::icon(mdi mdi-fire)
a)A cloud(
::icon(mdi mdi-fire)
`,
{},
undefined,
shouldHaveRoot
);
});
it('Blang and cloud shape with icons', () => {
imgSnapshotTest(
`mindmap
root))bang((
a))Another bang((
a)A cloud(
`,
{},
undefined,
shouldHaveRoot
);
});
it('braches', () => {
imgSnapshotTest(
`mindmap
root
child1
grandchild 1
grandchild 2
child2
grandchild 3
grandchild 4
child3
grandchild 5
grandchild 6
`,
{},
undefined,
shouldHaveRoot
);
});
it('braches with shapes and labels', () => {
imgSnapshotTest(
`mindmap
root
child1((Circle))
grandchild 1
grandchild 2
child2(Round rectangle)
grandchild 3
grandchild 4
child3[Square]
grandchild 5
::icon(mdi mdi-fire)
gc6((grand<br/>child 6))
::icon(mdi mdi-fire)
`,
{},
undefined,
shouldHaveRoot
);
});
it('text shouhld wrap with icon', () => {
imgSnapshotTest(
`mindmap
root
Child3(A node with an icon and with a long text that wraps to keep the node size in check)
`,
{},
undefined,
shouldHaveRoot
);
});
it('square shape', () => {
imgSnapshotTest(
`
mindmap
root[
The root
]
`,
{},
undefined,
shouldHaveRoot
);
cy.get('svg');
});
it('rounded rect shape', () => {
imgSnapshotTest(
`
mindmap
root((
The root
))
`,
{},
undefined,
shouldHaveRoot
);
cy.get('svg');
});
it('circle shape', () => {
imgSnapshotTest(
`
mindmap
root(
The root
)
`,
{},
undefined,
shouldHaveRoot
);
cy.get('svg');
});
it('default shape', () => {
imgSnapshotTest(
`
mindmap
The root
`,
{},
undefined,
shouldHaveRoot
);
cy.get('svg');
});
it('adding children', () => {
imgSnapshotTest(
`
mindmap
The root
child1
child2
`,
{},
undefined,
shouldHaveRoot
);
cy.get('svg');
});
it('adding grand children', () => {
imgSnapshotTest(
`
mindmap
The root
child1
child2
child3
`,
{},
undefined,
shouldHaveRoot
);
cy.get('svg');
});
/* The end */
});

View File

@@ -559,4 +559,16 @@ stateDiagram-v2
); );
}); });
}); });
it('1433: should render a simple state diagram with a title', () => {
imgSnapshotTest(
`---
title: simple state diagram
---
stateDiagram-v2
[*] --> State1
State1 --> [*]
`,
{}
);
});
}); });

8
cypress/tsconfig.json Normal file
View File

@@ -0,0 +1,8 @@
{
"compilerOptions": {
"target": "es2020",
"lib": ["es2020", "dom"],
"types": ["cypress", "node"]
},
"include": ["**/*.ts"]
}

View File

@@ -17,6 +17,9 @@
<h1>Class diagram demos</h1> <h1>Class diagram demos</h1>
<pre class="mermaid"> <pre class="mermaid">
---
title: Demo Class Diagram
---
classDiagram classDiagram
accTitle: Demo Class Diagram accTitle: Demo Class Diagram
accDescr: This class diagram show the abstract Animal class, and 3 classes that inherit from it: Duck, Fish, and Zebra. accDescr: This class diagram show the abstract Animal class, and 3 classes that inherit from it: Duck, Fish, and Zebra.

View File

@@ -20,6 +20,9 @@
<body> <body>
<pre class="mermaid"> <pre class="mermaid">
---
title: This is a title
---
erDiagram erDiagram
%% title This is a title %% title This is a title
%% accDescription Test a description %% accDescription Test a description

View File

@@ -17,6 +17,9 @@
<h2>Sample 1</h2> <h2>Sample 1</h2>
<h3>graph</h3> <h3>graph</h3>
<pre class="mermaid"> <pre class="mermaid">
---
title: This is a complicated flow
---
graph LR graph LR
accTitle: This is a complicated flow accTitle: This is a complicated flow
accDescr: This is the descriptoin for the complicated flow. accDescr: This is the descriptoin for the complicated flow.
@@ -221,6 +224,9 @@
<h2>Sample 2</h2> <h2>Sample 2</h2>
<h3>graph</h3> <h3>graph</h3>
<pre class="mermaid"> <pre class="mermaid">
---
title: What to buy
---
graph TD graph TD
accTitle: What to buy accTitle: What to buy
accDescr: Options of what to buy with Christmas money accDescr: Options of what to buy with Christmas money

View File

@@ -16,6 +16,9 @@
<body> <body>
<h1>Git diagram demo</h1> <h1>Git diagram demo</h1>
<pre class="mermaid"> <pre class="mermaid">
---
title: Simple Git diagram
---
gitGraph: gitGraph:
options options
{ {

View File

@@ -48,6 +48,9 @@
<li> <li>
<h2><a href="./journey.html">Journey</a></h2> <h2><a href="./journey.html">Journey</a></h2>
</li> </li>
<li>
<h2><a href="./mindmap.html">Mindmap</a></h2>
</li>
<li> <li>
<h2><a href="./pie.html">Pie</a></h2> <h2><a href="./pie.html">Pie</a></h2>
</li> </li>

View File

@@ -16,8 +16,10 @@
<body> <body>
<h1>Journey diagram demo</h1> <h1>Journey diagram demo</h1>
<pre class="mermaid"> <pre class="mermaid">
journey ---
title My working day title: My working day
---
journey
accTitle: Very simple journey demo accTitle: Very simple journey demo
accDescr: 2 main sections: work and home, each with just a few tasks accDescr: 2 main sections: work and home, each with just a few tasks

108
demos/mindmap.html Normal file
View File

@@ -0,0 +1,108 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Mindmap Mermaid Quick Test Page</title>
<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgo=" />
<style>
div.mermaid {
/* font-family: 'trebuchet ms', verdana, arial; */
font-family: 'Courier New', Courier, monospace !important;
}
</style>
</head>
<body>
<h1>Mindmap diagram demo</h1>
<pre class="mermaid">
mindmap
root
child1((Circle))
grandchild 1
grandchild 2
child2(Round rectangle)
grandchild 3
grandchild 4
child3[Square]
grandchild 5
::icon(mdi mdi-fire)
gc6((grand<br/>child 6))
::icon(mdi mdi-fire)
gc7((grand<br/>grand<br/>child 8))
</pre>
<h2>Mindmap with root wrapping text and a shape</h2>
<pre class="mermaid">
mindmap
root[A root with a long text that wraps to keep the node size in check]
</pre>
<script type="module">
import mermaid from './mermaid.esm.mjs';
import mermaidMindmap from './mermaid-mindmap.esm.mjs';
const ALLOWED_TAGS = [
'a',
'b',
'blockquote',
'br',
'dd',
'div',
'dl',
'dt',
'em',
'foreignObject',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'h7',
'h8',
'hr',
'i',
'li',
'ul',
'ol',
'p',
'pre',
'span',
'strike',
'strong',
'table',
'tbody',
'td',
'tfoot',
'th',
'thead',
'tr',
];
mermaid.parseError = function (err, hash) {
// console.error('Mermaid error: ', err);
};
await mermaid.registerExternalDiagrams([mermaidMindmap]);
mermaid.initialize({
theme: 'base',
startOnLoad: true,
logLevel: 0,
flowchart: {
useMaxWidth: false,
htmlLabels: true,
},
gantt: {
useMaxWidth: false,
},
useMaxWidth: false,
});
function callback() {
alert('It worked');
}
mermaid.parseError = function (err, hash) {
console.error('In parse error:');
console.error(err);
};
</script>
</body>
</html>

View File

@@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en" xmlns="http://www.w3.org/1999/html">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" />
@@ -17,6 +17,9 @@
<h1>State diagram demos</h1> <h1>State diagram demos</h1>
<h2>Very simple showing change from State1 to State2</h2> <h2>Very simple showing change from State1 to State2</h2>
<pre class="mermaid"> <pre class="mermaid">
---
title: Very simple diagram
---
stateDiagram stateDiagram
accTitle: This is the accessible title accTitle: This is the accessible title
accDescr:This is an accessible description accDescr:This is an accessible description
@@ -30,8 +33,9 @@
<p> <p>
<code> <code>
classDef notMoving fill:white<br /> classDef notMoving fill:white<br />
classDef movement font-style:italic;<br /> classDef movement font-style:italic<br />
classDef badBadEvent fill:#f00,color:white,font-weight:bold<br /> classDef badBadEvent
fill:#f00,color:white,font-weight:bold,stroke-width:2px,stroke:yellow<br />
</code> </code>
</p> </p>
<h4>And these are how they are applied:</h4> <h4>And these are how they are applied:</h4>
@@ -43,15 +47,20 @@
</code> </code>
</p> </p>
<pre class="mermaid"> <pre class="mermaid">
stateDiagram-v2 ---
title: Very simple diagram
---
stateDiagram
direction TB
accTitle: This is the accessible title accTitle: This is the accessible title
accDescr: This is an accessible description accDescr: This is an accessible description
classDef notMoving fill:white classDef notMoving fill:white
classDef movement font-style:italic; classDef movement font-style:italic
classDef badBadEvent fill:#f00,color:white,font-weight:bold classDef badBadEvent fill:#f00,color:white,font-weight:bold,stroke-width:2px,stroke:yellow
[*] --> Still [*]--> Still
Still --> [*] Still --> [*]
Still --> Moving Still --> Moving
Moving --> Still Moving --> Still
@@ -61,10 +70,57 @@
class Still notMoving class Still notMoving
class Moving, Crash movement class Moving, Crash movement
class Crash badBadEvent class Crash badBadEvent
class end badBadEvent
</pre> </pre>
<hr /> <hr />
<h2>Here is a diagram that uses the ::: operator to apply styles to states</h2>
<h4>Here are the <code>classDef</code> statements:</h4>
<p>
<code>
classDef notMoving fill:white<br />
classDef movement font-style:italic<br />
classDef badBadEvent
fill:#f00,color:white,font-weight:bold,stroke-width:2px,stroke:yellow<br />
</code>
</p>
<h4>And these are how they are applied:</h4>
<p>
<code>
[*] --> Still:::notMoving<br />
...<br />
Still --> Moving:::movement<br />
...<br />
Moving --> Crash:::movement<br />
Crash:::badBadEvent --> [*]<br />
</code>
</p>
<p>
Note that both the starting state and the end state have styles applied:<br />
The start state has the <i>start</i> classDef style<br />and the end state has the
<i>stop</i> classDef style applied.
</p>
<pre class="mermaid">
stateDiagram
direction TB
accTitle: This is the accessible title
accDescr: This is an accessible description
classDef notMoving fill:white
classDef movement font-style:italic
classDef badBadEvent fill:#f00,color:white,font-weight:bold,stroke-width:2px,stroke:yellow
[*] --> Still:::notMoving
Still --> [*]
Still --> Moving:::movement
Moving --> Still
Moving --> Crash:::movement
Crash:::badBadEvent --> [*]
</pre>
<hr />
<pre class="mermaid"> <pre class="mermaid">
stateDiagram-v2 stateDiagram-v2
accTitle: very very simple state accTitle: very very simple state
@@ -73,6 +129,20 @@
</pre> </pre>
<hr /> <hr />
<h2>States with spaces in them</h2>
<pre class="mermaid">
stateDiagram
classDef yourState font-style:italic,font-weight:bold,fill:white
yswsii: Your state with spaces in it
[*] --> yswsii:::yourState
[*] --> SomeOtherState
SomeOtherState --> YetAnotherState
yswsii --> YetAnotherState
YetAnotherState --> [*]
</pre>
<hr />
<h2>You can label the relationships</h2> <h2>You can label the relationships</h2>
<pre class="mermaid"> <pre class="mermaid">
stateDiagram-v2 stateDiagram-v2
@@ -121,7 +191,7 @@
<pre class="mermaid"> <pre class="mermaid">
stateDiagram-v2 stateDiagram-v2
[*] --> S1 [*] --> S1
S1 --> S2: This long line uses a br tag<br/>to create multiple<br/>lines. S1 --> S2: This long line uses a br tag<br />to create multiple<br />lines.
S1 --> S3: This transition descripton uses \na newline character\nto create multiple\nlines. S1 --> S3: This transition descripton uses \na newline character\nto create multiple\nlines.
</pre> </pre>
@@ -133,7 +203,7 @@
direction LR direction LR
State1: A state with a note State1: A state with a note
note right of State1 note right of State1
Important information!<br />You can write notes.<br/>And\nthey\ncan\nbe\nmulti-\nline. Important information!<br />You can write notes.<br />And\nthey\ncan\nbe\nmulti-\nline.
end note end note
State1 --> State2 State1 --> State2
note left of State2 : Notes can be to the left of a state\n(like this one). note left of State2 : Notes can be to the left of a state\n(like this one).

View File

@@ -14,7 +14,7 @@
#### Defined in #### Defined in
[defaultConfig.ts:1881](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/defaultConfig.ts#L1881) [defaultConfig.ts:1933](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/defaultConfig.ts#L1933)
--- ---

View File

@@ -348,7 +348,7 @@ on what kind of integration you use.
## Using the mermaid object ## Using the mermaid object
Is it possible to set some configuration via the mermaid object. The two parameters that are supported using this It is possible to set some configuration via the mermaid object. The two parameters that are supported using this
approach are: approach are:
- mermaid.startOnLoad - mermaid.startOnLoad

View File

@@ -14,7 +14,7 @@ It is a JavaScript based diagramming and charting tool that renders Markdown-ins
<img src="/header.png" alt="" /> <img src="/header.png" alt="" />
[![Build CI Status](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml/badge.svg)](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml) [![NPM](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid) [![Coverage Status](https://coveralls.io/repos/github/mermaid-js/mermaid/badge.svg?branch=master)](https://coveralls.io/github/mermaid-js/mermaid?branch=master) [![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid) [![NPM](https://img.shields.io/npm/dm/mermaid)](https://www.npmjs.com/package/mermaid) [![Join our Slack!](https://img.shields.io/static/v1?message=join%20chat&color=9cf&logo=slack&label=slack)](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE) [![Twitter Follow](https://img.shields.io/twitter/follow/mermaidjs_?style=social)](https://twitter.com/mermaidjs_) [![Build CI Status](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml/badge.svg)](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml) [![NPM](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid) [![npm minified gzipped bundle size](https://img.shields.io/bundlephobia/minzip/mermaid)](https://bundlephobia.com/package/mermaid) [![Coverage Status](https://coveralls.io/repos/github/mermaid-js/mermaid/badge.svg?branch=master)](https://coveralls.io/github/mermaid-js/mermaid?branch=master) [![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid) [![NPM](https://img.shields.io/npm/dm/mermaid)](https://www.npmjs.com/package/mermaid) [![Join our Slack!](https://img.shields.io/static/v1?message=join%20chat&color=9cf&logo=slack&label=slack)](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE) [![Twitter Follow](https://img.shields.io/twitter/follow/mermaidjs_?style=social)](https://twitter.com/mermaidjs_)
<!-- Mermaid book banner --> <!-- Mermaid book banner -->

View File

@@ -39,6 +39,7 @@ They also serve as proof of concept, for the variety of things that can be built
- [markdown-for-mermaid-plugin](https://github.com/jamieh-mongolian/markdown-for-mermaid-plugin) - [markdown-for-mermaid-plugin](https://github.com/jamieh-mongolian/markdown-for-mermaid-plugin)
- [JetBrains IDE eg Pycharm](https://www.jetbrains.com/go/guide/tips/mermaid-js-support-in-markdown/) - [JetBrains IDE eg Pycharm](https://www.jetbrains.com/go/guide/tips/mermaid-js-support-in-markdown/)
- [mermerd](https://github.com/KarnerTh/mermerd) - [mermerd](https://github.com/KarnerTh/mermerd)
- Visual Studio Code [Polyglot Interactive Notebooks](https://github.com/dotnet/interactive#net-interactive)
## CRM/ERP/Similar ## CRM/ERP/Similar
@@ -121,6 +122,7 @@ They also serve as proof of concept, for the variety of things that can be built
- [Draw.io](https://draw.io) - [Plugin](https://github.com/nopeslide/drawio_mermaid_plugin) - [Draw.io](https://draw.io) - [Plugin](https://github.com/nopeslide/drawio_mermaid_plugin)
- [Inkdrop](https://www.inkdrop.app) - [Plugin](https://github.com/inkdropapp/inkdrop-mermaid) - [Inkdrop](https://www.inkdrop.app) - [Plugin](https://github.com/inkdropapp/inkdrop-mermaid)
- [Vim](https://www.vim.org) - [Vim](https://www.vim.org)
- [Official Vim Syntax and ftplugin](https://github.com/craigmac/vim-mermaid)
- [Vim Diagram Syntax](https://github.com/zhaozg/vim-diagram) - [Vim Diagram Syntax](https://github.com/zhaozg/vim-diagram)
- [GNU Emacs](https://www.gnu.org/software/emacs/) - [GNU Emacs](https://www.gnu.org/software/emacs/)
- [Major mode for .mmd files](https://github.com/abrochard/mermaid-mode) - [Major mode for .mmd files](https://github.com/abrochard/mermaid-mode)

View File

@@ -567,7 +567,7 @@ UpdateRelStyle(customerA, bankA, $offsetY="60")
Container(mobile, "Mobile App", "Xamarin", "Provides a limited subset of the Internet Banking functionality to customers via their mobile device.") Container(mobile, "Mobile App", "Xamarin", "Provides a limited subset of the Internet Banking functionality to customers via their mobile device.")
} }
Deployment_Node(comp, "Customer's computer", "Mircosoft Windows or Apple macOS"){ Deployment_Node(comp, "Customer's computer", "Microsoft Windows or Apple macOS"){
Deployment_Node(browser, "Web Browser", "Google Chrome, Mozilla Firefox,<br/> Apple Safari or Microsoft Edge"){ Deployment_Node(browser, "Web Browser", "Google Chrome, Mozilla Firefox,<br/> Apple Safari or Microsoft Edge"){
Container(spa, "Single Page Application", "JavaScript and Angular", "Provides all of the Internet Banking functionality to customers via their web browser.") Container(spa, "Single Page Application", "JavaScript and Angular", "Provides all of the Internet Banking functionality to customers via their web browser.")
} }
@@ -619,7 +619,7 @@ UpdateRelStyle(customerA, bankA, $offsetY="60")
Container(mobile, "Mobile App", "Xamarin", "Provides a limited subset of the Internet Banking functionality to customers via their mobile device.") Container(mobile, "Mobile App", "Xamarin", "Provides a limited subset of the Internet Banking functionality to customers via their mobile device.")
} }
Deployment_Node(comp, "Customer's computer", "Mircosoft Windows or Apple macOS"){ Deployment_Node(comp, "Customer's computer", "Microsoft Windows or Apple macOS"){
Deployment_Node(browser, "Web Browser", "Google Chrome, Mozilla Firefox,<br/> Apple Safari or Microsoft Edge"){ Deployment_Node(browser, "Web Browser", "Google Chrome, Mozilla Firefox,<br/> Apple Safari or Microsoft Edge"){
Container(spa, "Single Page Application", "JavaScript and Angular", "Provides all of the Internet Banking functionality to customers via their web browser.") Container(spa, "Single Page Application", "JavaScript and Angular", "Provides all of the Internet Banking functionality to customers via their web browser.")
} }

View File

@@ -14,6 +14,9 @@ The class diagram is the main building block of object-oriented modeling. It is
Mermaid can render class diagrams. Mermaid can render class diagrams.
```mermaid-example ```mermaid-example
---
title: Animal example
---
classDiagram classDiagram
note "From Duck till Zebra" note "From Duck till Zebra"
Animal <|-- Duck Animal <|-- Duck
@@ -40,6 +43,9 @@ classDiagram
``` ```
```mermaid ```mermaid
---
title: Animal example
---
classDiagram classDiagram
note "From Duck till Zebra" note "From Duck till Zebra"
Animal <|-- Duck Animal <|-- Duck
@@ -77,6 +83,9 @@ A single instance of a class in the diagram contains three compartments:
- The bottom compartment contains the operations the class can execute. They are also left-aligned and the first letter is lowercase. - The bottom compartment contains the operations the class can execute. They are also left-aligned and the first letter is lowercase.
```mermaid-example ```mermaid-example
---
title: Bank example
---
classDiagram classDiagram
class BankAccount class BankAccount
BankAccount : +String owner BankAccount : +String owner
@@ -87,6 +96,9 @@ classDiagram
``` ```
```mermaid ```mermaid
---
title: Bank example
---
classDiagram classDiagram
class BankAccount class BankAccount
BankAccount : +String owner BankAccount : +String owner
@@ -559,7 +571,7 @@ You would define these actions on a separate line after all classes have been de
## Notes ## Notes
It is possible to add notes on digram using `note "line1\nline2"` or note for class using `note for class "line1\nline2"` It is possible to add notes on diagram using `note "line1\nline2"` or note for class using `note for class "line1\nline2"`
### Examples ### Examples

View File

@@ -13,6 +13,9 @@ Note that practitioners of ER modelling almost always refer to _entity types_ si
Mermaid can render ER diagrams Mermaid can render ER diagrams
```mermaid-example ```mermaid-example
---
title: Order example
---
erDiagram erDiagram
CUSTOMER ||--o{ ORDER : places CUSTOMER ||--o{ ORDER : places
ORDER ||--|{ LINE-ITEM : contains ORDER ||--|{ LINE-ITEM : contains
@@ -20,6 +23,9 @@ erDiagram
``` ```
```mermaid ```mermaid
---
title: Order example
---
erDiagram erDiagram
CUSTOMER ||--o{ ORDER : places CUSTOMER ||--o{ ORDER : places
ORDER ||--|{ LINE-ITEM : contains ORDER ||--|{ LINE-ITEM : contains

View File

@@ -15,11 +15,17 @@ It can also accommodate different arrow types, multi directional arrows, and lin
### A node (default) ### A node (default)
```mermaid-example ```mermaid-example
---
title: Node
---
flowchart LR flowchart LR
id id
``` ```
```mermaid ```mermaid
---
title: Node
---
flowchart LR flowchart LR
id id
``` ```
@@ -33,11 +39,17 @@ found for the node that will be used. Also if you define edges for the node late
one previously defined will be used when rendering the box. one previously defined will be used when rendering the box.
```mermaid-example ```mermaid-example
---
title: Node with text
---
flowchart LR flowchart LR
id1[This is the text in the box] id1[This is the text in the box]
``` ```
```mermaid ```mermaid
---
title: Node with text
---
flowchart LR flowchart LR
id1[This is the text in the box] id1[This is the text in the box]
``` ```
@@ -980,7 +992,7 @@ flowchart LR
## Configuration... ## Configuration...
Is it possible to adjust the width of the rendered flowchart. It is possible to adjust the width of the rendered flowchart.
This is done by defining **mermaid.flowchartConfig** or by the CLI to use a JSON file with the configuration. How to use the CLI is described in the mermaidCLI page. This is done by defining **mermaid.flowchartConfig** or by the CLI to use a JSON file with the configuration. How to use the CLI is described in the mermaidCLI page.
mermaid.flowchartConfig can be set to a JSON string with config parameters or the corresponding object. mermaid.flowchartConfig can be set to a JSON string with config parameters or the corresponding object.

View File

@@ -13,31 +13,37 @@ These kind of diagram are particularly helpful to developers and devops teams to
Mermaid can render Git diagrams Mermaid can render Git diagrams
```mermaid-example ```mermaid-example
gitGraph ---
commit title: Example Git diagram
commit ---
branch develop gitGraph
checkout develop commit
commit commit
commit branch develop
checkout main checkout develop
merge develop commit
commit commit
commit checkout main
merge develop
commit
commit
``` ```
```mermaid ```mermaid
gitGraph ---
commit title: Example Git diagram
commit ---
branch develop gitGraph
checkout develop commit
commit commit
commit branch develop
checkout main checkout develop
merge develop commit
commit commit
commit checkout main
merge develop
commit
commit
``` ```
In Mermaid, we support the basic git operations like: In Mermaid, we support the basic git operations like:

View File

@@ -21,7 +21,7 @@ mindmap
Popularisation Popularisation
British popular psychology author Tony Buzan British popular psychology author Tony Buzan
Research Research
On effectivness<br/>and eatures On effectiveness<br/>and features
On Automatic creation On Automatic creation
Uses Uses
Creative techniques Creative techniques
@@ -42,7 +42,7 @@ mindmap
Popularisation Popularisation
British popular psychology author Tony Buzan British popular psychology author Tony Buzan
Research Research
On effectivness<br/>and eatures On effectiveness<br/>and features
On Automatic creation On Automatic creation
Uses Uses
Creative techniques Creative techniques
@@ -152,6 +152,18 @@ mindmap
id)I am a cloud( id)I am a cloud(
``` ```
### Hexagon
```mermaid-example
mindmap
id{{I am a hexagon}}
```
```mermaid
mindmap
id{{I am a hexagon}}
```
### Default ### Default
```mermaid-example ```mermaid-example

View File

@@ -35,7 +35,7 @@ Drawing a pie chart is really simple in mermaid.
- Followed by dataSet. Pie slices will be ordered clockwise in the same order as the labels. - Followed by dataSet. Pie slices will be ordered clockwise in the same order as the labels.
- `label` for a section in the pie diagram within `" "` quotes. - `label` for a section in the pie diagram within `" "` quotes.
- Followed by `:` colon as separator - Followed by `:` colon as separator
- Followed by `positive numeric value` (supported upto two decimal places) - Followed by `positive numeric value` (supported up to two decimal places)
\[pie] \[showData] (OPTIONAL) \[pie] \[showData] (OPTIONAL)
\[title] \[titlevalue] (OPTIONAL) \[title] \[titlevalue] (OPTIONAL)

View File

@@ -727,7 +727,7 @@ text.actor {
## Configuration ## Configuration
Is it possible to adjust the margins for rendering the sequence diagram. It is possible to adjust the margins for rendering the sequence diagram.
This is done by defining `mermaid.sequenceConfig` or by the CLI to use a json file with the configuration. This is done by defining `mermaid.sequenceConfig` or by the CLI to use a json file with the configuration.
How to use the CLI is described in the [mermaidCLI](../config/mermaidCLI.md) page. How to use the CLI is described in the [mermaidCLI](../config/mermaidCLI.md) page.

View File

@@ -6,11 +6,17 @@
# State diagrams # State diagrams
> "A state diagram is a type of diagram used in computer science and related fields to describe the behavior of systems. State diagrams require that the system described is composed of a finite number of states; sometimes, this is indeed the case, while at other times this is a reasonable abstraction." Wikipedia > "A state diagram is a type of diagram used in computer science and related fields to describe the behavior of systems.
> State diagrams require that the system described is composed of a finite number of states; sometimes, this is indeed the
> case, while at other times this is a reasonable abstraction." Wikipedia
Mermaid can render state diagrams. The syntax tries to be compliant with the syntax used in plantUml as this will make it easier for users to share diagrams between mermaid and plantUml. Mermaid can render state diagrams. The syntax tries to be compliant with the syntax used in plantUml as this will make
it easier for users to share diagrams between mermaid and plantUml.
```mermaid-example ```mermaid-example
---
title: Simple sample
---
stateDiagram-v2 stateDiagram-v2
[*] --> Still [*] --> Still
Still --> [*] Still --> [*]
@@ -22,6 +28,9 @@ stateDiagram-v2
``` ```
```mermaid ```mermaid
---
title: Simple sample
---
stateDiagram-v2 stateDiagram-v2
[*] --> Still [*] --> Still
Still --> [*] Still --> [*]
@@ -56,20 +65,23 @@ stateDiagram
Crash --> [*] Crash --> [*]
``` ```
In state diagrams systems are described in terms of its states and how the systems state can change to another state via a transitions. The example diagram above shows three states **Still**, **Moving** and **Crash**. You start in the state of Still. From Still you can change the state to Moving. In Moving you can change the state either back to Still or to Crash. There is no transition from Still to Crash. In state diagrams systems are described in terms of _states_ and how one _state_ can change to another _state_ via
a _transition._ The example diagram above shows three states: **Still**, **Moving** and **Crash**. You start in the
**Still** state. From **Still** you can change to the **Moving** state. From **Moving** you can change either back to the **Still** state or to
the **Crash** state. There is no transition from **Still** to **Crash**. (You can't crash if you're still.)
## States ## States
A state can be declared in multiple ways. The simplest way is to define a state id as a description. A state can be declared in multiple ways. The simplest way is to define a state with just an id:
```mermaid-example ```mermaid-example
stateDiagram-v2 stateDiagram-v2
s1 stateId
``` ```
```mermaid ```mermaid
stateDiagram-v2 stateDiagram-v2
s1 stateId
``` ```
Another way is by using the state keyword with a description as per below: Another way is by using the state keyword with a description as per below:
@@ -100,7 +112,8 @@ stateDiagram-v2
Transitions are path/edges when one state passes into another. This is represented using text arrow, "-->". Transitions are path/edges when one state passes into another. This is represented using text arrow, "-->".
When you define a transition between two states and the states are not already defined the undefined states are defined with the id from the transition. You can later add descriptions to states defined this way. When you define a transition between two states and the states are not already defined, the undefined states are defined
with the id from the transition. You can later add descriptions to states defined this way.
```mermaid-example ```mermaid-example
stateDiagram-v2 stateDiagram-v2
@@ -112,7 +125,7 @@ stateDiagram-v2
s1 --> s2 s1 --> s2
``` ```
It is possible to add text to a transition. To describe what it represents. It is possible to add text to a transition to describe what it represents:
```mermaid-example ```mermaid-example
stateDiagram-v2 stateDiagram-v2
@@ -126,7 +139,8 @@ stateDiagram-v2
## Start and End ## Start and End
There are two special states indicating the start and stop of the diagram. These are written with the \[\*] syntax and the direction of the transition to it defines it either as a start or a stop state. There are two special states indicating the start and stop of the diagram. These are written with the \[\*] syntax and
the direction of the transition to it defines it either as a start or a stop state.
```mermaid-example ```mermaid-example
stateDiagram-v2 stateDiagram-v2
@@ -142,10 +156,11 @@ stateDiagram-v2
## Composite states ## Composite states
In a real world use of state diagrams you often end up with diagrams that are multi-dimensional as one state can In a real world use of state diagrams you often end up with diagrams that are multidimensional as one state can
have several internal states. These are called composite states in this terminology. have several internal states. These are called composite states in this terminology.
In order to define a composite state you need to use the state keyword followed by an id and the body of the composite state between {}. See the example below: In order to define a composite state you need to use the state keyword followed by an id and the body of the composite
state between {}. See the example below:
```mermaid-example ```mermaid-example
stateDiagram-v2 stateDiagram-v2
@@ -305,7 +320,7 @@ It is possible to specify a fork in the diagram using <\<fork>> <\<join>>.
## Notes ## Notes
Sometimes nothing says it better then a Post-it note. That is also the case in state diagrams. Sometimes nothing says it better than a Post-it note. That is also the case in state diagrams.
Here you can choose to put the note to the _right of_ or to the _left of_ a node. Here you can choose to put the note to the _right of_ or to the _left of_ a node.
@@ -375,7 +390,8 @@ stateDiagram-v2
## Setting the direction of the diagram ## Setting the direction of the diagram
With state diagrams you can use the direction statement to set the direction which the diagram will render like in this example. With state diagrams you can use the direction statement to set the direction which the diagram will render like in this
example.
```mermaid-example ```mermaid-example
stateDiagram stateDiagram
@@ -405,7 +421,9 @@ stateDiagram
## Comments ## Comments
Comments can be entered within a state diagram chart, which will be ignored by the parser. Comments need to be on their own line, and must be prefaced with `%%` (double percent signs). Any text after the start of the comment to the next newline will be treated as a comment, including any diagram syntax Comments can be entered within a state diagram chart, which will be ignored by the parser. Comments need to be on their
own line, and must be prefaced with `%%` (double percent signs). Any text after the start of the comment to the next
newline will be treated as a comment, including any diagram syntax
```mermaid-example ```mermaid-example
stateDiagram-v2 stateDiagram-v2
@@ -429,22 +447,204 @@ stateDiagram-v2
Crash --> [*] Crash --> [*]
``` ```
## Styling ## Styling with classDefs
Styling of the a state diagram is done by defining a number of css classes. During rendering these classes are extracted from the file located at src/themes/state.scss As with other diagrams (like flowcharts), you can define a style in the diagram itself and apply that named style to a
state or states in the diagram.
**These are the current limitations with state diagram classDefs:**
1. Cannot be applied to start or end states
2. Cannot be applied to or within composite states
_These are in development and will be available in a future version._
You define a style using the `classDef` keyword, which is short for "class definition" (where "class" means something
like a _CSS class_)
followed by _a name for the style,_
and then one or more _property-value pairs_. Each _property-value pair_ is
a _[valid CSS property name](https://www.w3.org/TR/CSS/#properties)_ followed by a colon (`:`) and then a _value._
Here is an example of a classDef with just one property-value pair:
classDef movement font-style:italic;
where
- the _name_ of the style is `movement`
- the only _property_ is `font-style` and its _value_ is `italic`
If you want to have more than one _property-value pair_ then you put a comma (`,`) between each _property-value pair._
Here is an example with three property-value pairs:
classDef badBadEvent fill:#f00,color:white,font-weight:bold,stroke-width:2px,stroke:yellow
where
- the _name_ of the style is `badBadEvent`
- the first _property_ is `fill` and its _value_ is `#f00`
- the second _property_ is `color` and its _value_ is `white`
- the third _property_ is `font-weight` and its _value_ is `bold`
- the fourth _property_ is `stroke-width` and its _value_ is `2px`
- the fifth _property_ is `stroke` and its _value_ is `yello`
### Apply classDef styles to states
There are two ways to apply a `classDef` style to a state:
1. use the `class` keyword to apply a classDef style to one or more states in a single statement, or
2. use the `:::` operator to apply a classDef style to a state as it is being used in a transition statement (e.g. with an arrow
to/from another state)
#### 1. `class` statement
A `class` statement tells Mermaid to apply the named classDef to one or more classes. The form is:
```text
class [one or more state names, separated by commas] [name of a style defined with classDef]
```
Here is an example applying the `badBadEvent` style to a state named `Crash`:
```text
class Crash badBadEvent
```
Here is an example applying the `movement` style to the two states `Moving` and `Crash`:
```text
class Moving, Crash movement
```
Here is a diagram that shows the examples in use. Note that the `Crash` state has two classDef styles applied: `movement`
and `badBadEvent`
```mermaid-example
stateDiagram
direction TB
accTitle: This is the accessible title
accDescr: This is an accessible description
classDef notMoving fill:white
classDef movement font-style:italic
classDef badBadEvent fill:#f00,color:white,font-weight:bold,stroke-width:2px,stroke:yellow
[*]--> Still
Still --> [*]
Still --> Moving
Moving --> Still
Moving --> Crash
Crash --> [*]
class Still notMoving
class Moving, Crash movement
class Crash badBadEvent
class end badBadEvent
```
```mermaid
stateDiagram
direction TB
accTitle: This is the accessible title
accDescr: This is an accessible description
classDef notMoving fill:white
classDef movement font-style:italic
classDef badBadEvent fill:#f00,color:white,font-weight:bold,stroke-width:2px,stroke:yellow
[*]--> Still
Still --> [*]
Still --> Moving
Moving --> Still
Moving --> Crash
Crash --> [*]
class Still notMoving
class Moving, Crash movement
class Crash badBadEvent
class end badBadEvent
```
#### 2. `:::` operator to apply a style to a state
You can apply a classDef style to a state using the `:::` (three colons) operator. The syntax is
```text
[state]:::[style name]
```
You can use this in a diagram within a statement using a class. This includes the start and end states. For example:
```mermaid-example
stateDiagram
direction TB
accTitle: This is the accessible title
accDescr: This is an accessible description
classDef notMoving fill:white
classDef movement font-style:italic;
classDef badBadEvent fill:#f00,color:white,font-weight:bold,stroke-width:2px,stroke:yellow
[*] --> Still:::notMoving
Still --> [*]
Still --> Moving:::movement
Moving --> Still
Moving --> Crash:::movement
Crash:::badBadEvent --> [*]
```
```mermaid
stateDiagram
direction TB
accTitle: This is the accessible title
accDescr: This is an accessible description
classDef notMoving fill:white
classDef movement font-style:italic;
classDef badBadEvent fill:#f00,color:white,font-weight:bold,stroke-width:2px,stroke:yellow
[*] --> Still:::notMoving
Still --> [*]
Still --> Moving:::movement
Moving --> Still
Moving --> Crash:::movement
Crash:::badBadEvent --> [*]
```
## Spaces in state names ## Spaces in state names
Spaces can be added to a state by defining it at the top and referencing the acronym later. Spaces can be added to a state by first defining the state with an id and then referencing the id later.
In the following example there is a state with the id **yswsii** and description **Your state with spaces in it**.
After it has been defined, **yswsii** is used in the diagram in the first transition (`[*] --> yswsii`)
and also in the transition to **YetAnotherState** (`yswsii --> YetAnotherState`).\
(**yswsii** has been styled so that it is different from the other states.)
```mermaid-example ```mermaid-example
stateDiagram-v2 stateDiagram
Yswsii: Your state with spaces in it classDef yourState font-style:italic,font-weight:bold,fill:white
[*] --> Yswsii
yswsii: Your state with spaces in it
[*] --> yswsii:::yourState
[*] --> SomeOtherState
SomeOtherState --> YetAnotherState
yswsii --> YetAnotherState
YetAnotherState --> [*]
``` ```
```mermaid ```mermaid
stateDiagram-v2 stateDiagram
Yswsii: Your state with spaces in it classDef yourState font-style:italic,font-weight:bold,fill:white
[*] --> Yswsii
yswsii: Your state with spaces in it
[*] --> yswsii:::yourState
[*] --> SomeOtherState
SomeOtherState --> YetAnotherState
yswsii --> YetAnotherState
YetAnotherState --> [*]
``` ```

View File

@@ -4,7 +4,7 @@
"version": "9.2.2", "version": "9.2.2",
"description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.", "description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.",
"type": "module", "type": "module",
"packageManager": "pnpm@7.15.0", "packageManager": "pnpm@7.17.0",
"keywords": [ "keywords": [
"diagram", "diagram",
"markdown", "markdown",
@@ -15,8 +15,9 @@
"git graph" "git graph"
], ],
"scripts": { "scripts": {
"build:mermaid": "ts-node-esm --transpileOnly .vite/build.ts --mermaid",
"build:vite": "ts-node-esm --transpileOnly .vite/build.ts", "build:vite": "ts-node-esm --transpileOnly .vite/build.ts",
"build:mermaid": "pnpm build:vite --mermaid",
"build:viz": "pnpm build:mermaid --visualize",
"build:types": "tsc -p ./packages/mermaid/tsconfig.json --emitDeclarationOnly && tsc -p ./packages/mermaid-mindmap/tsconfig.json --emitDeclarationOnly", "build:types": "tsc -p ./packages/mermaid/tsconfig.json --emitDeclarationOnly && tsc -p ./packages/mermaid-mindmap/tsconfig.json --emitDeclarationOnly",
"build:watch": "pnpm build:vite --watch", "build:watch": "pnpm build:vite --watch",
"build": "pnpm run -r clean && concurrently \"pnpm build:vite\" \"pnpm build:types\"", "build": "pnpm run -r clean && concurrently \"pnpm build:vite\" \"pnpm build:types\"",
@@ -59,11 +60,13 @@
"@cspell/eslint-plugin": "^6.14.2", "@cspell/eslint-plugin": "^6.14.2",
"@types/eslint": "^8.4.10", "@types/eslint": "^8.4.10",
"@types/express": "^4.17.14", "@types/express": "^4.17.14",
"@types/js-yaml": "^4.0.5",
"@types/jsdom": "^20.0.1", "@types/jsdom": "^20.0.1",
"@types/lodash": "^4.14.188", "@types/lodash": "^4.14.188",
"@types/mdast": "^3.0.10", "@types/mdast": "^3.0.10",
"@types/node": "^18.11.9", "@types/node": "^18.11.9",
"@types/prettier": "^2.7.1", "@types/prettier": "^2.7.1",
"@types/rollup-plugin-visualizer": "^4.2.1",
"@typescript-eslint/eslint-plugin": "^5.42.1", "@typescript-eslint/eslint-plugin": "^5.42.1",
"@typescript-eslint/parser": "^5.42.1", "@typescript-eslint/parser": "^5.42.1",
"@vitest/coverage-c8": "^0.25.1", "@vitest/coverage-c8": "^0.25.1",
@@ -80,15 +83,18 @@
"eslint-plugin-jest": "^27.1.5", "eslint-plugin-jest": "^27.1.5",
"eslint-plugin-jsdoc": "^39.6.2", "eslint-plugin-jsdoc": "^39.6.2",
"eslint-plugin-json": "^3.1.0", "eslint-plugin-json": "^3.1.0",
"eslint-plugin-lodash": "^7.4.0",
"eslint-plugin-markdown": "^3.0.0", "eslint-plugin-markdown": "^3.0.0",
"eslint-plugin-no-only-tests": "^3.1.0", "eslint-plugin-no-only-tests": "^3.1.0",
"eslint-plugin-tsdoc": "^0.2.17", "eslint-plugin-tsdoc": "^0.2.17",
"eslint-plugin-unicorn": "^45.0.0",
"express": "^4.18.2", "express": "^4.18.2",
"globby": "^13.1.2", "globby": "^13.1.2",
"husky": "^8.0.2", "husky": "^8.0.2",
"identity-obj-proxy": "^3.0.0", "identity-obj-proxy": "^3.0.0",
"jest": "^29.3.1", "jest": "^29.3.1",
"jison": "^0.4.18", "jison": "^0.4.18",
"js-yaml": "^4.1.0",
"jsdom": "^20.0.2", "jsdom": "^20.0.2",
"lint-staged": "^13.0.3", "lint-staged": "^13.0.3",
"path-browserify": "^1.0.1", "path-browserify": "^1.0.1",
@@ -96,6 +102,7 @@
"prettier": "^2.7.1", "prettier": "^2.7.1",
"prettier-plugin-jsdoc": "^0.4.2", "prettier-plugin-jsdoc": "^0.4.2",
"rimraf": "^3.0.2", "rimraf": "^3.0.2",
"rollup-plugin-visualizer": "^5.8.3",
"start-server-and-test": "^1.14.0", "start-server-and-test": "^1.14.0",
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"typescript": "^4.8.4", "typescript": "^4.8.4",
@@ -103,15 +110,8 @@
"vitepress": "^1.0.0-alpha.28", "vitepress": "^1.0.0-alpha.28",
"vitepress-plugin-mermaid": "^2.0.8", "vitepress-plugin-mermaid": "^2.0.8",
"vitepress-plugin-search": "^1.0.4-alpha.15", "vitepress-plugin-search": "^1.0.4-alpha.15",
"vitest": "^0.25.1" "vitest": "^0.25.3"
}, },
"resolutions": {
"d3": "^7.6.1"
},
"sideEffects": [
"**/*.css",
"**/*.scss"
],
"volta": { "volta": {
"node": "18.12.1" "node": "18.12.1"
} }

View File

@@ -172,6 +172,18 @@ root
expect(mm.children.length).toEqual(0); expect(mm.children.length).toEqual(0);
expect(mm.type).toEqual(mindmap.yy.nodeType.BANG); expect(mm.type).toEqual(mindmap.yy.nodeType.BANG);
}); });
it('MMP-12-a mutiple types (hexagon)', function () {
let str = `mindmap
root{{the root}}
`;
mindmap.parse(str);
const mm = mindmap.yy.getMindmap();
expect(mm.type).toEqual(mindmap.yy.nodeType.HEXAGON);
expect(mm.descr).toEqual('the root');
expect(mm.children.length).toEqual(0);
});
}); });
describe('decorations', function () { describe('decorations', function () {
it('MMP-13 should be possible to set an icon for the node', function () { it('MMP-13 should be possible to set an icon for the node', function () {

View File

@@ -42,6 +42,9 @@ export const addNode = (level, id, descr, type) => {
case nodeType.RECT: case nodeType.RECT:
node.padding = 2 * conf.mindmap.padding; node.padding = 2 * conf.mindmap.padding;
break; break;
case nodeType.HEXAGON:
node.padding = 2 * conf.mindmap.padding;
break;
default: default:
node.padding = conf.mindmap.padding; node.padding = conf.mindmap.padding;
} }
@@ -79,6 +82,7 @@ export const nodeType = {
CIRCLE: 3, CIRCLE: 3,
CLOUD: 4, CLOUD: 4,
BANG: 5, BANG: 5,
HEXAGON: 6,
}; };
export const getType = (startStr, endStr) => { export const getType = (startStr, endStr) => {
@@ -94,6 +98,8 @@ export const getType = (startStr, endStr) => {
return nodeType.CLOUD; return nodeType.CLOUD;
case '))': case '))':
return nodeType.BANG; return nodeType.BANG;
case '{{':
return nodeType.HEXAGON;
default: default:
return nodeType.DEFAULT; return nodeType.DEFAULT;
} }
@@ -127,6 +133,8 @@ export const type2Str = (type) => {
return 'cloud'; return 'cloud';
case nodeType.BANG: case nodeType.BANG:
return 'bang'; return 'bang';
case nodeType.HEXAGON:
return 'hexgon';
default: default:
return 'no-border'; return 'no-border';
} }

View File

@@ -92,10 +92,6 @@ function addNodes(mindmap, cy, conf, level) {
*/ */
function layoutMindmap(node, conf) { function layoutMindmap(node, conf) {
return new Promise((resolve) => { return new Promise((resolve) => {
if (node.children.length === 0) {
return node;
}
// Add temporary render element // Add temporary render element
const renderEl = select('body').append('div').attr('id', 'cy').attr('style', 'display:none'); const renderEl = select('body').append('div').attr('id', 'cy').attr('style', 'display:none');
const cy = cytoscape({ const cy = cytoscape({

View File

@@ -33,11 +33,12 @@
"))" { yy.getLogger().trace('Explosion Bang'); this.begin('NODE');return 'NODE_DSTART'; } "))" { yy.getLogger().trace('Explosion Bang'); this.begin('NODE');return 'NODE_DSTART'; }
")" { yy.getLogger().trace('Cloud Bang'); this.begin('NODE');return 'NODE_DSTART'; } ")" { yy.getLogger().trace('Cloud Bang'); this.begin('NODE');return 'NODE_DSTART'; }
"((" { this.begin('NODE');return 'NODE_DSTART'; } "((" { this.begin('NODE');return 'NODE_DSTART'; }
"{{" { this.begin('NODE');return 'NODE_DSTART'; }
"(" { this.begin('NODE');return 'NODE_DSTART'; } "(" { this.begin('NODE');return 'NODE_DSTART'; }
"[" { this.begin('NODE');return 'NODE_DSTART'; } "[" { this.begin('NODE');return 'NODE_DSTART'; }
[\s]+ return 'SPACELIST' /* skip all whitespace */ ; [\s]+ return 'SPACELIST' /* skip all whitespace */ ;
// !(-\() return 'NODE_ID'; // !(-\() return 'NODE_ID';
[^\(\[\n\-\)]+ return 'NODE_ID'; [^\(\[\n\-\)\{\}]+ return 'NODE_ID';
<<EOF>> return 'EOF'; <<EOF>> return 'EOF';
<NODE>["] { yy.getLogger().trace('Starting NSTR');this.begin("NSTR");} <NODE>["] { yy.getLogger().trace('Starting NSTR');this.begin("NSTR");}
<NSTR>[^"]+ { yy.getLogger().trace('description:', yytext); return "NODE_DESCR";} <NSTR>[^"]+ { yy.getLogger().trace('description:', yytext); return "NODE_DESCR";}
@@ -45,11 +46,12 @@
<NODE>[\)]\) {this.popState();yy.getLogger().trace('node end ))');return "NODE_DEND";} <NODE>[\)]\) {this.popState();yy.getLogger().trace('node end ))');return "NODE_DEND";}
<NODE>[\)] {this.popState();yy.getLogger().trace('node end )');return "NODE_DEND";} <NODE>[\)] {this.popState();yy.getLogger().trace('node end )');return "NODE_DEND";}
<NODE>[\]] {this.popState();yy.getLogger().trace('node end ...',yytext);return "NODE_DEND";} <NODE>[\]] {this.popState();yy.getLogger().trace('node end ...',yytext);return "NODE_DEND";}
<NODE>"}}" {this.popState();yy.getLogger().trace('node end ((');return "NODE_DEND";}
<NODE>"(-" {this.popState();yy.getLogger().trace('node end (-');return "NODE_DEND";} <NODE>"(-" {this.popState();yy.getLogger().trace('node end (-');return "NODE_DEND";}
<NODE>"-)" {this.popState();yy.getLogger().trace('node end (-');return "NODE_DEND";} <NODE>"-)" {this.popState();yy.getLogger().trace('node end (-');return "NODE_DEND";}
<NODE>"((" {this.popState();yy.getLogger().trace('node end ((');return "NODE_DEND";} <NODE>"((" {this.popState();yy.getLogger().trace('node end ((');return "NODE_DEND";}
<NODE>"(" {this.popState();yy.getLogger().trace('node end ((');return "NODE_DEND";} <NODE>"(" {this.popState();yy.getLogger().trace('node end ((');return "NODE_DEND";}
<NODE>[^\)\]\(]+ { yy.getLogger().trace('Long description:', yytext); return 'NODE_DESCR';} <NODE>[^\)\]\(\}]+ { yy.getLogger().trace('Long description:', yytext); return 'NODE_DESCR';}
<NODE>.+(?!\(\() { yy.getLogger().trace('Long description:', yytext); return 'NODE_DESCR';} <NODE>.+(?!\(\() { yy.getLogger().trace('Long description:', yytext); return 'NODE_DESCR';}
// [\[] return 'NODE_START'; // [\[] return 'NODE_START';
// .+ return 'TXT' ; // .+ return 'TXT' ;

View File

@@ -17,7 +17,7 @@ const genSections = (options) => {
sections += ` sections += `
.section-${i - 1} rect, .section-${i - 1} path, .section-${i - 1} circle, .section-${ .section-${i - 1} rect, .section-${i - 1} path, .section-${i - 1} circle, .section-${
i - 1 i - 1
} path { } polygon, .section-${i - 1} path {
fill: ${options['cScale' + i]}; fill: ${options['cScale' + i]};
} }
.section-${i - 1} text { .section-${i - 1} text {
@@ -55,7 +55,7 @@ const getStyles = (options) =>
stroke-width: 3; stroke-width: 3;
} }
${genSections(options)} ${genSections(options)}
.section-root rect, .section-root path, .section-root circle { .section-root rect, .section-root path, .section-root circle, .section-root polygon {
fill: ${options.git0}; fill: ${options.git0};
} }
.section-root text { .section-root text {

View File

@@ -145,6 +145,45 @@ const circleBkg = function (elem, node) {
.attr('class', 'node-bkg node-' + db.type2Str(node.type)) .attr('class', 'node-bkg node-' + db.type2Str(node.type))
.attr('r', node.width / 2); .attr('r', node.width / 2);
}; };
/**
*
* @param parent
* @param w
* @param h
* @param points
* @param node
*/
function insertPolygonShape(parent, w, h, points, node) {
return parent
.insert('polygon', ':first-child')
.attr(
'points',
points
.map(function (d) {
return d.x + ',' + d.y;
})
.join(' ')
)
.attr('transform', 'translate(' + (node.width - w) / 2 + ', ' + h + ')');
}
const hexagonBkg = function (elem, node) {
const h = node.height;
const f = 4;
const m = h / f;
const w = node.width - node.padding + 2 * m;
const points = [
{ x: m, y: 0 },
{ x: w - m, y: 0 },
{ x: w, y: -h / 2 },
{ x: w - m, y: -h },
{ x: m, y: -h },
{ x: 0, y: -h / 2 },
];
const shapeSvg = insertPolygonShape(elem, w, h, points, node);
};
const roundedRectBkg = function (elem, node) { const roundedRectBkg = function (elem, node) {
elem elem
.append('rect') .append('rect')
@@ -252,6 +291,9 @@ export const drawNode = function (elem, node, fullSection, conf) {
case db.nodeType.BANG: case db.nodeType.BANG:
bangBkg(bkgElem, node, section, conf); bangBkg(bkgElem, node, section, conf);
break; break;
case db.nodeType.HEXAGON:
hexagonBkg(bkgElem, node, section, conf);
break;
} }
// Position the node to its coordinate // Position the node to its coordinate

View File

@@ -1,6 +0,0 @@
{
"src/docs/**": ["pnpm --filter mermaid run docs:build --git"],
"src/docs.mts": ["pnpm --filter mermaid run docs:build --git"],
"src/(defaultConfig|config|mermaidAPI).ts": ["pnpm --filter mermaid run docs:build --git"],
"*.jison": ["pnpm run lint:jison"]
}

View File

@@ -0,0 +1,7 @@
import baseConfig from '../../.lintstagedrc.mjs';
export default {
...baseConfig,
'src/docs/**': ['pnpm --filter mermaid run docs:build --git'],
'src/docs.mts': ['pnpm --filter mermaid run docs:build --git'],
'src/(defaultConfig|config|mermaidAPI).ts': ['pnpm --filter mermaid run docs:build --git'],
};

View File

@@ -1,23 +1,6 @@
# mermaid # mermaid
[![Build CI Status](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml/badge.svg)](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml) [![NPM](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid) [![Coverage Status](https://coveralls.io/repos/github/mermaid-js/mermaid/badge.svg?branch=master)](https://coveralls.io/github/mermaid-js/mermaid?branch=master) [![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid) [![NPM](https://img.shields.io/npm/dm/mermaid)](https://www.npmjs.com/package/mermaid) [![Join our Slack!](https://img.shields.io/static/v1?message=join%20chat&color=9cf&logo=slack&label=slack)](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE) [![Twitter Follow](https://img.shields.io/twitter/follow/mermaidjs_?style=social)](https://twitter.com/mermaidjs_) [![Build CI Status](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml/badge.svg)](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml) [![NPM](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid) [![npm minified gzipped bundle size](https://img.shields.io/bundlephobia/minzip/mermaid)](https://bundlephobia.com/package/mermaid) [![Coverage Status](https://coveralls.io/repos/github/mermaid-js/mermaid/badge.svg?branch=master)](https://coveralls.io/github/mermaid-js/mermaid?branch=master) [![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid) [![NPM](https://img.shields.io/npm/dm/mermaid)](https://www.npmjs.com/package/mermaid) [![Join our Slack!](https://img.shields.io/static/v1?message=join%20chat&color=9cf&logo=slack&label=slack)](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE) [![Twitter Follow](https://img.shields.io/twitter/follow/mermaidjs_?style=social)](https://twitter.com/mermaidjs_)
# Whoa, what's going on here?
We are transforming the Mermaid repository to a so called mono-repo. This is a part of the effort to decouple the diagrams from the core of mermaid. This will:
- Make it possible to select which diagrams to include on your site
- Open up for lazy loading
- Make it possible to add diagrams from outside of the Mermaid repository
- Separate the release flow between different diagrams and the Mermaid core
As such be aware of some changes..
# We use pnpm now
# The source code has moved
It is now located in the src folder for each respective package located as subfolders in packages.
English | [简体中文](./README.zh-CN.md) English | [简体中文](./README.zh-CN.md)

View File

@@ -1,6 +1,6 @@
# mermaid # mermaid
[![Build CI Status](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml/badge.svg)](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml) [![NPM](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid) [![Coverage Status](https://coveralls.io/repos/github/mermaid-js/mermaid/badge.svg?branch=master)](https://coveralls.io/github/mermaid-js/mermaid?branch=master) [![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid) [![NPM](https://img.shields.io/npm/dm/mermaid)](https://www.npmjs.com/package/mermaid) [![Join our Slack!](https://img.shields.io/static/v1?message=join%20chat&color=9cf&logo=slack&label=slack)](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE) [![Twitter Follow](https://img.shields.io/twitter/follow/mermaidjs_?style=social)](https://twitter.com/mermaidjs_) [![Build CI Status](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml/badge.svg)](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml) [![NPM](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid) [![npm minified gzipped bundle size](https://img.shields.io/bundlephobia/minzip/mermaid)](https://bundlephobia.com/package/mermaid) [![Coverage Status](https://coveralls.io/repos/github/mermaid-js/mermaid/badge.svg?branch=master)](https://coveralls.io/github/mermaid-js/mermaid?branch=master) [![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid) [![NPM](https://img.shields.io/npm/dm/mermaid)](https://www.npmjs.com/package/mermaid) [![Join our Slack!](https://img.shields.io/static/v1?message=join%20chat&color=9cf&logo=slack&label=slack)](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE) [![Twitter Follow](https://img.shields.io/twitter/follow/mermaidjs_?style=social)](https://twitter.com/mermaidjs_)
[English](./README.md) | 简体中文 [English](./README.md) | 简体中文

View File

@@ -1,7 +1,7 @@
{ {
"name": "mermaid", "name": "mermaid",
"version": "9.2.2", "version": "9.2.2",
"description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.", "description": "Markdown-ish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.",
"main": "./dist/mermaid.min.js", "main": "./dist/mermaid.min.js",
"module": "./dist/mermaid.core.mjs", "module": "./dist/mermaid.core.mjs",
"types": "./dist/mermaid.d.ts", "types": "./dist/mermaid.d.ts",
@@ -26,12 +26,13 @@
"scripts": { "scripts": {
"clean": "rimraf dist", "clean": "rimraf dist",
"docs:code": "typedoc src/defaultConfig.ts src/config.ts src/mermaidAPI.ts && prettier --write ./src/docs/config/setup", "docs:code": "typedoc src/defaultConfig.ts src/config.ts src/mermaidAPI.ts && prettier --write ./src/docs/config/setup",
"docs:build": "rimraf ../../docs && pnpm docs:code && ts-node-esm src/docs.mts", "docs:build": "rimraf ../../docs && pnpm docs:spellcheck && pnpm docs:code && ts-node-esm src/docs.mts",
"docs:verify": "pnpm docs:code && ts-node-esm src/docs.mts --verify", "docs:verify": "pnpm docs:spellcheck && pnpm docs:code && ts-node-esm src/docs.mts --verify",
"docs:pre:vitepress": "rimraf src/vitepress && pnpm docs:code && ts-node-esm src/docs.mts --vitepress", "docs:pre:vitepress": "rimraf src/vitepress && pnpm docs:code && ts-node-esm src/docs.mts --vitepress",
"docs:build:vitepress": "pnpm docs:pre:vitepress && vitepress build src/vitepress", "docs:build:vitepress": "pnpm docs:pre:vitepress && vitepress build src/vitepress",
"docs:dev": "pnpm docs:pre:vitepress && concurrently \"vitepress dev src/vitepress\" \"ts-node-esm src/docs.mts --watch --vitepress\"", "docs:dev": "pnpm docs:pre:vitepress && concurrently \"vitepress dev src/vitepress\" \"ts-node-esm src/docs.mts --watch --vitepress\"",
"docs:serve": "pnpm docs:build:vitepress && vitepress serve src/vitepress", "docs:serve": "pnpm docs:build:vitepress && vitepress serve src/vitepress",
"docs:spellcheck": "cspell --config ../../cSpell.json \"src/docs/**/*.md\"",
"release": "pnpm build", "release": "pnpm build",
"prepublishOnly": "pnpm -w run build" "prepublishOnly": "pnpm -w run build"
}, },
@@ -54,13 +55,12 @@
"dependencies": { "dependencies": {
"@braintree/sanitize-url": "^6.0.0", "@braintree/sanitize-url": "^6.0.0",
"d3": "^7.0.0", "d3": "^7.0.0",
"dagre": "^0.8.5", "dagre-d3-es": "7.0.4",
"dagre-d3": "^0.6.4",
"dompurify": "2.4.1", "dompurify": "2.4.1",
"fast-clone": "^1.5.13", "fast-clone": "^1.5.13",
"graphlib": "^2.1.8", "graphlib": "^2.1.8",
"khroma": "^2.0.0", "khroma": "^2.0.0",
"lodash": "^4.17.21", "lodash-es": "^4.17.21",
"moment-mini": "^2.24.0", "moment-mini": "^2.24.0",
"non-layered-tidy-tree-layout": "^2.0.2", "non-layered-tidy-tree-layout": "^2.0.2",
"stylis": "^4.1.2", "stylis": "^4.1.2",
@@ -70,7 +70,7 @@
"@types/d3": "^7.4.0", "@types/d3": "^7.4.0",
"@types/dompurify": "^2.4.0", "@types/dompurify": "^2.4.0",
"@types/jsdom": "^20.0.1", "@types/jsdom": "^20.0.1",
"@types/lodash": "^4.14.188", "@types/lodash-es": "^4.17.6",
"@types/micromatch": "^4.0.2", "@types/micromatch": "^4.0.2",
"@types/prettier": "^2.7.1", "@types/prettier": "^2.7.1",
"@types/stylis": "^4.0.2", "@types/stylis": "^4.0.2",
@@ -80,6 +80,7 @@
"chokidar": "^3.5.3", "chokidar": "^3.5.3",
"concurrently": "^7.5.0", "concurrently": "^7.5.0",
"coveralls": "^3.1.1", "coveralls": "^3.1.1",
"cspell": "^6.14.3",
"globby": "^13.1.2", "globby": "^13.1.2",
"identity-obj-proxy": "^3.0.0", "identity-obj-proxy": "^3.0.0",
"jison": "^0.4.18", "jison": "^0.4.18",
@@ -97,9 +98,6 @@
"typescript": "^4.8.4", "typescript": "^4.8.4",
"unist-util-flatmap": "^1.0.0" "unist-util-flatmap": "^1.0.0"
}, },
"resolutions": {
"d3": "^7.0.0"
},
"files": [ "files": [
"dist", "dist",
"README.md" "README.md"

View File

@@ -2,6 +2,7 @@ import * as configApi from './config';
import { log } from './logger'; import { log } from './logger';
import { getDiagram, registerDiagram } from './diagram-api/diagramAPI'; import { getDiagram, registerDiagram } from './diagram-api/diagramAPI';
import { detectType, getDiagramLoader } from './diagram-api/detectType'; import { detectType, getDiagramLoader } from './diagram-api/detectType';
import { extractFrontMatter } from './diagram-api/frontmatter';
import { isDetailedError, type DetailedError } from './utils'; import { isDetailedError, type DetailedError } from './utils';
export type ParseErrorFunction = (err: string | DetailedError, hash?: any) => void; export type ParseErrorFunction = (err: string | DetailedError, hash?: any) => void;
@@ -29,6 +30,16 @@ export class Diagram {
this.db.clear?.(); this.db.clear?.();
this.renderer = diagram.renderer; this.renderer = diagram.renderer;
this.parser = diagram.parser; this.parser = diagram.parser;
const originalParse = this.parser.parse.bind(this.parser);
// Wrap the jison parse() method to handle extracting frontmatter.
//
// This can't be done in this.parse() because some code
// directly calls diagram.parser.parse(), bypassing this.parse().
//
// Similarly, we can't do this in getDiagramFromText() because some code
// calls diagram.db.clear(), which would reset anything set by
// extractFrontMatter().
this.parser.parse = (text: string) => originalParse(extractFrontMatter(text, this.db));
this.parser.parser.yy = this.db; this.parser.parser.yy = this.db;
if (diagram.init) { if (diagram.init) {
diagram.init(cnf); diagram.init(cnf);
@@ -45,7 +56,7 @@ export class Diagram {
} }
try { try {
text = text + '\n'; text = text + '\n';
this.db.clear(); this.db.clear?.();
this.parser.parse(text); this.parser.parse(text);
return true; return true;
} catch (error) { } catch (error) {

View File

@@ -189,6 +189,7 @@ export interface C4DiagramConfig extends BaseDiagramConfig {
} }
export interface GitGraphDiagramConfig extends BaseDiagramConfig { export interface GitGraphDiagramConfig extends BaseDiagramConfig {
titleTopMargin?: number;
diagramPadding?: number; diagramPadding?: number;
nodeLabel?: NodeLabel; nodeLabel?: NodeLabel;
mainBranchName?: string; mainBranchName?: string;
@@ -227,6 +228,7 @@ export interface MindmapDiagramConfig extends BaseDiagramConfig {
export type PieDiagramConfig = BaseDiagramConfig; export type PieDiagramConfig = BaseDiagramConfig;
export interface ErDiagramConfig extends BaseDiagramConfig { export interface ErDiagramConfig extends BaseDiagramConfig {
titleTopMargin?: number;
diagramPadding?: number; diagramPadding?: number;
layoutDirection?: string; layoutDirection?: string;
minEntityWidth?: number; minEntityWidth?: number;
@@ -238,6 +240,7 @@ export interface ErDiagramConfig extends BaseDiagramConfig {
} }
export interface StateDiagramConfig extends BaseDiagramConfig { export interface StateDiagramConfig extends BaseDiagramConfig {
titleTopMargin?: number;
arrowMarkerAbsolute?: boolean; arrowMarkerAbsolute?: boolean;
dividerMargin?: number; dividerMargin?: number;
sizeUnit?: number; sizeUnit?: number;
@@ -258,6 +261,7 @@ export interface StateDiagramConfig extends BaseDiagramConfig {
} }
export interface ClassDiagramConfig extends BaseDiagramConfig { export interface ClassDiagramConfig extends BaseDiagramConfig {
titleTopMargin?: number;
arrowMarkerAbsolute?: boolean; arrowMarkerAbsolute?: boolean;
dividerMargin?: number; dividerMargin?: number;
padding?: number; padding?: number;
@@ -343,6 +347,7 @@ export interface SequenceDiagramConfig extends BaseDiagramConfig {
} }
export interface FlowchartDiagramConfig extends BaseDiagramConfig { export interface FlowchartDiagramConfig extends BaseDiagramConfig {
titleTopMargin?: number;
arrowMarkerAbsolute?: boolean; arrowMarkerAbsolute?: boolean;
diagramPadding?: number; diagramPadding?: number;
htmlLabels?: boolean; htmlLabels?: boolean;

View File

@@ -1,5 +1,5 @@
import dagre from 'dagre'; import { layout as dagreLayout } from 'dagre-d3-es/src/dagre/index.js';
import graphlib from 'graphlib'; import * as graphlibJson from 'dagre-d3-es/src/graphlib/json';
import insertMarkers from './markers'; import insertMarkers from './markers';
import { updateNodeBounds } from './shapes/util'; import { updateNodeBounds } from './shapes/util';
import { import {
@@ -15,7 +15,7 @@ import { insertEdgeLabel, positionEdgeLabel, insertEdge, clear as clearEdges } f
import { log } from '../logger'; import { log } from '../logger';
const recursiveRender = (_elem, graph, diagramtype, parentCluster) => { const recursiveRender = (_elem, graph, diagramtype, parentCluster) => {
log.info('Graph in recursive render: XXX', graphlib.json.write(graph), parentCluster); log.info('Graph in recursive render: XXX', graphlibJson.write(graph), parentCluster);
const dir = graph.graph().rankdir; const dir = graph.graph().rankdir;
log.trace('Dir in recursive render - dir:', dir); log.trace('Dir in recursive render - dir:', dir);
@@ -95,8 +95,8 @@ const recursiveRender = (_elem, graph, diagramtype, parentCluster) => {
log.info('### Layout ###'); log.info('### Layout ###');
log.info('#############################################'); log.info('#############################################');
log.info(graph); log.info(graph);
dagre.layout(graph); dagreLayout(graph);
log.info('Graph after layout:', graphlib.json.write(graph)); log.info('Graph after layout:', graphlibJson.write(graph));
// Move the nodes to the correct place // Move the nodes to the correct place
let diff = 0; let diff = 0;
sortNodesByHierarchy(graph).forEach(function (v) { sortNodesByHierarchy(graph).forEach(function (v) {
@@ -153,10 +153,10 @@ export const render = (elem, graph, markers, diagramtype, id) => {
clearClusters(); clearClusters();
clearGraphlib(); clearGraphlib();
log.warn('Graph at first:', graphlib.json.write(graph)); log.warn('Graph at first:', graphlibJson.write(graph));
adjustClustersAndEdges(graph); adjustClustersAndEdges(graph);
log.warn('Graph after:', graphlib.json.write(graph)); log.warn('Graph after:', graphlibJson.write(graph));
// log.warn('Graph ever after:', graphlib.json.write(graph.node('A').graph)); // log.warn('Graph ever after:', graphlibJson.write(graph.node('A').graph));
recursiveRender(elem, graph, diagramtype); recursiveRender(elem, graph, diagramtype);
}; };

View File

@@ -1,6 +1,7 @@
/** Decorates with functions required by mermaids dagre-wrapper. */ /** Decorates with functions required by mermaids dagre-wrapper. */
import { log } from '../logger'; import { log } from '../logger';
import graphlib from 'graphlib'; import * as graphlibJson from 'dagre-d3-es/src/graphlib/json';
import * as graphlib from 'dagre-d3-es/src/graphlib';
export let clusterDb = {}; export let clusterDb = {};
let decendants = {}; let decendants = {};
@@ -322,7 +323,7 @@ export const adjustClustersAndEdges = (graph, depth) => {
graph.setEdge(v, w, edge, e.name); graph.setEdge(v, w, edge, e.name);
} }
}); });
log.warn('Adjusted Graph', graphlib.json.write(graph)); log.warn('Adjusted Graph', graphlibJson.write(graph));
extractor(graph, 0); extractor(graph, 0);
log.trace(clusterDb); log.trace(clusterDb);
@@ -336,7 +337,7 @@ export const adjustClustersAndEdges = (graph, depth) => {
}; };
export const extractor = (graph, depth) => { export const extractor = (graph, depth) => {
log.warn('extractor - ', depth, graphlib.json.write(graph), graph.children('D')); log.warn('extractor - ', depth, graphlibJson.write(graph), graph.children('D'));
if (depth > 10) { if (depth > 10) {
log.error('Bailing out'); log.error('Bailing out');
return; return;
@@ -415,7 +416,7 @@ export const extractor = (graph, depth) => {
return {}; return {};
}); });
log.warn('Old graph before copy', graphlib.json.write(graph)); log.warn('Old graph before copy', graphlibJson.write(graph));
copy(node, graph, clusterGraph, node); copy(node, graph, clusterGraph, node);
graph.setNode(node, { graph.setNode(node, {
clusterNode: true, clusterNode: true,
@@ -424,8 +425,8 @@ export const extractor = (graph, depth) => {
labelText: clusterDb[node].labelText, labelText: clusterDb[node].labelText,
graph: clusterGraph, graph: clusterGraph,
}); });
log.warn('New graph after copy node: (', node, ')', graphlib.json.write(clusterGraph)); log.warn('New graph after copy node: (', node, ')', graphlibJson.write(clusterGraph));
log.debug('Old graph after copy', graphlib.json.write(graph)); log.debug('Old graph after copy', graphlibJson.write(graph));
} else { } else {
log.warn( log.warn(
'Cluster ** ', 'Cluster ** ',

View File

@@ -1,5 +1,5 @@
import graphlib from 'graphlib'; import * as graphlibJson from 'dagre-d3-es/src/graphlib/json';
import dagre from 'dagre'; import * as graphlib from 'dagre-d3-es/src/graphlib';
import { import {
validate, validate,
adjustClustersAndEdges, adjustClustersAndEdges,
@@ -233,9 +233,9 @@ describe('Graphlib decorations', () => {
g.setParent('D', 'C'); g.setParent('D', 'C');
// log.info('Graph before', g.node('D')) // log.info('Graph before', g.node('D'))
// log.info('Graph before', graphlib.json.write(g)) // log.info('Graph before', graphlibJson.write(g))
adjustClustersAndEdges(g); adjustClustersAndEdges(g);
// log.info('Graph after', graphlib.json.write(g), g.node('C').graph) // log.info('Graph after', graphlibJson.write(g), g.node('C').graph)
const CGraph = g.node('C').graph; const CGraph = g.node('C').graph;
const DGraph = CGraph.node('D').graph; const DGraph = CGraph.node('D').graph;
@@ -279,9 +279,9 @@ describe('Graphlib decorations', () => {
g.setEdge('A', 'C', { data: 'link2' }, '2'); g.setEdge('A', 'C', { data: 'link2' }, '2');
log.info('Graph before', g.node('D')); log.info('Graph before', g.node('D'));
log.info('Graph before', graphlib.json.write(g)); log.info('Graph before', graphlibJson.write(g));
adjustClustersAndEdges(g); adjustClustersAndEdges(g);
log.trace('Graph after', graphlib.json.write(g)); log.trace('Graph after', graphlibJson.write(g));
expect(g.nodes()).toEqual(['C', 'B', 'A']); expect(g.nodes()).toEqual(['C', 'B', 'A']);
expect(g.nodes().length).toBe(3); expect(g.nodes().length).toBe(3);
expect(g.edges().length).toBe(2); expect(g.edges().length).toBe(2);
@@ -334,11 +334,11 @@ describe('Graphlib decorations', () => {
g.setEdge('c', 'd', { data: 'link2' }, '2'); g.setEdge('c', 'd', { data: 'link2' }, '2');
g.setEdge('d', 'e', { data: 'link2' }, '2'); g.setEdge('d', 'e', { data: 'link2' }, '2');
log.info('Graph before', graphlib.json.write(g)); log.info('Graph before', graphlibJson.write(g));
adjustClustersAndEdges(g); adjustClustersAndEdges(g);
const bGraph = g.node('b').graph; const bGraph = g.node('b').graph;
// log.trace('Graph after', graphlib.json.write(g)) // log.trace('Graph after', graphlibJson.write(g))
log.info('Graph after', graphlib.json.write(bGraph)); log.info('Graph after', graphlibJson.write(bGraph));
expect(bGraph.nodes().length).toBe(3); expect(bGraph.nodes().length).toBe(3);
expect(bGraph.edges().length).toBe(2); expect(bGraph.edges().length).toBe(2);
}); });
@@ -360,13 +360,13 @@ describe('Graphlib decorations', () => {
g.setParent('c', 'b'); g.setParent('c', 'b');
g.setParent('e', 'c'); g.setParent('e', 'c');
log.info('Graph before', graphlib.json.write(g)); log.info('Graph before', graphlibJson.write(g));
adjustClustersAndEdges(g); adjustClustersAndEdges(g);
const aGraph = g.node('a').graph; const aGraph = g.node('a').graph;
const bGraph = aGraph.node('b').graph; const bGraph = aGraph.node('b').graph;
log.info('Graph after', graphlib.json.write(aGraph)); log.info('Graph after', graphlibJson.write(aGraph));
const cGraph = bGraph.node('c').graph; const cGraph = bGraph.node('c').graph;
// log.trace('Graph after', graphlib.json.write(g)) // log.trace('Graph after', graphlibJson.write(g))
expect(aGraph.nodes().length).toBe(1); expect(aGraph.nodes().length).toBe(1);
expect(bGraph.nodes().length).toBe(1); expect(bGraph.nodes().length).toBe(1);
expect(cGraph.nodes().length).toBe(1); expect(cGraph.nodes().length).toBe(1);
@@ -388,14 +388,14 @@ flowchart TB
const exportedGraph = JSON.parse( const exportedGraph = JSON.parse(
'{"options":{"directed":true,"multigraph":true,"compound":true},"nodes":[{"v":"A","value":{"labelStyle":"","shape":"rect","labelText":"A","rx":0,"ry":0,"class":"default","style":"","id":"A","width":500,"type":"group","padding":15}},{"v":"B","value":{"labelStyle":"","shape":"rect","labelText":"B","rx":0,"ry":0,"class":"default","style":"","id":"B","width":500,"type":"group","padding":15},"parent":"A"},{"v":"b","value":{"labelStyle":"","shape":"rect","labelText":"b","rx":0,"ry":0,"class":"default","style":"","id":"b","padding":15},"parent":"A"},{"v":"c","value":{"labelStyle":"","shape":"rect","labelText":"c","rx":0,"ry":0,"class":"default","style":"","id":"c","padding":15},"parent":"B"},{"v":"a","value":{"labelStyle":"","shape":"rect","labelText":"a","rx":0,"ry":0,"class":"default","style":"","id":"a","padding":15},"parent":"A"}],"edges":[{"v":"b","w":"B","name":"1","value":{"minlen":1,"arrowhead":"normal","arrowTypeStart":"arrow_open","arrowTypeEnd":"arrow_point","thickness":"normal","pattern":"solid","style":"fill:none","labelStyle":"","arrowheadStyle":"fill: #333","labelpos":"c","labelType":"text","label":"","id":"L-b-B","classes":"flowchart-link LS-b LE-B"}},{"v":"a","w":"c","name":"2","value":{"minlen":1,"arrowhead":"normal","arrowTypeStart":"arrow_open","arrowTypeEnd":"arrow_point","thickness":"normal","pattern":"solid","style":"fill:none","labelStyle":"","arrowheadStyle":"fill: #333","labelpos":"c","labelType":"text","label":"","id":"L-a-c","classes":"flowchart-link LS-a LE-c"}}],"value":{"rankdir":"TB","nodesep":50,"ranksep":50,"marginx":8,"marginy":8}}' '{"options":{"directed":true,"multigraph":true,"compound":true},"nodes":[{"v":"A","value":{"labelStyle":"","shape":"rect","labelText":"A","rx":0,"ry":0,"class":"default","style":"","id":"A","width":500,"type":"group","padding":15}},{"v":"B","value":{"labelStyle":"","shape":"rect","labelText":"B","rx":0,"ry":0,"class":"default","style":"","id":"B","width":500,"type":"group","padding":15},"parent":"A"},{"v":"b","value":{"labelStyle":"","shape":"rect","labelText":"b","rx":0,"ry":0,"class":"default","style":"","id":"b","padding":15},"parent":"A"},{"v":"c","value":{"labelStyle":"","shape":"rect","labelText":"c","rx":0,"ry":0,"class":"default","style":"","id":"c","padding":15},"parent":"B"},{"v":"a","value":{"labelStyle":"","shape":"rect","labelText":"a","rx":0,"ry":0,"class":"default","style":"","id":"a","padding":15},"parent":"A"}],"edges":[{"v":"b","w":"B","name":"1","value":{"minlen":1,"arrowhead":"normal","arrowTypeStart":"arrow_open","arrowTypeEnd":"arrow_point","thickness":"normal","pattern":"solid","style":"fill:none","labelStyle":"","arrowheadStyle":"fill: #333","labelpos":"c","labelType":"text","label":"","id":"L-b-B","classes":"flowchart-link LS-b LE-B"}},{"v":"a","w":"c","name":"2","value":{"minlen":1,"arrowhead":"normal","arrowTypeStart":"arrow_open","arrowTypeEnd":"arrow_point","thickness":"normal","pattern":"solid","style":"fill:none","labelStyle":"","arrowheadStyle":"fill: #333","labelpos":"c","labelType":"text","label":"","id":"L-a-c","classes":"flowchart-link LS-a LE-c"}}],"value":{"rankdir":"TB","nodesep":50,"ranksep":50,"marginx":8,"marginy":8}}'
); );
const gr = graphlib.json.read(exportedGraph); const gr = graphlibJson.read(exportedGraph);
log.info('Graph before', graphlib.json.write(gr)); log.info('Graph before', graphlibJson.write(gr));
adjustClustersAndEdges(gr); adjustClustersAndEdges(gr);
const aGraph = gr.node('A').graph; const aGraph = gr.node('A').graph;
const bGraph = aGraph.node('B').graph; const bGraph = aGraph.node('B').graph;
log.info('Graph after', graphlib.json.write(aGraph)); log.info('Graph after', graphlibJson.write(aGraph));
// log.trace('Graph after', graphlib.json.write(g)) // log.trace('Graph after', graphlibJson.write(g))
expect(aGraph.parent('c')).toBe('B'); expect(aGraph.parent('c')).toBe('B');
expect(aGraph.parent('B')).toBe(undefined); expect(aGraph.parent('B')).toBe(undefined);
}); });

View File

@@ -154,6 +154,17 @@ const config: Partial<MermaidConfig> = {
/** The object containing configurations specific for flowcharts */ /** The object containing configurations specific for flowcharts */
flowchart: { flowchart: {
/**
* ### titleTopMargin
*
* | Parameter | Description | Type | Required | Values |
* | -------------- | ---------------------------------------------- | ------- | -------- | ------------------ |
* | titleTopMargin | Margin top for the text over the flowchart | Integer | Required | Any Positive Value |
*
* **Notes:** Default value: 25
*/
titleTopMargin: 25,
/** /**
* | Parameter | Description | Type | Required | Values | * | Parameter | Description | Type | Required | Values |
* | -------------- | ----------------------------------------------- | ------- | -------- | ------------------ | * | -------------- | ----------------------------------------------- | ------- | -------- | ------------------ |
@@ -851,6 +862,16 @@ const config: Partial<MermaidConfig> = {
sectionColours: ['#fff'], sectionColours: ['#fff'],
}, },
class: { class: {
/**
* ### titleTopMargin
*
* | Parameter | Description | Type | Required | Values |
* | -------------- | ---------------------------------------------- | ------- | -------- | ------------------ |
* | titleTopMargin | Margin top for the text over the class diagram | Integer | Required | Any Positive Value |
*
* **Notes:** Default value: 25
*/
titleTopMargin: 25,
arrowMarkerAbsolute: false, arrowMarkerAbsolute: false,
dividerMargin: 10, dividerMargin: 10,
padding: 5, padding: 5,
@@ -884,6 +905,16 @@ const config: Partial<MermaidConfig> = {
defaultRenderer: 'dagre-wrapper', defaultRenderer: 'dagre-wrapper',
}, },
state: { state: {
/**
* ### titleTopMargin
*
* | Parameter | Description | Type | Required | Values |
* | -------------- | ---------------------------------------------- | ------- | -------- | ------------------ |
* | titleTopMargin | Margin top for the text over the state diagram | Integer | Required | Any Positive Value |
*
* **Notes:** Default value: 25
*/
titleTopMargin: 25,
dividerMargin: 10, dividerMargin: 10,
sizeUnit: 5, sizeUnit: 5,
padding: 8, padding: 8,
@@ -932,6 +963,17 @@ const config: Partial<MermaidConfig> = {
/** The object containing configurations specific for entity relationship diagrams */ /** The object containing configurations specific for entity relationship diagrams */
er: { er: {
/**
* ### titleTopMargin
*
* | Parameter | Description | Type | Required | Values |
* | -------------- | ---------------------------------------------- | ------- | -------- | ------------------ |
* | titleTopMargin | Margin top for the text over the diagram | Integer | Required | Any Positive Value |
*
* **Notes:** Default value: 25
*/
titleTopMargin: 25,
/** /**
* | Parameter | Description | Type | Required | Values | * | Parameter | Description | Type | Required | Values |
* | -------------- | ----------------------------------------------- | ------- | -------- | ------------------ | * | -------------- | ----------------------------------------------- | ------- | -------- | ------------------ |
@@ -1085,6 +1127,16 @@ const config: Partial<MermaidConfig> = {
line_height: 20, line_height: 20,
}, },
gitGraph: { gitGraph: {
/**
* ### titleTopMargin
*
* | Parameter | Description | Type | Required | Values |
* | -------------- | ---------------------------------------------- | ------- | -------- | ------------------ |
* | titleTopMargin | Margin top for the text over the Git diagram | Integer | Required | Any Positive Value |
*
* **Notes:** Default value: 25
*/
titleTopMargin: 25,
diagramPadding: 8, diagramPadding: 8,
nodeLabel: { nodeLabel: {
width: 75, width: 75,

View File

@@ -1,6 +1,7 @@
import { MermaidConfig } from '../config.type'; import { MermaidConfig } from '../config.type';
import { log } from '../logger'; import { log } from '../logger';
import { DetectorRecord, DiagramDetector, DiagramLoader } from './types'; import { DetectorRecord, DiagramDetector, DiagramLoader } from './types';
import { frontMatterRegex } from './frontmatter';
const directive = const directive =
/[%]{2}[{]\s*(?:(?:(\w+)\s*:|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi; /[%]{2}[{]\s*(?:(?:(\w+)\s*:|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi;
@@ -31,7 +32,7 @@ const detectors: Record<string, DetectorRecord> = {};
* @returns A graph definition key * @returns A graph definition key
*/ */
export const detectType = function (text: string, config?: MermaidConfig): string { export const detectType = function (text: string, config?: MermaidConfig): string {
text = text.replace(directive, '').replace(anyComment, '\n'); text = text.replace(frontMatterRegex, '').replace(directive, '').replace(anyComment, '\n');
for (const [key, { detector }] of Object.entries(detectors)) { for (const [key, { detector }] of Object.entries(detectors)) {
const diagram = detector(text, config); const diagram = detector(text, config);
if (diagram) { if (diagram) {

View File

@@ -0,0 +1,78 @@
import { vi } from 'vitest';
import { extractFrontMatter } from './frontmatter';
const dbMock = () => ({ setDiagramTitle: vi.fn() });
describe('extractFrontmatter', () => {
it('returns text unchanged if no frontmatter', () => {
expect(extractFrontMatter('diagram', dbMock())).toEqual('diagram');
});
it('returns text unchanged if frontmatter lacks closing delimiter', () => {
const text = `---\ntitle: foo\ndiagram`;
expect(extractFrontMatter(text, dbMock())).toEqual(text);
});
it('handles empty frontmatter', () => {
const db = dbMock();
const text = `---\n\n---\ndiagram`;
expect(extractFrontMatter(text, db)).toEqual('diagram');
expect(db.setDiagramTitle).not.toHaveBeenCalled();
});
it('handles frontmatter without mappings', () => {
const db = dbMock();
const text = `---\n1\n---\ndiagram`;
expect(extractFrontMatter(text, db)).toEqual('diagram');
expect(db.setDiagramTitle).not.toHaveBeenCalled();
});
it('does not try to parse frontmatter at the end', () => {
const db = dbMock();
const text = `diagram\n---\ntitle: foo\n---\n`;
expect(extractFrontMatter(text, db)).toEqual(text);
expect(db.setDiagramTitle).not.toHaveBeenCalled();
});
it('handles frontmatter with multiple delimiters', () => {
const db = dbMock();
const text = `---\ntitle: foo---bar\n---\ndiagram\n---\ntest`;
expect(extractFrontMatter(text, db)).toEqual('diagram\n---\ntest');
expect(db.setDiagramTitle).toHaveBeenCalledWith('foo---bar');
});
it('handles frontmatter with multi-line string and multiple delimiters', () => {
const db = dbMock();
const text = `---\ntitle: |\n multi-line string\n ---\n---\ndiagram`;
expect(extractFrontMatter(text, db)).toEqual('diagram');
expect(db.setDiagramTitle).toHaveBeenCalledWith('multi-line string\n---\n');
});
it('handles frontmatter with title', () => {
const db = dbMock();
const text = `---\ntitle: foo\n---\ndiagram`;
expect(extractFrontMatter(text, db)).toEqual('diagram');
expect(db.setDiagramTitle).toHaveBeenCalledWith('foo');
});
it('handles booleans in frontmatter properly', () => {
const db = dbMock();
const text = `---\ntitle: true\n---\ndiagram`;
expect(extractFrontMatter(text, db)).toEqual('diagram');
expect(db.setDiagramTitle).toHaveBeenCalledWith('true');
});
it('ignores unspecified frontmatter keys', () => {
const db = dbMock();
const text = `---\ninvalid: true\ntitle: foo\ntest: bar\n---\ndiagram`;
expect(extractFrontMatter(text, db)).toEqual('diagram');
expect(db.setDiagramTitle).toHaveBeenCalledWith('foo');
});
it('throws exception for invalid YAML syntax', () => {
const text = `---\n!!!\n---\ndiagram`;
expect(() => extractFrontMatter(text, dbMock())).toThrow(
'tag suffix cannot contain exclamation marks'
);
});
});

View File

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

View File

@@ -8,8 +8,16 @@ export interface InjectUtils {
_setupGraphViewbox: any; _setupGraphViewbox: any;
} }
/**
* Generic Diagram DB that may apply to any diagram type.
*/
export interface DiagramDb {
clear?: () => void;
setDiagramTitle?: (title: string) => void;
}
export interface DiagramDefinition { export interface DiagramDefinition {
db: any; db: DiagramDb;
renderer: any; renderer: any;
parser: any; parser: any;
styles: any; styles: any;

View File

@@ -10,6 +10,8 @@ import {
getAccDescription, getAccDescription,
setAccDescription, setAccDescription,
clear as commonClear, clear as commonClear,
setDiagramTitle,
getDiagramTitle,
} from '../../commonDb'; } from '../../commonDb';
const MERMAID_DOM_ID_PREFIX = 'classid-'; const MERMAID_DOM_ID_PREFIX = 'classid-';
@@ -408,4 +410,6 @@ export default {
getTooltip, getTooltip,
setTooltip, setTooltip,
lookUpDomId, lookUpDomId,
setDiagramTitle,
getDiagramTitle,
}; };

View File

@@ -1,8 +1,9 @@
import { select } from 'd3'; import { select } from 'd3';
import graphlib from 'graphlib'; import * as graphlib from 'dagre-d3-es/src/graphlib';
import { log } from '../../logger'; import { log } from '../../logger';
import { getConfig } from '../../config'; import { getConfig } from '../../config';
import { render } from '../../dagre-wrapper/index.js'; import { render } from '../../dagre-wrapper/index.js';
import utils from '../../utils';
import { curveLinear } from 'd3'; import { curveLinear } from 'd3';
import { interpolateToCurve, getStylesFromArray } from '../../utils'; import { interpolateToCurve, getStylesFromArray } from '../../utils';
import { setupGraphViewbox } from '../../setupGraphViewbox'; import { setupGraphViewbox } from '../../setupGraphViewbox';
@@ -429,6 +430,8 @@ export const draw = function (text, id, _version, diagObj) {
id id
); );
utils.insertTitle(svg, 'classTitleText', conf.titleTopMargin, diagObj.db.getDiagramTitle());
setupGraphViewbox(g, svg, conf.diagramPadding, conf.useMaxWidth); setupGraphViewbox(g, svg, conf.diagramPadding, conf.useMaxWidth);
// Add label rects for non html labels // Add label rects for non html labels

View File

@@ -1,6 +1,6 @@
import { select } from 'd3'; import { select } from 'd3';
import dagre from 'dagre'; import { layout as dagreLayout } from 'dagre-d3-es/src/dagre/index.js';
import graphlib from 'graphlib'; import * as graphlib from 'dagre-d3-es/src/graphlib/index.js';
import { log } from '../../logger'; import { log } from '../../logger';
import svgDraw from './svgDraw'; import svgDraw from './svgDraw';
import { configureSvgSize } from '../../setupGraphViewbox'; import { configureSvgSize } from '../../setupGraphViewbox';
@@ -238,7 +238,7 @@ export const draw = function (text, id, _version, diagObj) {
} }
}); });
dagre.layout(g); dagreLayout(g);
g.nodes().forEach(function (v) { g.nodes().forEach(function (v) {
if (typeof v !== 'undefined' && typeof g.node(v) !== 'undefined') { if (typeof v !== 'undefined' && typeof g.node(v) !== 'undefined') {
log.debug('Node ' + v + ': ' + JSON.stringify(g.node(v))); log.debug('Node ' + v + ': ' + JSON.stringify(g.node(v)));

View File

@@ -148,6 +148,11 @@ g.classGroup line {
font-size: 11px; font-size: 11px;
} }
.classTitleText {
text-anchor: middle;
font-size: 18px;
fill: ${options.textColor};
}
`; `;
export default getStyles; export default getStyles;

View File

@@ -8,6 +8,8 @@ import {
getAccDescription, getAccDescription,
setAccDescription, setAccDescription,
clear as commonClear, clear as commonClear,
setDiagramTitle,
getDiagramTitle,
} from '../../commonDb'; } from '../../commonDb';
let entities = {}; let entities = {};
@@ -94,4 +96,6 @@ export default {
getAccTitle, getAccTitle,
setAccDescription, setAccDescription,
getAccDescription, getAccDescription,
setDiagramTitle,
getDiagramTitle,
}; };

View File

@@ -1,8 +1,9 @@
import graphlib from 'graphlib'; import * as graphlib from 'dagre-d3-es/src/graphlib';
import { line, curveBasis, select } from 'd3'; import { line, curveBasis, select } from 'd3';
import dagre from 'dagre'; import { layout as dagreLayout } from 'dagre-d3-es/src/dagre/index.js';
import { getConfig } from '../../config'; import { getConfig } from '../../config';
import { log } from '../../logger'; import { log } from '../../logger';
import utils from '../../utils';
import erMarkers from './erMarkers'; import erMarkers from './erMarkers';
import { configureSvgSize } from '../../setupGraphViewbox'; import { configureSvgSize } from '../../setupGraphViewbox';
import addSVGAccessibilityFields from '../../accessibility'; import addSVGAccessibilityFields from '../../accessibility';
@@ -210,9 +211,6 @@ const drawAttributes = (groupNode, entityTextNode, attributes) => {
const typeRect = groupNode const typeRect = groupNode
.insert('rect', '#' + attributeNode.tn.node().id) .insert('rect', '#' + attributeNode.tn.node().id)
.classed(`er ${attribStyle}`, true) .classed(`er ${attribStyle}`, true)
.style('fill', conf.fill)
.style('fill-opacity', '100%')
.style('stroke', conf.stroke)
.attr('x', 0) .attr('x', 0)
.attr('y', heightOffset) .attr('y', heightOffset)
.attr('width', maxTypeWidth + widthPadding * 2 + spareColumnWidth) .attr('width', maxTypeWidth + widthPadding * 2 + spareColumnWidth)
@@ -230,9 +228,6 @@ const drawAttributes = (groupNode, entityTextNode, attributes) => {
const nameRect = groupNode const nameRect = groupNode
.insert('rect', '#' + attributeNode.nn.node().id) .insert('rect', '#' + attributeNode.nn.node().id)
.classed(`er ${attribStyle}`, true) .classed(`er ${attribStyle}`, true)
.style('fill', conf.fill)
.style('fill-opacity', '100%')
.style('stroke', conf.stroke)
.attr('x', nameXOffset) .attr('x', nameXOffset)
.attr('y', heightOffset) .attr('y', heightOffset)
.attr('width', maxNameWidth + widthPadding * 2 + spareColumnWidth) .attr('width', maxNameWidth + widthPadding * 2 + spareColumnWidth)
@@ -252,9 +247,6 @@ const drawAttributes = (groupNode, entityTextNode, attributes) => {
const keyTypeRect = groupNode const keyTypeRect = groupNode
.insert('rect', '#' + attributeNode.kn.node().id) .insert('rect', '#' + attributeNode.kn.node().id)
.classed(`er ${attribStyle}`, true) .classed(`er ${attribStyle}`, true)
.style('fill', conf.fill)
.style('fill-opacity', '100%')
.style('stroke', conf.stroke)
.attr('x', keyTypeAndCommentXOffset) .attr('x', keyTypeAndCommentXOffset)
.attr('y', heightOffset) .attr('y', heightOffset)
.attr('width', maxKeyWidth + widthPadding * 2 + spareColumnWidth) .attr('width', maxKeyWidth + widthPadding * 2 + spareColumnWidth)
@@ -275,9 +267,6 @@ const drawAttributes = (groupNode, entityTextNode, attributes) => {
groupNode groupNode
.insert('rect', '#' + attributeNode.cn.node().id) .insert('rect', '#' + attributeNode.cn.node().id)
.classed(`er ${attribStyle}`, 'true') .classed(`er ${attribStyle}`, 'true')
.style('fill', conf.fill)
.style('fill-opacity', '100%')
.style('stroke', conf.stroke)
.attr('x', keyTypeAndCommentXOffset) .attr('x', keyTypeAndCommentXOffset)
.attr('y', heightOffset) .attr('y', heightOffset)
.attr('width', maxCommentWidth + widthPadding * 2 + spareColumnWidth) .attr('width', maxCommentWidth + widthPadding * 2 + spareColumnWidth)
@@ -347,9 +336,6 @@ const drawEntities = function (svgNode, entities, graph) {
const rectNode = groupNode const rectNode = groupNode
.insert('rect', '#' + textId) .insert('rect', '#' + textId)
.classed('er entityBox', true) .classed('er entityBox', true)
.style('fill', conf.fill)
.style('fill-opacity', '100%')
.style('stroke', conf.stroke)
.attr('x', 0) .attr('x', 0)
.attr('y', 0) .attr('y', 0)
.attr('width', entityWidth) .attr('width', entityWidth)
@@ -547,9 +533,7 @@ const drawRelationshipFromLayout = function (svg, rel, g, insert, diagObj) {
.attr('x', labelPoint.x - labelBBox.width / 2) .attr('x', labelPoint.x - labelBBox.width / 2)
.attr('y', labelPoint.y - labelBBox.height / 2) .attr('y', labelPoint.y - labelBBox.height / 2)
.attr('width', labelBBox.width) .attr('width', labelBBox.width)
.attr('height', labelBBox.height) .attr('height', labelBBox.height);
.style('fill', 'white')
.style('fill-opacity', '85%');
}; };
/** /**
@@ -637,7 +621,7 @@ export const draw = function (text, id, _version, diagObj) {
// Add all the relationships to the graph // Add all the relationships to the graph
const relationships = addRelationships(diagObj.db.getRelationships(), g); const relationships = addRelationships(diagObj.db.getRelationships(), g);
dagre.layout(g); // Node and edge positions will be updated dagreLayout(g); // Node and edge positions will be updated
// Adjust the positions of the entities so that they adhere to the layout // Adjust the positions of the entities so that they adhere to the layout
adjustEntities(svg, g); adjustEntities(svg, g);
@@ -649,6 +633,8 @@ export const draw = function (text, id, _version, diagObj) {
const padding = conf.diagramPadding; const padding = conf.diagramPadding;
utils.insertTitle(svg, 'entityTitleText', conf.titleTopMargin, diagObj.db.getDiagramTitle());
const svgBounds = svg.node().getBBox(); const svgBounds = svg.node().getBBox();
const width = svgBounds.width + padding * 2; const width = svgBounds.width + padding * 2;
const height = svgBounds.height + padding * 2; const height = svgBounds.height + padding * 2;

View File

@@ -27,6 +27,12 @@ const getStyles = (options) =>
.relationshipLine { .relationshipLine {
stroke: ${options.lineColor}; stroke: ${options.lineColor};
} }
.entityTitleText {
text-anchor: middle;
font-size: 18px;
fill: ${options.textColor};
}
`; `;
export default getStyles; export default getStyles;

View File

@@ -1,4 +1,5 @@
import dagreD3 from 'dagre-d3'; import { intersectPolygon } from 'dagre-d3-es/src/dagre-js/intersect/intersect-polygon.js';
import { intersectRect } from 'dagre-d3-es/src/dagre-js/intersect/intersect-rect.js';
/** /**
* @param parent * @param parent
@@ -17,7 +18,7 @@ function question(parent, bbox, node) {
]; ];
const shapeSvg = insertPolygonShape(parent, s, s, points); const shapeSvg = insertPolygonShape(parent, s, s, points);
node.intersect = function (point) { node.intersect = function (point) {
return dagreD3.intersect.polygon(node, points, point); return intersectPolygon(node, points, point);
}; };
return shapeSvg; return shapeSvg;
} }
@@ -42,7 +43,7 @@ function hexagon(parent, bbox, node) {
]; ];
const shapeSvg = insertPolygonShape(parent, w, h, points); const shapeSvg = insertPolygonShape(parent, w, h, points);
node.intersect = function (point) { node.intersect = function (point) {
return dagreD3.intersect.polygon(node, points, point); return intersectPolygon(node, points, point);
}; };
return shapeSvg; return shapeSvg;
} }
@@ -64,7 +65,7 @@ function rect_left_inv_arrow(parent, bbox, node) {
]; ];
const shapeSvg = insertPolygonShape(parent, w, h, points); const shapeSvg = insertPolygonShape(parent, w, h, points);
node.intersect = function (point) { node.intersect = function (point) {
return dagreD3.intersect.polygon(node, points, point); return intersectPolygon(node, points, point);
}; };
return shapeSvg; return shapeSvg;
} }
@@ -85,7 +86,7 @@ function lean_right(parent, bbox, node) {
]; ];
const shapeSvg = insertPolygonShape(parent, w, h, points); const shapeSvg = insertPolygonShape(parent, w, h, points);
node.intersect = function (point) { node.intersect = function (point) {
return dagreD3.intersect.polygon(node, points, point); return intersectPolygon(node, points, point);
}; };
return shapeSvg; return shapeSvg;
} }
@@ -106,7 +107,7 @@ function lean_left(parent, bbox, node) {
]; ];
const shapeSvg = insertPolygonShape(parent, w, h, points); const shapeSvg = insertPolygonShape(parent, w, h, points);
node.intersect = function (point) { node.intersect = function (point) {
return dagreD3.intersect.polygon(node, points, point); return intersectPolygon(node, points, point);
}; };
return shapeSvg; return shapeSvg;
} }
@@ -127,7 +128,7 @@ function trapezoid(parent, bbox, node) {
]; ];
const shapeSvg = insertPolygonShape(parent, w, h, points); const shapeSvg = insertPolygonShape(parent, w, h, points);
node.intersect = function (point) { node.intersect = function (point) {
return dagreD3.intersect.polygon(node, points, point); return intersectPolygon(node, points, point);
}; };
return shapeSvg; return shapeSvg;
} }
@@ -148,7 +149,7 @@ function inv_trapezoid(parent, bbox, node) {
]; ];
const shapeSvg = insertPolygonShape(parent, w, h, points); const shapeSvg = insertPolygonShape(parent, w, h, points);
node.intersect = function (point) { node.intersect = function (point) {
return dagreD3.intersect.polygon(node, points, point); return intersectPolygon(node, points, point);
}; };
return shapeSvg; return shapeSvg;
} }
@@ -170,7 +171,7 @@ function rect_right_inv_arrow(parent, bbox, node) {
]; ];
const shapeSvg = insertPolygonShape(parent, w, h, points); const shapeSvg = insertPolygonShape(parent, w, h, points);
node.intersect = function (point) { node.intersect = function (point) {
return dagreD3.intersect.polygon(node, points, point); return intersectPolygon(node, points, point);
}; };
return shapeSvg; return shapeSvg;
} }
@@ -194,7 +195,7 @@ function stadium(parent, bbox, node) {
.attr('height', h); .attr('height', h);
node.intersect = function (point) { node.intersect = function (point) {
return dagreD3.intersect.rect(node, point); return intersectRect(node, point);
}; };
return shapeSvg; return shapeSvg;
} }
@@ -221,7 +222,7 @@ function subroutine(parent, bbox, node) {
]; ];
const shapeSvg = insertPolygonShape(parent, w, h, points); const shapeSvg = insertPolygonShape(parent, w, h, points);
node.intersect = function (point) { node.intersect = function (point) {
return dagreD3.intersect.polygon(node, points, point); return intersectPolygon(node, points, point);
}; };
return shapeSvg; return shapeSvg;
} }
@@ -270,7 +271,7 @@ function cylinder(parent, bbox, node) {
.attr('transform', 'translate(' + -w / 2 + ',' + -(h / 2 + ry) + ')'); .attr('transform', 'translate(' + -w / 2 + ',' + -(h / 2 + ry) + ')');
node.intersect = function (point) { node.intersect = function (point) {
const pos = dagreD3.intersect.rect(node, point); const pos = intersectRect(node, point);
const x = pos.x - node.x; const x = pos.x - node.x;
if ( if (

View File

@@ -10,6 +10,8 @@ import {
getAccDescription, getAccDescription,
setAccDescription, setAccDescription,
clear as commonClear, clear as commonClear,
setDiagramTitle,
getDiagramTitle,
} from '../../commonDb'; } from '../../commonDb';
const MERMAID_DOM_ID_PREFIX = 'flowchart-'; const MERMAID_DOM_ID_PREFIX = 'flowchart-';
@@ -785,4 +787,6 @@ export default {
}, },
exists, exists,
makeUniq, makeUniq,
setDiagramTitle,
getDiagramTitle,
}; };

View File

@@ -1,11 +1,12 @@
import graphlib from 'graphlib'; import * as graphlib from 'dagre-d3-es/src/graphlib';
import { select, curveLinear, selectAll } from 'd3'; import { select, curveLinear, selectAll } from 'd3';
import flowDb from './flowDb'; import flowDb from './flowDb';
import { getConfig } from '../../config'; import { getConfig } from '../../config';
import utils from '../../utils';
import { render } from '../../dagre-wrapper/index.js'; import { render } from '../../dagre-wrapper/index.js';
import addHtmlLabel from 'dagre-d3/lib/label/add-html-label.js'; import { addHtmlLabel } from 'dagre-d3-es/src/dagre-js/label/add-html-label.js';
import { log } from '../../logger'; import { log } from '../../logger';
import common, { evaluate } from '../common/common'; import common, { evaluate } from '../common/common';
import { interpolateToCurve, getStylesFromArray } from '../../utils'; import { interpolateToCurve, getStylesFromArray } from '../../utils';
@@ -437,6 +438,8 @@ export const draw = function (text, id, _version, diagObj) {
const element = root.select('#' + id + ' g'); const element = root.select('#' + id + ' g');
render(element, g, ['point', 'circle', 'cross'], 'flowchart', id); render(element, g, ['point', 'circle', 'cross'], 'flowchart', id);
utils.insertTitle(svg, 'flowchartTitleText', conf.titleTopMargin, diagObj.db.getDiagramTitle());
setupGraphViewbox(g, svg, conf.diagramPadding, conf.useMaxWidth); setupGraphViewbox(g, svg, conf.diagramPadding, conf.useMaxWidth);
// Index nodes // Index nodes

View File

@@ -1,8 +1,9 @@
import graphlib from 'graphlib'; import * as graphlib from 'dagre-d3-es/src/graphlib';
import { select, curveLinear, selectAll } from 'd3'; import { select, curveLinear, selectAll } from 'd3';
import { getConfig } from '../../config'; import { getConfig } from '../../config';
import dagreD3 from 'dagre-d3'; import { render as Render } from 'dagre-d3-es';
import addHtmlLabel from 'dagre-d3/lib/label/add-html-label.js'; import { applyStyle } from 'dagre-d3-es/src/dagre-js/util.js';
import { addHtmlLabel } from 'dagre-d3-es/src/dagre-js/label/add-html-label.js';
import { log } from '../../logger'; import { log } from '../../logger';
import common, { evaluate } from '../common/common'; import common, { evaluate } from '../common/common';
import { interpolateToCurve, getStylesFromArray } from '../../utils'; import { interpolateToCurve, getStylesFromArray } from '../../utils';
@@ -370,7 +371,6 @@ export const draw = function (text, id, _version, diagObj) {
addEdges(edges, g, diagObj); addEdges(edges, g, diagObj);
// Create the renderer // Create the renderer
const Render = dagreD3.render;
const render = new Render(); const render = new Render();
// Add custom shapes // Add custom shapes
@@ -390,7 +390,7 @@ export const draw = function (text, id, _version, diagObj) {
.attr('orient', 'auto'); .attr('orient', 'auto');
const path = marker.append('path').attr('d', 'M 0 0 L 0 0 L 0 0 z'); const path = marker.append('path').attr('d', 'M 0 0 L 0 0 L 0 0 z');
dagreD3.util.applyStyle(path, edge[type + 'Style']); applyStyle(path, edge[type + 'Style']);
}; };
// Override normal arrowhead defined in d3. Remove style & add class to allow css styling. // Override normal arrowhead defined in d3. Remove style & add class to allow css styling.

View File

@@ -1,6 +1,6 @@
import flowDb from '../flowDb'; import flowDb from '../flowDb';
import flow from './flow'; import flow from './flow';
import filter from 'lodash/filter'; import filter from 'lodash-es/filter';
import { setConfig } from '../../../config'; import { setConfig } from '../../../config';
setConfig({ setConfig({

View File

@@ -1,6 +1,6 @@
import flowDb from '../flowDb'; import flowDb from '../flowDb';
import flow from './flow'; import flow from './flow';
import filter from 'lodash/filter'; import filter from 'lodash-es/filter';
import { setConfig } from '../../../config'; import { setConfig } from '../../../config';
setConfig({ setConfig({

View File

@@ -103,6 +103,12 @@ const getStyles = (options: FlowChartStyleOptions) =>
pointer-events: none; pointer-events: none;
z-index: 100; z-index: 100;
} }
.flowchartTitleText {
text-anchor: middle;
font-size: 18px;
fill: ${options.textColor};
}
`; `;
export default getStyles; export default getStyles;

View File

@@ -10,6 +10,8 @@ import {
getAccDescription, getAccDescription,
setAccDescription, setAccDescription,
clear as commonClear, clear as commonClear,
setDiagramTitle,
getDiagramTitle,
} from '../../commonDb'; } from '../../commonDb';
let mainBranchName = getConfig().gitGraph.mainBranchName; let mainBranchName = getConfig().gitGraph.mainBranchName;
@@ -529,5 +531,7 @@ export default {
getAccTitle, getAccTitle,
getAccDescription, getAccDescription,
setAccDescription, setAccDescription,
setDiagramTitle,
getDiagramTitle,
commitType, commitType,
}; };

View File

@@ -1,6 +1,7 @@
import { select } from 'd3'; import { select } from 'd3';
import { getConfig, setupGraphViewbox } from '../../diagram-api/diagramAPI'; import { getConfig, setupGraphViewbox } from '../../diagram-api/diagramAPI';
import { log } from '../../logger'; import { log } from '../../logger';
import utils from '../../utils';
import addSVGAccessibilityFields from '../../accessibility'; import addSVGAccessibilityFields from '../../accessibility';
let allCommitsDict = {}; let allCommitsDict = {};
@@ -521,6 +522,12 @@ export const draw = function (txt, id, ver, diagObj) {
} }
drawArrows(diagram, allCommitsDict); drawArrows(diagram, allCommitsDict);
drawCommits(diagram, allCommitsDict, true); drawCommits(diagram, allCommitsDict, true);
utils.insertTitle(
diagram,
'gitTitleText',
gitGraphConfig.titleTopMargin,
diagObj.db.getDiagramTitle()
);
// Setup the view box and size of the svg element // Setup the view box and size of the svg element
setupGraphViewbox( setupGraphViewbox(

View File

@@ -51,6 +51,11 @@ const getStyles = (options) =>
} }
.arrow { stroke-width: 8; stroke-linecap: round; fill: none} .arrow { stroke-width: 8; stroke-linecap: round; fill: none}
.gitTitleText {
text-anchor: middle;
font-size: 18px;
fill: ${options.textColor};
}
} }
`; `;

View File

@@ -1,5 +1,6 @@
import type { DiagramDetector } from '../../diagram-api/types'; import type { DiagramDetector } from '../../diagram-api/types';
export const pieDetector: DiagramDetector = (txt) => { export const pieDetector: DiagramDetector = (txt) => {
return txt.match(/^\s*pie/) !== null; const logOutput = txt.match(/^\s*pie/) !== null || txt.match(/^\s*bar/) !== null;
return logOutput;
}; };

View File

@@ -157,11 +157,11 @@ export const draw = (txt, id, _version, diagObj) => {
.append('g') .append('g')
.attr('class', 'legend') .attr('class', 'legend')
.attr('transform', function (d, i) { .attr('transform', function (d, i) {
var height = legendRectSize + legendSpacing; const height = legendRectSize + legendSpacing;
var offset = (height * color.domain().length) / 2; const offset = (height * color.domain().length) / 2;
var horz = 12 * legendRectSize; const horizontal = 12 * legendRectSize;
var vert = i * height - offset; const vertical = i * height - offset;
return 'translate(' + horz + ',' + vert + ')'; return 'translate(' + horizontal + ',' + vertical + ')';
}); });
legend legend

View File

@@ -1,6 +1,6 @@
import { line, select } from 'd3'; import { line, select } from 'd3';
import dagre from 'dagre'; import { layout as dagreLayout } from 'dagre-d3-es/src/dagre/index.js';
import graphlib from 'graphlib'; import * as graphlib from 'dagre-d3-es/src/graphlib/index.js';
import { log } from '../../logger'; import { log } from '../../logger';
import { configureSvgSize } from '../../setupGraphViewbox'; import { configureSvgSize } from '../../setupGraphViewbox';
import common from '../common/common'; import common from '../common/common';
@@ -348,7 +348,7 @@ export const draw = (text, id, _version, diagObj) => {
drawReqs(requirements, g, svg); drawReqs(requirements, g, svg);
drawElements(elements, g, svg); drawElements(elements, g, svg);
addRelationships(relationships, g); addRelationships(relationships, g);
dagre.layout(g); dagreLayout(g);
adjustEntities(svg, g); adjustEntities(svg, g);
relationships.forEach(function (rel) { relationships.forEach(function (rel) {

View File

@@ -9,6 +9,8 @@ import {
getAccDescription, getAccDescription,
setAccDescription, setAccDescription,
clear as commonClear, clear as commonClear,
setDiagramTitle,
getDiagramTitle,
} from '../../commonDb'; } from '../../commonDb';
import { import {
@@ -571,4 +573,6 @@ export default {
addStyleClass, addStyleClass,
setCssClass, setCssClass,
addDescription, addDescription,
setDiagramTitle,
getDiagramTitle,
}; };

View File

@@ -1,10 +1,11 @@
import graphlib from 'graphlib'; import * as graphlib from 'dagre-d3-es/src/graphlib';
import { select } from 'd3'; import { select } from 'd3';
import { getConfig } from '../../config'; import { getConfig } from '../../config';
import { render } from '../../dagre-wrapper/index.js'; import { render } from '../../dagre-wrapper/index.js';
import { log } from '../../logger'; import { log } from '../../logger';
import { configureSvgSize } from '../../setupGraphViewbox'; import { configureSvgSize } from '../../setupGraphViewbox';
import common from '../common/common'; import common from '../common/common';
import utils from '../../utils';
import addSVGAccessibilityFields from '../../accessibility'; import addSVGAccessibilityFields from '../../accessibility';
import { import {
DEFAULT_DIAGRAM_DIRECTION, DEFAULT_DIAGRAM_DIRECTION,
@@ -437,8 +438,9 @@ export const draw = function (text, id, _version, diag) {
const padding = 8; const padding = 8;
const bounds = svg.node().getBBox(); utils.insertTitle(svg, 'statediagramTitleText', conf.titleTopMargin, diag.db.getDiagramTitle());
const bounds = svg.node().getBBox();
const width = bounds.width + padding * 2; const width = bounds.width + padding * 2;
const height = bounds.height + padding * 2; const height = bounds.height + padding * 2;

View File

@@ -1,6 +1,6 @@
import { select } from 'd3'; import { select } from 'd3';
import dagre from 'dagre'; import { layout as dagreLayout } from 'dagre-d3-es/src/dagre/index.js';
import graphlib from 'graphlib'; import * as graphlib from 'dagre-d3-es/src/graphlib/index.js';
import { log } from '../../logger'; import { log } from '../../logger';
import common from '../common/common'; import common from '../common/common';
import { drawState, addTitleAndBox, drawEdge } from './shapes'; import { drawState, addTitleAndBox, drawEdge } from './shapes';
@@ -239,7 +239,7 @@ const renderDoc = (doc, diagram, parentId, altBkg, root, domDocument, diagObj) =
); );
}); });
dagre.layout(graph); dagreLayout(graph);
log.debug('Graph after layout', graph.nodes()); log.debug('Graph after layout', graph.nodes());
const svgElem = diagram.node(); const svgElem = diagram.node();

View File

@@ -194,6 +194,12 @@ g.stateGroup line {
stroke: ${options.lineColor}; stroke: ${options.lineColor};
stroke-width: 1; stroke-width: 1;
} }
.statediagramTitleText {
text-anchor: middle;
font-size: 18px;
fill: ${options.textColor};
}
`; `;
export default getStyles; export default getStyles;

View File

@@ -2,7 +2,7 @@
// Update https://github.com/mermaid-js/mermaid/blob/18c27c6f1d0537a738cbd95898df301b83c38ffc/packages/mermaid/src/docs.mts#L246 once fixed // Update https://github.com/mermaid-js/mermaid/blob/18c27c6f1d0537a738cbd95898df301b83c38ffc/packages/mermaid/src/docs.mts#L246 once fixed
import { expect, test } from 'vitest'; import { expect, test } from 'vitest';
import { getRedirect } from './.vitepress/theme/redirect'; import { getRedirect } from './redirect';
test.each([ test.each([
['http://localhost:1234/mermaid/#/flowchart.md', 'syntax/flowchart.html'], ['http://localhost:1234/mermaid/#/flowchart.md', 'syntax/flowchart.html'],

View File

@@ -347,7 +347,7 @@ This is the preferred way of configuring mermaid.
## Using the mermaid object ## Using the mermaid object
Is it possible to set some configuration via the mermaid object. The two parameters that are supported using this It is possible to set some configuration via the mermaid object. The two parameters that are supported using this
approach are: approach are:
- mermaid.startOnLoad - mermaid.startOnLoad

View File

@@ -8,7 +8,7 @@ It is a JavaScript based diagramming and charting tool that renders Markdown-ins
<img src="/header.png" alt="" /> <img src="/header.png" alt="" />
[![Build CI Status](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml/badge.svg)](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml) [![NPM](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid) [![Coverage Status](https://coveralls.io/repos/github/mermaid-js/mermaid/badge.svg?branch=master)](https://coveralls.io/github/mermaid-js/mermaid?branch=master) [![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid) [![NPM](https://img.shields.io/npm/dm/mermaid)](https://www.npmjs.com/package/mermaid) [![Join our Slack!](https://img.shields.io/static/v1?message=join%20chat&color=9cf&logo=slack&label=slack)](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE) [![Twitter Follow](https://img.shields.io/twitter/follow/mermaidjs_?style=social)](https://twitter.com/mermaidjs_) [![Build CI Status](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml/badge.svg)](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml) [![NPM](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid) [![npm minified gzipped bundle size](https://img.shields.io/bundlephobia/minzip/mermaid)](https://bundlephobia.com/package/mermaid) [![Coverage Status](https://coveralls.io/repos/github/mermaid-js/mermaid/badge.svg?branch=master)](https://coveralls.io/github/mermaid-js/mermaid?branch=master) [![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid) [![NPM](https://img.shields.io/npm/dm/mermaid)](https://www.npmjs.com/package/mermaid) [![Join our Slack!](https://img.shields.io/static/v1?message=join%20chat&color=9cf&logo=slack&label=slack)](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE) [![Twitter Follow](https://img.shields.io/twitter/follow/mermaidjs_?style=social)](https://twitter.com/mermaidjs_)
<!-- Mermaid book banner --> <!-- Mermaid book banner -->

View File

@@ -33,6 +33,7 @@ They also serve as proof of concept, for the variety of things that can be built
- [markdown-for-mermaid-plugin](https://github.com/jamieh-mongolian/markdown-for-mermaid-plugin) - [markdown-for-mermaid-plugin](https://github.com/jamieh-mongolian/markdown-for-mermaid-plugin)
- [JetBrains IDE eg Pycharm](https://www.jetbrains.com/go/guide/tips/mermaid-js-support-in-markdown/) - [JetBrains IDE eg Pycharm](https://www.jetbrains.com/go/guide/tips/mermaid-js-support-in-markdown/)
- [mermerd](https://github.com/KarnerTh/mermerd) - [mermerd](https://github.com/KarnerTh/mermerd)
- Visual Studio Code [Polyglot Interactive Notebooks](https://github.com/dotnet/interactive#net-interactive)
## CRM/ERP/Similar ## CRM/ERP/Similar
@@ -115,6 +116,7 @@ They also serve as proof of concept, for the variety of things that can be built
- [Draw.io](https://draw.io) - [Plugin](https://github.com/nopeslide/drawio_mermaid_plugin) - [Draw.io](https://draw.io) - [Plugin](https://github.com/nopeslide/drawio_mermaid_plugin)
- [Inkdrop](https://www.inkdrop.app) - [Plugin](https://github.com/inkdropapp/inkdrop-mermaid) - [Inkdrop](https://www.inkdrop.app) - [Plugin](https://github.com/inkdropapp/inkdrop-mermaid)
- [Vim](https://www.vim.org) - [Vim](https://www.vim.org)
- [Official Vim Syntax and ftplugin](https://github.com/craigmac/vim-mermaid)
- [Vim Diagram Syntax](https://github.com/zhaozg/vim-diagram) - [Vim Diagram Syntax](https://github.com/zhaozg/vim-diagram)
- [GNU Emacs](https://www.gnu.org/software/emacs/) - [GNU Emacs](https://www.gnu.org/software/emacs/)
- [Major mode for .mmd files](https://github.com/abrochard/mermaid-mode) - [Major mode for .mmd files](https://github.com/abrochard/mermaid-mode)

View File

@@ -318,7 +318,7 @@ UpdateRelStyle(customerA, bankA, $offsetY="60")
Container(mobile, "Mobile App", "Xamarin", "Provides a limited subset of the Internet Banking functionality to customers via their mobile device.") Container(mobile, "Mobile App", "Xamarin", "Provides a limited subset of the Internet Banking functionality to customers via their mobile device.")
} }
Deployment_Node(comp, "Customer's computer", "Mircosoft Windows or Apple macOS"){ Deployment_Node(comp, "Customer's computer", "Microsoft Windows or Apple macOS"){
Deployment_Node(browser, "Web Browser", "Google Chrome, Mozilla Firefox,<br/> Apple Safari or Microsoft Edge"){ Deployment_Node(browser, "Web Browser", "Google Chrome, Mozilla Firefox,<br/> Apple Safari or Microsoft Edge"){
Container(spa, "Single Page Application", "JavaScript and Angular", "Provides all of the Internet Banking functionality to customers via their web browser.") Container(spa, "Single Page Application", "JavaScript and Angular", "Provides all of the Internet Banking functionality to customers via their web browser.")
} }

View File

@@ -8,6 +8,9 @@ The class diagram is the main building block of object-oriented modeling. It is
Mermaid can render class diagrams. Mermaid can render class diagrams.
```mermaid-example ```mermaid-example
---
title: Animal example
---
classDiagram classDiagram
note "From Duck till Zebra" note "From Duck till Zebra"
Animal <|-- Duck Animal <|-- Duck
@@ -45,6 +48,9 @@ A single instance of a class in the diagram contains three compartments:
- The bottom compartment contains the operations the class can execute. They are also left-aligned and the first letter is lowercase. - The bottom compartment contains the operations the class can execute. They are also left-aligned and the first letter is lowercase.
```mermaid-example ```mermaid-example
---
title: Bank example
---
classDiagram classDiagram
class BankAccount class BankAccount
BankAccount : +String owner BankAccount : +String owner
@@ -379,7 +385,7 @@ click className href "url" "tooltip"
## Notes ## Notes
It is possible to add notes on digram using `note "line1\nline2"` or note for class using `note for class "line1\nline2"` It is possible to add notes on diagram using `note "line1\nline2"` or note for class using `note for class "line1\nline2"`
### Examples ### Examples

View File

@@ -7,6 +7,9 @@ Note that practitioners of ER modelling almost always refer to _entity types_ si
Mermaid can render ER diagrams Mermaid can render ER diagrams
```mermaid-example ```mermaid-example
---
title: Order example
---
erDiagram erDiagram
CUSTOMER ||--o{ ORDER : places CUSTOMER ||--o{ ORDER : places
ORDER ||--|{ LINE-ITEM : contains ORDER ||--|{ LINE-ITEM : contains

View File

@@ -9,6 +9,9 @@ It can also accommodate different arrow types, multi directional arrows, and lin
### A node (default) ### A node (default)
```mermaid-example ```mermaid-example
---
title: Node
---
flowchart LR flowchart LR
id id
``` ```
@@ -22,6 +25,9 @@ found for the node that will be used. Also if you define edges for the node late
one previously defined will be used when rendering the box. one previously defined will be used when rendering the box.
```mermaid-example ```mermaid-example
---
title: Node with text
---
flowchart LR flowchart LR
id1[This is the text in the box] id1[This is the text in the box]
``` ```
@@ -665,7 +671,7 @@ flowchart LR
## Configuration... ## Configuration...
Is it possible to adjust the width of the rendered flowchart. It is possible to adjust the width of the rendered flowchart.
This is done by defining **mermaid.flowchartConfig** or by the CLI to use a JSON file with the configuration. How to use the CLI is described in the mermaidCLI page. This is done by defining **mermaid.flowchartConfig** or by the CLI to use a JSON file with the configuration. How to use the CLI is described in the mermaidCLI page.
mermaid.flowchartConfig can be set to a JSON string with config parameters or the corresponding object. mermaid.flowchartConfig can be set to a JSON string with config parameters or the corresponding object.

View File

@@ -7,17 +7,20 @@ These kind of diagram are particularly helpful to developers and devops teams to
Mermaid can render Git diagrams Mermaid can render Git diagrams
```mermaid-example ```mermaid-example
gitGraph ---
commit title: Example Git diagram
commit ---
branch develop gitGraph
checkout develop commit
commit commit
commit branch develop
checkout main checkout develop
merge develop commit
commit commit
commit checkout main
merge develop
commit
commit
``` ```
In Mermaid, we support the basic git operations like: In Mermaid, we support the basic git operations like:

View File

@@ -15,7 +15,7 @@ mindmap
Popularisation Popularisation
British popular psychology author Tony Buzan British popular psychology author Tony Buzan
Research Research
On effectivness<br/>and eatures On effectiveness<br/>and features
On Automatic creation On Automatic creation
Uses Uses
Creative techniques Creative techniques
@@ -94,6 +94,13 @@ mindmap
id)I am a cloud( id)I am a cloud(
``` ```
### Hexagon
```mermaid-example
mindmap
id{{I am a hexagon}}
```
### Default ### Default
```mermaid-example ```mermaid-example

View File

@@ -22,7 +22,7 @@ Drawing a pie chart is really simple in mermaid.
- Followed by dataSet. Pie slices will be ordered clockwise in the same order as the labels. - Followed by dataSet. Pie slices will be ordered clockwise in the same order as the labels.
- `label` for a section in the pie diagram within `" "` quotes. - `label` for a section in the pie diagram within `" "` quotes.
- Followed by `:` colon as separator - Followed by `:` colon as separator
- Followed by `positive numeric value` (supported upto two decimal places) - Followed by `positive numeric value` (supported up to two decimal places)
[pie] [showData] (OPTIONAL) [pie] [showData] (OPTIONAL)
[title] [titlevalue] (OPTIONAL) [title] [titlevalue] (OPTIONAL)

View File

@@ -534,7 +534,7 @@ text.actor {
## Configuration ## Configuration
Is it possible to adjust the margins for rendering the sequence diagram. It is possible to adjust the margins for rendering the sequence diagram.
This is done by defining `mermaid.sequenceConfig` or by the CLI to use a json file with the configuration. This is done by defining `mermaid.sequenceConfig` or by the CLI to use a json file with the configuration.
How to use the CLI is described in the [mermaidCLI](../config/mermaidCLI.md) page. How to use the CLI is described in the [mermaidCLI](../config/mermaidCLI.md) page.

View File

@@ -1,10 +1,16 @@
# State diagrams # State diagrams
> "A state diagram is a type of diagram used in computer science and related fields to describe the behavior of systems. State diagrams require that the system described is composed of a finite number of states; sometimes, this is indeed the case, while at other times this is a reasonable abstraction." Wikipedia > "A state diagram is a type of diagram used in computer science and related fields to describe the behavior of systems.
> State diagrams require that the system described is composed of a finite number of states; sometimes, this is indeed the
> case, while at other times this is a reasonable abstraction." Wikipedia
Mermaid can render state diagrams. The syntax tries to be compliant with the syntax used in plantUml as this will make it easier for users to share diagrams between mermaid and plantUml. Mermaid can render state diagrams. The syntax tries to be compliant with the syntax used in plantUml as this will make
it easier for users to share diagrams between mermaid and plantUml.
```mermaid-example ```mermaid-example
---
title: Simple sample
---
stateDiagram-v2 stateDiagram-v2
[*] --> Still [*] --> Still
Still --> [*] Still --> [*]
@@ -28,15 +34,18 @@ stateDiagram
Crash --> [*] Crash --> [*]
``` ```
In state diagrams systems are described in terms of its states and how the systems state can change to another state via a transitions. The example diagram above shows three states **Still**, **Moving** and **Crash**. You start in the state of Still. From Still you can change the state to Moving. In Moving you can change the state either back to Still or to Crash. There is no transition from Still to Crash. In state diagrams systems are described in terms of _states_ and how one _state_ can change to another _state_ via
a _transition._ The example diagram above shows three states: **Still**, **Moving** and **Crash**. You start in the
**Still** state. From **Still** you can change to the **Moving** state. From **Moving** you can change either back to the **Still** state or to
the **Crash** state. There is no transition from **Still** to **Crash**. (You can't crash if you're still.)
## States ## States
A state can be declared in multiple ways. The simplest way is to define a state id as a description. A state can be declared in multiple ways. The simplest way is to define a state with just an id:
```mermaid-example ```mermaid-example
stateDiagram-v2 stateDiagram-v2
s1 stateId
``` ```
Another way is by using the state keyword with a description as per below: Another way is by using the state keyword with a description as per below:
@@ -57,14 +66,15 @@ stateDiagram-v2
Transitions are path/edges when one state passes into another. This is represented using text arrow, "\-\-\>". Transitions are path/edges when one state passes into another. This is represented using text arrow, "\-\-\>".
When you define a transition between two states and the states are not already defined the undefined states are defined with the id from the transition. You can later add descriptions to states defined this way. When you define a transition between two states and the states are not already defined, the undefined states are defined
with the id from the transition. You can later add descriptions to states defined this way.
```mermaid-example ```mermaid-example
stateDiagram-v2 stateDiagram-v2
s1 --> s2 s1 --> s2
``` ```
It is possible to add text to a transition. To describe what it represents. It is possible to add text to a transition to describe what it represents:
```mermaid-example ```mermaid-example
stateDiagram-v2 stateDiagram-v2
@@ -73,7 +83,8 @@ stateDiagram-v2
## Start and End ## Start and End
There are two special states indicating the start and stop of the diagram. These are written with the [\*] syntax and the direction of the transition to it defines it either as a start or a stop state. There are two special states indicating the start and stop of the diagram. These are written with the [\*] syntax and
the direction of the transition to it defines it either as a start or a stop state.
```mermaid-example ```mermaid-example
stateDiagram-v2 stateDiagram-v2
@@ -83,10 +94,11 @@ stateDiagram-v2
## Composite states ## Composite states
In a real world use of state diagrams you often end up with diagrams that are multi-dimensional as one state can In a real world use of state diagrams you often end up with diagrams that are multidimensional as one state can
have several internal states. These are called composite states in this terminology. have several internal states. These are called composite states in this terminology.
In order to define a composite state you need to use the state keyword followed by an id and the body of the composite state between \{\}. See the example below: In order to define a composite state you need to use the state keyword followed by an id and the body of the composite
state between \{\}. See the example below:
```mermaid-example ```mermaid-example
stateDiagram-v2 stateDiagram-v2
@@ -175,7 +187,7 @@ It is possible to specify a fork in the diagram using &lt;&lt;fork&gt;&gt; &lt;&
## Notes ## Notes
Sometimes nothing says it better then a Post-it note. That is also the case in state diagrams. Sometimes nothing says it better than a Post-it note. That is also the case in state diagrams.
Here you can choose to put the note to the _right of_ or to the _left of_ a node. Here you can choose to put the note to the _right of_ or to the _left of_ a node.
@@ -215,7 +227,8 @@ stateDiagram-v2
## Setting the direction of the diagram ## Setting the direction of the diagram
With state diagrams you can use the direction statement to set the direction which the diagram will render like in this example. With state diagrams you can use the direction statement to set the direction which the diagram will render like in this
example.
```mermaid-example ```mermaid-example
stateDiagram stateDiagram
@@ -232,7 +245,9 @@ stateDiagram
## Comments ## Comments
Comments can be entered within a state diagram chart, which will be ignored by the parser. Comments need to be on their own line, and must be prefaced with `%%` (double percent signs). Any text after the start of the comment to the next newline will be treated as a comment, including any diagram syntax Comments can be entered within a state diagram chart, which will be ignored by the parser. Comments need to be on their
own line, and must be prefaced with `%%` (double percent signs). Any text after the start of the comment to the next
newline will be treated as a comment, including any diagram syntax
```mmd ```mmd
stateDiagram-v2 stateDiagram-v2
@@ -245,16 +260,153 @@ stateDiagram-v2
Crash --> [*] Crash --> [*]
``` ```
## Styling ## Styling with classDefs
Styling of the a state diagram is done by defining a number of css classes. During rendering these classes are extracted from the file located at src/themes/state.scss As with other diagrams (like flowcharts), you can define a style in the diagram itself and apply that named style to a
state or states in the diagram.
**These are the current limitations with state diagram classDefs:**
1. Cannot be applied to start or end states
2. Cannot be applied to or within composite states
_These are in development and will be available in a future version._
You define a style using the `classDef` keyword, which is short for "class definition" (where "class" means something
like a _CSS class_)
followed by _a name for the style,_
and then one or more _property-value pairs_. Each _property-value pair_ is
a _[valid CSS property name](https://www.w3.org/TR/CSS/#properties)_ followed by a colon (`:`) and then a _value._
Here is an example of a classDef with just one property-value pair:
```
classDef movement font-style:italic;
```
where
- the _name_ of the style is `movement`
- the only _property_ is `font-style` and its _value_ is `italic`
If you want to have more than one _property-value pair_ then you put a comma (`,`) between each _property-value pair._
Here is an example with three property-value pairs:
```
classDef badBadEvent fill:#f00,color:white,font-weight:bold,stroke-width:2px,stroke:yellow
```
where
- the _name_ of the style is `badBadEvent`
- the first _property_ is `fill` and its _value_ is `#f00`
- the second _property_ is `color` and its _value_ is `white`
- the third _property_ is `font-weight` and its _value_ is `bold`
- the fourth _property_ is `stroke-width` and its _value_ is `2px`
- the fifth _property_ is `stroke` and its _value_ is `yello`
### Apply classDef styles to states
There are two ways to apply a `classDef` style to a state:
1. use the `class` keyword to apply a classDef style to one or more states in a single statement, or
2. use the `:::` operator to apply a classDef style to a state as it is being used in a transition statement (e.g. with an arrow
to/from another state)
#### 1. `class` statement
A `class` statement tells Mermaid to apply the named classDef to one or more classes. The form is:
```text
class [one or more state names, separated by commas] [name of a style defined with classDef]
```
Here is an example applying the `badBadEvent` style to a state named `Crash`:
```text
class Crash badBadEvent
```
Here is an example applying the `movement` style to the two states `Moving` and `Crash`:
```text
class Moving, Crash movement
```
Here is a diagram that shows the examples in use. Note that the `Crash` state has two classDef styles applied: `movement`
and `badBadEvent`
```mermaid-example
stateDiagram
direction TB
accTitle: This is the accessible title
accDescr: This is an accessible description
classDef notMoving fill:white
classDef movement font-style:italic
classDef badBadEvent fill:#f00,color:white,font-weight:bold,stroke-width:2px,stroke:yellow
[*]--> Still
Still --> [*]
Still --> Moving
Moving --> Still
Moving --> Crash
Crash --> [*]
class Still notMoving
class Moving, Crash movement
class Crash badBadEvent
class end badBadEvent
```
#### 2. `:::` operator to apply a style to a state
You can apply a classDef style to a state using the `:::` (three colons) operator. The syntax is
```text
[state]:::[style name]
```
You can use this in a diagram within a statement using a class. This includes the start and end states. For example:
```mermaid-example
stateDiagram
direction TB
accTitle: This is the accessible title
accDescr: This is an accessible description
classDef notMoving fill:white
classDef movement font-style:italic;
classDef badBadEvent fill:#f00,color:white,font-weight:bold,stroke-width:2px,stroke:yellow
[*] --> Still:::notMoving
Still --> [*]
Still --> Moving:::movement
Moving --> Still
Moving --> Crash:::movement
Crash:::badBadEvent --> [*]
```
## Spaces in state names ## Spaces in state names
Spaces can be added to a state by defining it at the top and referencing the acronym later. Spaces can be added to a state by first defining the state with an id and then referencing the id later.
In the following example there is a state with the id **yswsii** and description **Your state with spaces in it**.
After it has been defined, **yswsii** is used in the diagram in the first transition (`[*] --> yswsii`)
and also in the transition to **YetAnotherState** (`yswsii --> YetAnotherState`).
(**yswsii** has been styled so that it is different from the other states.)
```mermaid-example ```mermaid-example
stateDiagram-v2 stateDiagram
Yswsii: Your state with spaces in it classDef yourState font-style:italic,font-weight:bold,fill:white
[*] --> Yswsii
yswsii: Your state with spaces in it
[*] --> yswsii:::yourState
[*] --> SomeOtherState
SomeOtherState --> YetAnotherState
yswsii --> YetAnotherState
YetAnotherState --> [*]
``` ```

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