Merge branch 'develop' into feature/4269_add_xychart

This commit is contained in:
Subhash Halder 2023-08-20 18:09:51 +05:30
commit 5a64cec9ca
152 changed files with 7053 additions and 6171 deletions

44
.github/lychee.toml vendored Normal file
View File

@ -0,0 +1,44 @@
############################# Display #############################
# Verbose program output
# Accepts log level: "error", "warn", "info", "debug", "trace"
verbose = "debug"
# Don't show interactive progress bar while checking links.
no_progress = true
############################# Cache ###############################
# Enable link caching. This can be helpful to avoid checking the same links on
# multiple runs.
cache = true
# Discard all cached requests older than this duration.
max_cache_age = "1d"
############################# Requests ############################
# Comma-separated list of accepted status codes for valid links.
accept = [200, 429]
############################# Exclusions ##########################
# Exclude URLs and mail addresses from checking (supports regex).
exclude = [
# Network error: Forbidden
"https://codepen.io",
# Timeout error, maybe Twitter has anti-bot defenses against GitHub's CI servers?
"https://twitter.com/mermaidjs_",
# Don't check files that are generated during the build via `pnpm docs:code`
'packages/mermaid/src/docs/config/setup/*',
# Ignore slack invite
"https://join.slack.com/"
]
# Exclude all private IPs from checking.
# Equivalent to setting `exclude_private`, `exclude_link_local`, and
# `exclude_loopback` to true.
exclude_all_private = true

View File

@ -13,6 +13,6 @@ Describe the way your implementation works or what design decisions you made if
Make sure you
- [ ] :book: have read the [contribution guidelines](https://github.com/mermaid-js/mermaid/blob/develop/CONTRIBUTING.md)
- [ ] :computer: have added unit/e2e tests (if appropriate)
- [ ] :notebook: have added documentation (if appropriate)
- [ ] :computer: have added necessary unit/e2e tests.
- [ ] :notebook: have added documentation. Make sure [`MERMAID_RELEASE_VERSION`](https://github.com/mermaid-js/mermaid/blob/develop/packages/mermaid/src/docs/community/development.md#3-update-documentation) is used for all new features.
- [ ] :bookmark: targeted `develop` branch

View File

@ -1,6 +1,10 @@
name: Build Vitepress docs
on:
push:
branches:
- master
- release/*
pull_request:
merge_group:
@ -25,5 +29,9 @@ jobs:
- name: Install Packages
run: pnpm install --frozen-lockfile
- name: Verify release verion
if: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/heads/release')) }}
run: pnpm --filter mermaid run docs:verify-version
- name: Run Build
run: pnpm --filter mermaid run docs:build:vitepress

View File

@ -45,6 +45,7 @@ jobs:
env:
CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}
VITEST_COVERAGE: true
CYPRESS_COMMIT: ${{ github.sha }}
- name: Upload Coverage to Codecov
uses: codecov/codecov-action@v3
# Run step only pushes to develop and pull_requests

View File

@ -20,7 +20,7 @@ on:
- cron: '30 8 * * *'
jobs:
linkChecker:
link-checker:
runs-on: ubuntu-latest
permissions:
# lychee only uses the GITHUB_TOKEN to avoid rate-limiting
@ -39,10 +39,7 @@ jobs:
uses: lycheeverse/lychee-action@v1.8.0
with:
args: >-
--verbose
--no-progress
--cache
--max-cache-age 1d
--config .github/lychee.toml
packages/mermaid/src/docs/**/*.md
README.md
README.zh-CN.md

3
.gitignore vendored
View File

@ -43,3 +43,6 @@ stats/
**/contributor-names.json
.pnpm-store
.nyc_output
demos/dev/**
!/demos/dev/example.html

View File

@ -1,17 +0,0 @@
# These links are ignored by our link checker https://github.com/lycheeverse/lychee
# The file allows you to list multiple regular expressions for exclusion (one pattern per line).
# Network error: Forbidden
https://codepen.io
# Timeout error, maybe Twitter has anti-bot defenses against GitHub's CI servers?
https://twitter.com/mermaidjs_
# Don't check files that are generated during the build via `pnpm docs:code`
packages/mermaid/src/docs/config/setup/*
# Ignore localhost
http://localhost:3333/
# Ignore slack invite
https://join.slack.com/

2
.vscode/launch.json vendored
View File

@ -17,7 +17,7 @@
"name": "Docs generation",
"type": "node",
"request": "launch",
"args": ["src/docs.mts"],
"args": ["scripts/docs.cli.mts"],
"runtimeArgs": ["--loader", "ts-node/esm"],
"cwd": "${workspaceRoot}/packages/mermaid",
"skipFiles": ["<node_internals>/**", "**/node_modules/**"],

View File

@ -26,9 +26,14 @@ Install required packages:
```bash
# npx is required for first install as volta support for pnpm is not added yet.
npx pnpm install
pnpm test
pnpm test # run unit tests
pnpm dev # starts a dev server
```
Open <http://localhost:9000> in your browser after starting the dev server.
You can also duplicate the `example.html` file in `demos/dev`, rename it and add your own mermaid code to it.
That will be served at <http://localhost:9000/dev/your-file-name.html>.
### Docker
If you are using docker and docker-compose, you have self-documented `run` bash script, which is a convenient alias for docker-compose commands:
@ -64,7 +69,7 @@ eg: `feature/2945_state-diagram-new-arrow-florbs`, `bug/1123_fix_random_ugly_red
Documentation is necessary for all non bugfix/refactoring changes.
Only make changes to files are in [`/packages/mermaid/src/docs`](packages/mermaid/src/docs)
Only make changes to files that are in [`/packages/mermaid/src/docs`](packages/mermaid/src/docs)
**_DO NOT CHANGE FILES IN `/docs`_**

View File

@ -136,6 +136,7 @@
"tsdoc",
"tuleap",
"tylerlong",
"typora",
"ugge",
"unist",
"unocss",

View File

@ -1,93 +0,0 @@
const utf8ToB64 = (str) => {
return window.btoa(unescape(encodeURIComponent(str)));
};
const batchId = 'mermaid-batch' + new Date().getTime();
export const mermaidUrl = (graphStr, options, api) => {
const obj = {
code: graphStr,
mermaid: options,
};
const objStr = JSON.stringify(obj);
let url = 'http://localhost:9000/e2e.html?graph=' + utf8ToB64(objStr);
if (api) {
url = 'http://localhost:9000/xss.html?graph=' + graphStr;
}
if (options.listUrl) {
cy.log(options.listId, ' ', url);
}
return url;
};
export const imgSnapshotTest = (graphStr, _options = {}, api = false, validation = undefined) => {
cy.log(_options);
const options = Object.assign(_options);
if (!options.fontFamily) {
options.fontFamily = 'courier';
}
if (!options.sequence) {
options.sequence = {};
}
if (!options.sequence || (options.sequence && !options.sequence.actorFontFamily)) {
options.sequence.actorFontFamily = 'courier';
}
if (options.sequence && !options.sequence.noteFontFamily) {
options.sequence.noteFontFamily = 'courier';
}
options.sequence.actorFontFamily = 'courier';
options.sequence.noteFontFamily = 'courier';
options.sequence.messageFontFamily = 'courier';
if (options.sequence && !options.sequence.actorFontFamily) {
options.sequence.actorFontFamily = 'courier';
}
if (!options.fontSize) {
options.fontSize = '16px';
}
const url = mermaidUrl(graphStr, options, api);
openURLAndVerifyRendering(url, options, validation);
};
export const urlSnapshotTest = (url, _options, api = false, validation) => {
const options = Object.assign(_options);
openURLAndVerifyRendering(url, options, validation);
};
export const renderGraph = (graphStr, options, api) => {
const url = mermaidUrl(graphStr, options, api);
openURLAndVerifyRendering(url, options);
};
export const openURLAndVerifyRendering = (url, options, validation = undefined) => {
const useAppli = Cypress.env('useAppli');
const name = (options.name || cy.state('runnable').fullTitle()).replace(/\s+/g, '-');
if (useAppli) {
cy.log('Opening eyes ' + Cypress.spec.name + ' --- ' + name);
cy.eyesOpen({
appName: 'Mermaid',
testName: name,
batchName: Cypress.spec.name,
batchId: batchId + Cypress.spec.name,
});
}
cy.visit(url);
cy.window().should('have.property', 'rendered', true);
cy.get('svg').should('be.visible');
if (validation) {
cy.get('svg').should(validation);
}
if (useAppli) {
cy.log('Check eyes' + Cypress.spec.name);
cy.eyesCheckWindow('Click!');
cy.log('Closing eyes' + Cypress.spec.name);
cy.eyesClose();
} else {
cy.matchImageSnapshot(name);
}
};

132
cypress/helpers/util.ts Normal file
View File

@ -0,0 +1,132 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Buffer } from 'buffer';
import type { MermaidConfig } from '../../packages/mermaid/src/config.type.js';
interface CypressConfig {
listUrl?: boolean;
listId?: string;
name?: string;
}
type CypressMermaidConfig = MermaidConfig & CypressConfig;
interface CodeObject {
code: string;
mermaid: CypressMermaidConfig;
}
const utf8ToB64 = (str: string): string => {
return Buffer.from(decodeURIComponent(encodeURIComponent(str))).toString('base64');
};
const batchId: string = 'mermaid-batch-' + Cypress.env('CYPRESS_COMMIT') || Date.now().toString();
export const mermaidUrl = (
graphStr: string,
options: CypressMermaidConfig,
api: boolean
): string => {
const codeObject: CodeObject = {
code: graphStr,
mermaid: options,
};
const objStr: string = JSON.stringify(codeObject);
let url = `http://localhost:9000/e2e.html?graph=${utf8ToB64(objStr)}`;
if (api) {
url = `http://localhost:9000/xss.html?graph=${graphStr}`;
}
if (options.listUrl) {
cy.log(options.listId, ' ', url);
}
return url;
};
export const imgSnapshotTest = (
graphStr: string,
_options: CypressMermaidConfig = {},
api = false,
validation?: any
): void => {
cy.log(JSON.stringify(_options));
const options: CypressMermaidConfig = Object.assign(_options);
if (!options.fontFamily) {
options.fontFamily = 'courier';
}
if (!options.sequence) {
options.sequence = {};
}
if (!options.sequence || (options.sequence && !options.sequence.actorFontFamily)) {
options.sequence.actorFontFamily = 'courier';
}
if (options.sequence && !options.sequence.noteFontFamily) {
options.sequence.noteFontFamily = 'courier';
}
options.sequence.actorFontFamily = 'courier';
options.sequence.noteFontFamily = 'courier';
options.sequence.messageFontFamily = 'courier';
if (options.sequence && !options.sequence.actorFontFamily) {
options.sequence.actorFontFamily = 'courier';
}
if (!options.fontSize) {
options.fontSize = 16;
}
const url: string = mermaidUrl(graphStr, options, api);
openURLAndVerifyRendering(url, options, validation);
};
export const urlSnapshotTest = (
url: string,
_options: CypressMermaidConfig,
_api = false,
validation?: any
): void => {
const options: CypressMermaidConfig = Object.assign(_options);
openURLAndVerifyRendering(url, options, validation);
};
export const renderGraph = (
graphStr: string,
options: CypressMermaidConfig = {},
api = false
): void => {
const url: string = mermaidUrl(graphStr, options, api);
openURLAndVerifyRendering(url, options);
};
export const openURLAndVerifyRendering = (
url: string,
options: CypressMermaidConfig,
validation?: any
): void => {
const useAppli: boolean = Cypress.env('useAppli');
const name: string = (options.name || cy.state('runnable').fullTitle()).replace(/\s+/g, '-');
if (useAppli) {
cy.log(`Opening eyes ${Cypress.spec.name} --- ${name}`);
cy.eyesOpen({
appName: 'Mermaid',
testName: name,
batchName: Cypress.spec.name,
batchId: batchId + Cypress.spec.name,
});
}
cy.visit(url);
cy.window().should('have.property', 'rendered', true);
cy.get('svg').should('be.visible');
if (validation) {
cy.get('svg').should(validation);
}
if (useAppli) {
cy.log(`Check eyes ${Cypress.spec.name}`);
cy.eyesCheckWindow('Click!');
cy.log(`Closing eyes ${Cypress.spec.name}`);
cy.eyesClose();
} else {
cy.matchImageSnapshot(name);
}
};

View File

@ -1,4 +1,4 @@
import { renderGraph } from '../../helpers/util.js';
import { renderGraph } from '../../helpers/util.ts';
describe('Configuration', () => {
describe('arrowMarkerAbsolute', () => {
it('should handle default value false of arrowMarkerAbsolute', () => {

View File

@ -1,4 +1,4 @@
import { urlSnapshotTest } from '../../helpers/util.js';
import { urlSnapshotTest } from '../../helpers/util.ts';
describe('mermaid', () => {
describe('registerDiagram', () => {

View File

@ -1,4 +1,4 @@
import { urlSnapshotTest, openURLAndVerifyRendering } from '../../helpers/util.js';
import { urlSnapshotTest, openURLAndVerifyRendering } from '../../helpers/util.ts';
describe('CSS injections', () => {
it('should not allow CSS injections outside of the diagram', () => {

View File

@ -1,4 +1,4 @@
import { mermaidUrl } from '../../helpers/util.js';
import { mermaidUrl } from '../../helpers/util.ts';
describe('XSS', () => {
it('should handle xss in tags', () => {
const str =

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest } from '../../helpers/util.js';
import { imgSnapshotTest } from '../../helpers/util.ts';
describe('Git Graph diagram', () => {
it('1: should render a simple gitgraph with commit on main branch', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe('C4 diagram', () => {
it('should render a simple C4Context diagram', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest } from '../../helpers/util.js';
import { imgSnapshotTest } from '../../helpers/util.ts';
describe('Class diagram V2', () => {
it('0: should render a simple class diagram', () => {
imgSnapshotTest(

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe('Class diagram', () => {
it('1: should render a simple class diagram', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest } from '../../helpers/util.js';
import { imgSnapshotTest } from '../../helpers/util.ts';
describe('Configuration and directives - nodes should be light blue', () => {
it('No config - use default', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest } from '../../helpers/util.js';
import { imgSnapshotTest } from '../../helpers/util.ts';
describe('Current diagram', () => {
it('should render a state with states in it', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest } from '../../helpers/util.js';
import { imgSnapshotTest } from '../../helpers/util.ts';
describe('Flowchart', () => {
it('34: testing the label width in percy', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe('Entity Relationship Diagram', () => {
it('should render a simple ER diagram', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe.skip('Flowchart ELK', () => {
it('1-elk: should render a simple flowchart', () => {
@ -681,7 +681,7 @@ title: Simple flowchart
flowchart-elk TD
A --> B
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('elk: should include classes on the edges', () => {
@ -710,7 +710,7 @@ flowchart-elk LR
style id2 fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5
classDef someclass fill:#f96
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('With formatting in a node', () => {
@ -726,7 +726,7 @@ flowchart-elk LR
b --> d(The dog in the hog)
c --> d
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('New line in node and formatted edge label', () => {
@ -736,7 +736,7 @@ flowchart-elk LR
b("\`The dog in **the** hog.(1)
NL\`") --"\`1o **bold**\`"--> c
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('Wrapping long text with a new line', () => {
@ -749,7 +749,7 @@ Word!
Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. \`) --> c
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('Sub graphs and markdown strings', () => {
@ -766,7 +766,7 @@ subgraph "\`**Two**\`"
end
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
});
@ -782,7 +782,7 @@ flowchart-elk LR
style id2 fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5
classDef someclass fill:#f96
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('With formatting in a node', () => {
@ -798,7 +798,7 @@ flowchart-elk LR
b --> d(The dog in the hog)
c --> d
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('New line in node and formatted edge label', () => {
@ -808,7 +808,7 @@ flowchart-elk LR
b("\`The dog in **the** hog.(1)
NL\`") --"\`1o **bold**\`"--> c
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('Wrapping long text with a new line', () => {
@ -821,7 +821,7 @@ Word!
Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. \`") --> c
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('Sub graphs and markdown strings', () => {
@ -838,7 +838,7 @@ subgraph "\`**Two**\`"
end
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
});

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe('Flowchart v2', () => {
it('1: should render a simple flowchart', () => {
@ -449,7 +449,7 @@ flowchart TD
{ htmlLabels: true, flowchart: { htmlLabels: true }, securityLevel: 'loose' }
);
});
it('65: text-color from classes', () => {
it('65-1: text-color from classes', () => {
imgSnapshotTest(
`
flowchart LR
@ -460,6 +460,31 @@ flowchart TD
{ htmlLabels: true, flowchart: { htmlLabels: true }, securityLevel: 'loose' }
);
});
it('65-2: bold text from classes', () => {
imgSnapshotTest(
`
flowchart
classDef cat fill:#f9d5e5, stroke:#233d4d,stroke-width:2px, font-weight:bold;
CS(A long bold text to be viewed):::cat
`,
{ htmlLabels: true, flowchart: { htmlLabels: true }, securityLevel: 'loose' }
);
});
it('65-3: bigger font from classes', () => {
imgSnapshotTest(
`
flowchart
Node1:::class1 --> Node2:::class2
Node1:::class1 --> Node3:::class2
Node3 --> Node4((I am a circle)):::larger
classDef class1 fill:lightblue
classDef class2 fill:pink
classDef larger font-size:30px,fill:yellow
`,
{ htmlLabels: true, flowchart: { htmlLabels: true }, securityLevel: 'loose' }
);
});
it('66: More nested subgraph cases (TB)', () => {
imgSnapshotTest(
`
@ -671,7 +696,7 @@ title: Simple flowchart
flowchart TD
A --> B
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 10 } }
);
});
it('3192: It should be possieble to render flowcharts with invisible edges', () => {
@ -682,7 +707,7 @@ title: Simple flowchart with invisible edges
flowchart TD
A ~~~ B
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 10 } }
);
});
it('4023: Should render html labels with images and-or text correctly', () => {
@ -716,7 +741,7 @@ flowchart LR
style id2 fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5
classDef someclass fill:#f96
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('With formatting in a node', () => {
@ -732,7 +757,7 @@ flowchart LR
b --> d(The dog in the hog)
c --> d
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('New line in node and formatted edge label', () => {
@ -742,7 +767,7 @@ flowchart LR
b("\`The dog in **the** hog.(1)
NL\`") --"\`1o **bold**\`"--> c
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('Wrapping long text with a new line', () => {
@ -755,7 +780,7 @@ Word!
Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. \`") --> c
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('Sub graphs and markdown strings', () => {
@ -772,7 +797,7 @@ subgraph "\`**Two**\`"
end
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
});
@ -788,7 +813,7 @@ flowchart LR
style id2 fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5
classDef someclass fill:#f96
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('With formatting in a node', () => {
@ -804,7 +829,7 @@ flowchart LR
b --> d(The dog in the hog)
c --> d
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('New line in node and formatted edge label', () => {
@ -814,7 +839,7 @@ flowchart LR
b("\`The dog in **the** hog.(1)
NL\`") --"\`1o **bold**\`"--> c
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('Wrapping long text with a new line', () => {
@ -827,7 +852,7 @@ Word!
Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. \`") --> c
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
it('Sub graphs and markdown strings', () => {
@ -844,7 +869,7 @@ subgraph "\`**Two**\`"
end
`,
{ titleTopMargin: 0 }
{ flowchart: { titleTopMargin: 0 } }
);
});
});

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe('Graph', () => {
it('1: should render a simple flowchart no htmlLabels', () => {
@ -891,4 +891,27 @@ graph TD
{ htmlLabels: true, flowchart: { htmlLabels: true }, securityLevel: 'loose' }
);
});
it('66: apply class called default on node called default', () => {
imgSnapshotTest(
`
graph TD
classDef default fill:#a34,stroke:#000,stroke-width:4px,color:#fff
hello --> default
`,
{ htmlLabels: true, flowchart: { htmlLabels: true }, securityLevel: 'loose' }
);
});
it('67: should be able to style default node independently', () => {
imgSnapshotTest(
`
flowchart TD
classDef default fill:#a34
hello --> default
style default stroke:#000,stroke-width:4px
`,
{ htmlLabels: true, flowchart: { htmlLabels: true }, securityLevel: 'loose' }
);
});
});

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe('Gantt diagram', () => {
beforeEach(() => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest } from '../../helpers/util.js';
import { imgSnapshotTest } from '../../helpers/util.ts';
describe('Git Graph diagram', () => {
it('1: should render a simple gitgraph with commit on main branch', () => {
@ -333,4 +333,372 @@ gitGraph
{}
);
});
it('15: should render a simple gitgraph with commit on main branch | Vertical Branch', () => {
imgSnapshotTest(
`gitGraph TB:
commit id: "1"
commit id: "2"
commit id: "3"
`,
{}
);
});
it('16: should render a simple gitgraph with commit on main branch with Id | Vertical Branch', () => {
imgSnapshotTest(
`gitGraph TB:
commit id: "One"
commit id: "Two"
commit id: "Three"
`,
{}
);
});
it('17: should render a simple gitgraph with different commitTypes on main branch | Vertical Branch', () => {
imgSnapshotTest(
`gitGraph TB:
commit id: "Normal Commit"
commit id: "Reverse Commit" type: REVERSE
commit id: "Hightlight Commit" type: HIGHLIGHT
`,
{}
);
});
it('18: should render a simple gitgraph with tags commitTypes on main branch | Vertical Branch', () => {
imgSnapshotTest(
`gitGraph TB:
commit id: "Normal Commit with tag" tag: "v1.0.0"
commit id: "Reverse Commit with tag" type: REVERSE tag: "RC_1"
commit id: "Hightlight Commit" type: HIGHLIGHT tag: "8.8.4"
`,
{}
);
});
it('19: should render a simple gitgraph with two branches | Vertical Branch', () => {
imgSnapshotTest(
`gitGraph TB:
commit id: "1"
commit id: "2"
branch develop
checkout develop
commit id: "3"
commit id: "4"
checkout main
commit id: "5"
commit id: "6"
`,
{}
);
});
it('20: should render a simple gitgraph with two branches and merge commit | Vertical Branch', () => {
imgSnapshotTest(
`gitGraph TB:
commit id: "1"
commit id: "2"
branch develop
checkout develop
commit id: "3"
commit id: "4"
checkout main
merge develop
commit id: "5"
commit id: "6"
`,
{}
);
});
it('21: should render a simple gitgraph with three branches and tagged merge commit | Vertical Branch', () => {
imgSnapshotTest(
`gitGraph TB:
commit id: "1"
commit id: "2"
branch nice_feature
checkout nice_feature
commit id: "3"
checkout main
commit id: "4"
checkout nice_feature
branch very_nice_feature
checkout very_nice_feature
commit id: "5"
checkout main
commit id: "6"
checkout nice_feature
commit id: "7"
checkout main
merge nice_feature id: "12345" tag: "my merge commit"
checkout very_nice_feature
commit id: "8"
checkout main
commit id: "9"
`,
{}
);
});
it('22: should render a simple gitgraph with more than 8 branchs & overriding variables | Vertical Branch', () => {
imgSnapshotTest(
`%%{init: { 'logLevel': 'debug', 'theme': 'default' , 'themeVariables': {
'gitBranchLabel0': '#ffffff',
'gitBranchLabel1': '#ffffff',
'gitBranchLabel2': '#ffffff',
'gitBranchLabel3': '#ffffff',
'gitBranchLabel4': '#ffffff',
'gitBranchLabel5': '#ffffff',
'gitBranchLabel6': '#ffffff',
'gitBranchLabel7': '#ffffff',
} } }%%
gitGraph TB:
checkout main
branch branch1
branch branch2
branch branch3
branch branch4
branch branch5
branch branch6
branch branch7
branch branch8
branch branch9
checkout branch1
commit id: "1"
`,
{}
);
});
it('23: should render a simple gitgraph with rotated labels | Vertical Branch', () => {
imgSnapshotTest(
`%%{init: { 'logLevel': 'debug', 'theme': 'default' , 'gitGraph': {
'rotateCommitLabel': true
} } }%%
gitGraph TB:
commit id: "75f7219e83b321cd3fdde7dcf83bc7c1000a6828"
commit id: "0db4784daf82736dec4569e0dc92980d328c1f2e"
commit id: "7067e9973f9eaa6cd4a4b723c506d1eab598e83e"
commit id: "66972321ad6c199013b5b31f03b3a86fa3f9817d"
`,
{}
);
});
it('24: should render a simple gitgraph with horizontal labels | Vertical Branch', () => {
imgSnapshotTest(
`%%{init: { 'logLevel': 'debug', 'theme': 'default' , 'gitGraph': {
'rotateCommitLabel': false
} } }%%
gitGraph TB:
commit id: "Alpha"
commit id: "Beta"
commit id: "Gamma"
commit id: "Delta"
`,
{}
);
});
it('25: should render a simple gitgraph with cherry pick commit | Vertical Branch', () => {
imgSnapshotTest(
`
gitGraph TB:
commit id: "ZERO"
branch develop
commit id:"A"
checkout main
commit id:"ONE"
checkout develop
commit id:"B"
checkout main
commit id:"TWO"
cherry-pick id:"A"
commit id:"THREE"
checkout develop
commit id:"C"
`,
{}
);
});
it('26: should render a gitgraph with cherry pick commit with custom tag | Vertical Branch', () => {
imgSnapshotTest(
`
gitGraph TB:
commit id: "ZERO"
branch develop
commit id:"A"
checkout main
commit id:"ONE"
checkout develop
commit id:"B"
checkout main
commit id:"TWO"
cherry-pick id:"A" tag: "snapshot"
commit id:"THREE"
checkout develop
commit id:"C"
`,
{}
);
});
it('27: should render a gitgraph with cherry pick commit with no tag | Vertical Branch', () => {
imgSnapshotTest(
`
gitGraph TB:
commit id: "ZERO"
branch develop
commit id:"A"
checkout main
commit id:"ONE"
checkout develop
commit id:"B"
checkout main
commit id:"TWO"
cherry-pick id:"A" tag: ""
commit id:"THREE"
checkout develop
commit id:"C"
`,
{}
);
});
it('28: should render a simple gitgraph with two cherry pick commit | Vertical Branch', () => {
imgSnapshotTest(
`
gitGraph TB:
commit id: "ZERO"
branch develop
commit id:"A"
checkout main
commit id:"ONE"
checkout develop
commit id:"B"
branch featureA
commit id:"FIX"
commit id: "FIX-2"
checkout main
commit id:"TWO"
cherry-pick id:"A"
commit id:"THREE"
cherry-pick id:"FIX"
checkout develop
commit id:"C"
merge featureA
`,
{}
);
});
it('29: should render commits for more than 8 branches | Vertical Branch', () => {
imgSnapshotTest(
`
gitGraph TB:
checkout main
%% Make sure to manually set the ID of all commits, for consistent visual tests
commit id: "1-abcdefg"
checkout main
branch branch1
commit id: "2-abcdefg"
checkout main
merge branch1
branch branch2
commit id: "3-abcdefg"
checkout main
merge branch2
branch branch3
commit id: "4-abcdefg"
checkout main
merge branch3
branch branch4
commit id: "5-abcdefg"
checkout main
merge branch4
branch branch5
commit id: "6-abcdefg"
checkout main
merge branch5
branch branch6
commit id: "7-abcdefg"
checkout main
merge branch6
branch branch7
commit id: "8-abcdefg"
checkout main
merge branch7
branch branch8
commit id: "9-abcdefg"
checkout main
merge branch8
branch branch9
commit id: "10-abcdefg"
`,
{}
);
});
it('30: should render a simple gitgraph with three branches,custom merge commit id,tag,type | Vertical Branch', () => {
imgSnapshotTest(
`gitGraph TB:
commit id: "1"
commit id: "2"
branch nice_feature
checkout nice_feature
commit id: "3"
checkout main
commit id: "4"
checkout nice_feature
branch very_nice_feature
checkout very_nice_feature
commit id: "5"
checkout main
commit id: "6"
checkout nice_feature
commit id: "7"
checkout main
merge nice_feature id: "customID" tag: "customTag" type: REVERSE
checkout very_nice_feature
commit id: "8"
checkout main
commit id: "9"
`,
{}
);
});
it('31: should render a simple gitgraph with a title | Vertical Branch', () => {
imgSnapshotTest(
`---
title: simple gitGraph
---
gitGraph TB:
commit id: "1-abcdefg"
`,
{}
);
});
it('32: should render a simple gitgraph overlapping commits | Vertical Branch', () => {
imgSnapshotTest(
`gitGraph TB:
commit id:"s1"
commit id:"s2"
branch branch1
commit id:"s3"
commit id:"s4"
checkout main
commit id:"s5"
checkout branch1
commit id:"s6"
commit id:"s7"
merge main
`,
{}
);
});
it('33: should render a simple gitgraph overlapping commits', () => {
imgSnapshotTest(
`gitGraph
commit id:"s1"
commit id:"s2"
branch branch1
commit id:"s3"
commit id:"s4"
checkout main
commit id:"s5"
checkout branch1
commit id:"s6"
commit id:"s7"
merge main
`,
{}
);
});
});

View File

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

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe('User journey diagram', () => {
it('Simple test', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest } from '../../helpers/util.js';
import { imgSnapshotTest } from '../../helpers/util.ts';
/**
* Check whether the SVG Element has a Mindmap root
@ -242,8 +242,7 @@ mindmap
a second line 😎\`]
id2[\`The dog in **the** hog... a *very long text* about it
Word!\`]
`,
{ titleTopMargin: 0 }
`
);
});
});

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe('Pie Chart', () => {
it('should render a simple pie diagram', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe('Quadrant Chart', () => {
it('should render if only chart type is provided', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe('Requirement diagram', () => {
it('sample', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe('Sankey Diagram', () => {
it('should render a simple example', () => {

View File

@ -1,6 +1,6 @@
/// <reference types="Cypress" />
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
context('Sequence diagram', () => {
it('should render a sequence diagram with boxes', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe('State diagram', () => {
it('v2 should render a simple info', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.js';
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe('State diagram', () => {
it('should render a simple state diagrams', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest } from '../../helpers/util.js';
import { imgSnapshotTest } from '../../helpers/util.ts';
describe('themeCSS balancing, it', () => {
it('should not allow unbalanced CSS definitions', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest } from '../../helpers/util.js';
import { imgSnapshotTest } from '../../helpers/util.ts';
describe('Timeline diagram', () => {
it('1: should render a simple timeline with no specific sections', () => {

View File

@ -1,4 +1,4 @@
import { imgSnapshotTest } from '../../helpers/util.js';
import { imgSnapshotTest } from '../../helpers/util.ts';
describe('Zen UML', () => {
it('Basic Zen UML diagram', () => {

View File

@ -58,6 +58,23 @@
</head>
<body>
<pre id="diagram" class="mermaid">
flowchart
classDef mainCategories fill:#f9d5e5, stroke:#233d4d,stroke-width:2px, font-weight:bold;
CS(Customer Awareness Journey):::mainCategories
</pre
>
<pre id="diagram" class="mermaid">
flowchart
Node1:::class1 --> Node2:::class2
Node1:::class1 --> Node3:::class2
Node3 --> Node4((I am a circle)):::larger
classDef class1 fill:lightblue
classDef class2 fill:pink
classDef larger font-size:30px,fill:yellow
</pre
>
<pre id="diagram" class="mermaid2">
stateDiagram-v2
[*] --> Still
Still --> [*]
@ -73,7 +90,7 @@ flowchart RL
a1 -- l2 --> a2
end
</pre>
<pre id="diagram" class="mermaid">
<pre id="diagram" class="mermaid2">
flowchart RL
subgraph "`one`"
a1 -- l1 --> a2
@ -98,11 +115,11 @@ flowchart LR
way`"]
</pre
>
<pre id="diagram" class="mermaid">
<pre id="diagram" class="mermaid2">
classDiagram-v2
note "I love this diagram!\nDo you love it?"
</pre>
<pre id="diagram" class="mermaid">
<pre id="diagram" class="mermaid2">
stateDiagram-v2
State1: The state with a note with minus - and plus + in it
note left of State1
@ -147,7 +164,7 @@ mindmap
शान्तिः سلام 和平 `"]
</pre>
<pre id="diagram" class="mermaid">
<pre id="diagram" class="mermaid2">
%%{init: {"flowchart": {"defaultRenderer": "elk"}} }%%
flowchart TB
%% I could not figure out how to use double quotes in labels in Mermaid
@ -399,21 +416,31 @@ mindmap
mermaid.parseError = function (err, hash) {
// console.error('Mermaid error: ', err);
};
// mermaid.initialize({
// // theme: 'forest',
// startOnLoad: true,
// logLevel: 0,
// flowchart: {
// // defaultRenderer: 'elk',
// useMaxWidth: false,
// // htmlLabels: false,
// htmlLabels: true,
// },
// // htmlLabels: false,
// gantt: {
// useMaxWidth: false,
// },
// useMaxWidth: false,
// });
mermaid.initialize({
// theme: 'forest',
startOnLoad: true,
logLevel: 0,
flowchart: {
// defaultRenderer: 'elk',
useMaxWidth: false,
// htmlLabels: false,
htmlLabels: true,
flowchart: { titleTopMargin: 10 },
fontFamily: 'courier',
sequence: {
actorFontFamily: 'courier',
noteFontFamily: 'courier',
messageFontFamily: 'courier',
},
// htmlLabels: false,
gantt: {
useMaxWidth: false,
},
useMaxWidth: false,
fontSize: 16,
});
function callback() {
alert('It worked');

View File

@ -2,7 +2,9 @@
"compilerOptions": {
"target": "es2020",
"lib": ["es2020", "dom"],
"types": ["cypress", "node"]
"types": ["cypress", "node"],
"allowImportingTsExtensions": true,
"noEmit": true
},
"include": ["**/*.ts"]
}

34
demos/dev/example.html Normal file
View File

@ -0,0 +1,34 @@
<!--Do not edit this file-->
<!--Duplicate this file to any name you like, run `pnpm dev`, open http://localhost:9000/dev/name.html to view-->
<html>
<head>
<title>Mermaid development page</title>
</head>
<body>
<pre id="diagram" class="mermaid">
graph TB
a --> b
a --> c
b --> d
c --> d
</pre>
<div id="dynamicDiagram"></div>
<script type="module">
import mermaid from '/mermaid.esm.mjs';
mermaid.parseError = function (err, hash) {
console.error('Mermaid error: ', err);
};
mermaid.initialize({
startOnLoad: true,
logLevel: 0,
});
const value = `graph TD\nHello --> World`;
const el = document.getElementById('dynamicDiagram');
const { svg } = await mermaid.render('dd', value);
console.log(svg);
el.innerHTML = svg;
</script>
</body>
</html>

View File

@ -1,7 +1,7 @@
version: '3.9'
services:
mermaid:
image: node:18.16.1-alpine3.18
image: node:18.17.1-alpine3.18
stdin_open: true
tty: true
working_dir: /mermaid
@ -17,7 +17,7 @@ services:
- 9000:9000
- 3333:3333
cypress:
image: cypress/included:12.17.1
image: cypress/included:12.17.3
stdin_open: true
tty: true
working_dir: /mermaid

View File

@ -70,7 +70,21 @@ pnpm test
The `test` script and others are in the top-level `package.json` file.
All tests should run successfully without any errors or failures. (You might see _lint_ or _formatting_ warnings; those are ok during this step.)
All tests should run successfully without any errors or failures. (You might see _lint_ or _formatting_ "warnings"; those are ok during this step.)
#### 4. Make your changes
Now you are ready to make your changes!
Edit whichever files in `src` as required.
#### 5. See your changes
Open <http://localhost:9000> in your browser, after starting the dev server.
There is a list of demos that can be used to see and test your changes.
If you need a specific diagram, you can duplicate the `example.html` file in `/demos/dev` and add your own mermaid code to your copy.
That will be served at <http://localhost:9000/dev/your-file-name.html>.
After making code changes, the dev server will rebuild the mermaid library. You will need to reload the browser page yourself to see the changes. (PRs for auto reload are welcome!)
### Docker
@ -223,6 +237,9 @@ If the users have no way to know that things have changed, then you haven't real
Likewise, if users don't know that there is a new feature that you've implemented, it will forever remain unknown and unused.
The documentation has to be updated to users know that things have changed and added!
If you are adding a new feature, add `(v<MERMAID_RELEASE_VERSION>+)` in the title or description. It will be replaced automatically with the current version number when the release happens.
eg: `# Feature Name (v<MERMAID_RELEASE_VERSION>+)`
We know it can sometimes be hard to code _and_ write user documentation.

View File

@ -10,7 +10,7 @@
#### Grammar
This would be to define a jison grammar for the new diagram type. That should start with a way to identify that the text in the mermaid tag is a diagram of that type. Create a new folder under diagrams for your new diagram type and a parser folder in it. This leads us to step 2.
This would be to define a JISON grammar for the new diagram type. That should start with a way to identify that the text in the mermaid tag is a diagram of that type. Create a new folder under diagrams for your new diagram type and a parser folder in it. This leads us to step 2.
For instance:
@ -60,7 +60,7 @@ Place the renderer in the diagram folder.
### Step 3: Detection of the new diagram type
The second thing to do is to add the capability to detect the new diagram to type to the detectType in utils.js. The detection should return a key for the new diagram type.
The second thing to do is to add the capability to detect the new diagram to type to the detectType in `diagram-api/detectType.ts`. The detection should return a key for the new diagram type.
[This key will be used to as the aria roledescription](#aria-roledescription), so it should be a word that clearly describes the diagram type.
For example, if your new diagram use a UML deployment diagram, a good key would be "UMLDeploymentDiagram" because assistive technologies such as a screen reader
would voice that as "U-M-L Deployment diagram." Another good key would be "deploymentDiagram" because that would be voiced as "Deployment Diagram." A bad key would be "deployment" because that would not sufficiently describe the diagram.
@ -124,53 +124,6 @@ There are a few features that are common between the different types of diagrams
Here some pointers on how to handle these different areas.
#### [Directives](../config/directives.md)
Here is example handling from flowcharts:
Jison:
```jison
/* lexical grammar */
%lex
%x open_directive
%x type_directive
%x arg_directive
%x close_directive
\%\%\{ { this.begin('open_directive'); return 'open_directive'; }
<open_directive>((?:(?!\}\%\%)[^:.])*) { this.begin('type_directive'); return 'type_directive'; }
<type_directive>":" { this.popState(); this.begin('arg_directive'); return ':'; }
<type_directive,arg_directive>\}\%\% { this.popState(); this.popState(); return 'close_directive'; }
<arg_directive>((?:(?!\}\%\%).|\n)*) return 'arg_directive';
/* language grammar */
/* ... */
directive
: openDirective typeDirective closeDirective separator
| openDirective typeDirective ':' argDirective closeDirective separator
;
openDirective
: open_directive { yy.parseDirective('%%{', 'open_directive'); }
;
typeDirective
: type_directive { yy.parseDirective($1, 'type_directive'); }
;
argDirective
: arg_directive { $1 = $1.trim().replace(/'/g, '"'); yy.parseDirective($1, 'arg_directive'); }
;
closeDirective
: close_directive { yy.parseDirective('}%%', 'close_directive', 'flowchart'); }
;
```
It is probably a good idea to keep the handling similar to this in your new diagram. The parseDirective function is provided by the mermaidAPI.
## Accessibility
Mermaid automatically adds the following accessibility information for the diagram SVG HTML element:
@ -189,7 +142,7 @@ See [the definition of aria-roledescription](https://www.w3.org/TR/wai-aria-1.1/
The syntax for accessible titles and descriptions is described in [the Accessibility documenation section.](../config/accessibility.md)
In a similar way to the directives, the jison syntax are quite similar between the diagrams.
As a design goal, the jison syntax should be similar between the diagrams.
```jison

View File

@ -96,7 +96,7 @@ mermaid.initialize(config);
#### Defined in
[mermaidAPI.ts:667](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L667)
[mermaidAPI.ts:668](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L668)
## Functions
@ -127,7 +127,7 @@ Return the last node appended
#### Defined in
[mermaidAPI.ts:308](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L308)
[mermaidAPI.ts:309](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L309)
---
@ -153,7 +153,7 @@ the cleaned up svgCode
#### Defined in
[mermaidAPI.ts:256](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L256)
[mermaidAPI.ts:255](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L255)
---
@ -179,7 +179,7 @@ the string with all the user styles
#### Defined in
[mermaidAPI.ts:185](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L185)
[mermaidAPI.ts:184](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L184)
---
@ -202,7 +202,7 @@ the string with all the user styles
#### Defined in
[mermaidAPI.ts:233](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L233)
[mermaidAPI.ts:232](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L232)
---
@ -229,7 +229,7 @@ with an enclosing block that has each of the cssClasses followed by !important;
#### Defined in
[mermaidAPI.ts:169](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L169)
[mermaidAPI.ts:168](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L168)
---
@ -249,7 +249,7 @@ with an enclosing block that has each of the cssClasses followed by !important;
#### Defined in
[mermaidAPI.ts:155](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L155)
[mermaidAPI.ts:154](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L154)
---
@ -269,7 +269,7 @@ with an enclosing block that has each of the cssClasses followed by !important;
#### Defined in
[mermaidAPI.ts:126](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L126)
[mermaidAPI.ts:125](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L125)
---
@ -295,7 +295,7 @@ Put the svgCode into an iFrame. Return the iFrame code
#### Defined in
[mermaidAPI.ts:287](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L287)
[mermaidAPI.ts:286](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L286)
---
@ -320,4 +320,4 @@ Remove any existing elements from the given document
#### Defined in
[mermaidAPI.ts:358](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L358)
[mermaidAPI.ts:359](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L359)

View File

@ -228,7 +228,7 @@ mermaid fully supports webpack. Here is a [working demo](https://github.com/merm
The main idea of the API is to be able to call a render function with the graph definition as a string. The render function will render the graph and call a callback with the resulting SVG code. With this approach it is up to the site creator to fetch the graph definition from the site (perhaps from a textarea), render it and place the graph somewhere in the site.
The example below show an outline of how this could be used. The example just logs the resulting SVG to the JavaScript console.
The example below shows an example of how this could be used. The example just logs the resulting SVG to the JavaScript console.
```html
<script type="module">

View File

@ -187,6 +187,7 @@ They also serve as proof of concept, for the variety of things that can be built
- [mdbook](https://rust-lang.github.io/mdBook/index.html)
- [mdbook-mermaid](https://github.com/badboy/mdbook-mermaid)
- [Quarto](https://quarto.org/)
- [Typora](https://typora.io/) ([Native support](https://support.typora.io/Draw-Diagrams-With-Markdown/#mermaid))
## Browser Extensions

View File

@ -14,8 +14,12 @@ It is a JavaScript based diagramming and charting tool that renders Markdown-ins
<img src="/header.png" alt="" />
<div class='badges'>
[![Build CI Status](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml/badge.svg)](https://github.com/mermaid-js/mermaid/actions/workflows/build.yml) [![NPM](https://img.shields.io/npm/v/mermaid)](https://www.npmjs.com/package/mermaid) [![npm minified gzipped bundle size](https://img.shields.io/bundlephobia/minzip/mermaid)](https://bundlephobia.com/package/mermaid) [![Coverage Status](https://coveralls.io/repos/github/mermaid-js/mermaid/badge.svg?branch=master)](https://coveralls.io/github/mermaid-js/mermaid?branch=master) [![CDN Status](https://img.shields.io/jsdelivr/npm/hm/mermaid)](https://www.jsdelivr.com/package/npm/mermaid) [![NPM](https://img.shields.io/npm/dm/mermaid)](https://www.npmjs.com/package/mermaid) [![Join our Slack!](https://img.shields.io/static/v1?message=join%20chat&color=9cf&logo=slack&label=slack)](https://join.slack.com/t/mermaid-talk/shared_invite/enQtNzc4NDIyNzk4OTAyLWVhYjQxOTI2OTg4YmE1ZmJkY2Y4MTU3ODliYmIwOTY3NDJlYjA0YjIyZTdkMDMyZTUwOGI0NjEzYmEwODcwOTE) [![Twitter Follow](https://img.shields.io/twitter/follow/mermaidjs_?style=social)](https://twitter.com/mermaidjs_)
</div>
<!-- Mermaid book banner -->
[![Explore Mermaid.js in depth, with real-world examples, tips & tricks from the creator... The first official book on Mermaid is available for purchase. Check it out!](img/book-banner-post-release.jpg)](https://mermaid-js.github.io/mermaid/landing/)
@ -387,7 +391,13 @@ The above command generates files into the `dist` folder and publishes them to \
- [Live Editor](https://github.com/mermaid-js/mermaid-live-editor)
- [HTTP Server](https://github.com/TomWright/mermaid-server)
## Contributors [![Good first issue](https://img.shields.io/github/labels/mermaid-js/mermaid/Good%20first%20issue%21)](https://github.com/mermaid-js/mermaid/issues?q=is%3Aissue+is%3Aopen+label%3A%22Good+first+issue%21%22) [![Contributors](https://img.shields.io/github/contributors/mermaid-js/mermaid)](https://github.com/mermaid-js/mermaid/graphs/contributors) [![Commits](https://img.shields.io/github/commit-activity/m/mermaid-js/mermaid)](https://github.com/mermaid-js/mermaid/graphs/contributors)
## Contributors
<div class='badges'>
[![Good first issue](https://img.shields.io/github/labels/mermaid-js/mermaid/Good%20first%20issue%21)](https://github.com/mermaid-js/mermaid/issues?q=is%3Aissue+is%3Aopen+label%3A%22Good+first+issue%21%22) [![Contributors](https://img.shields.io/github/contributors/mermaid-js/mermaid)](https://github.com/mermaid-js/mermaid/graphs/contributors) [![Commits](https://img.shields.io/github/commit-activity/m/mermaid-js/mermaid)](https://github.com/mermaid-js/mermaid/graphs/contributors)
</div>
Mermaid is a growing community and is always accepting new contributors. There's a lot of different ways to help out and we're always looking for extra hands! Look at [this issue](https://github.com/mermaid-js/mermaid/issues/866) if you want to know where to start helping out.
@ -422,20 +432,14 @@ A quick note from Knut Sveidqvist:
_Mermaid was created by Knut Sveidqvist for easier documentation._
<style scoped>
#contributors + p,
#about-mermaid + p + p + blockquote + img + p
{
display: flex
.badges > p {
display: flex;
}
.badges > p > a {
margin: 0 0.5rem;
}
#contributors + p a,
#about-mermaid + p + p + blockquote + img + p a
{
margin: 0 0.5rem
}
.dark #VPContent > div > div > div.content > div > main > div > div > img
{
.dark #VPContent > div > div > div.content > div > main > div > div > img {
filter: invert(1) hue-rotate(217deg) contrast(0.72);
}
</style>

View File

@ -6,8 +6,8 @@
# Announcements
## [Mermaid Charts ChatGPT Plugin Combines Generative AI and Smart Diagramming For Users](https://www.mermaidchart.com/blog/posts/mermaid-chart-chatgpt-plugin-combines-generative-ai-and-smart-diagramming)
## [From Chaos to Clarity: Exploring Mind Maps with MermaidJS](https://www.mermaidchart.com/blog/posts/from-chaos-to-clarity-exploring-mind-maps-with-mermaidjs)
29 June 2023 · 4 mins
24 July 2023 · 4 mins
Mermaid Charts new ChatGPT plugin integrates AI-powered text prompts with Mermaids intuitive diagramming editor, enabling users to generate, edit, and share complex diagrams with ease and efficiency.
Introducing the concept of mind mapping as a tool for organizing complex information, and highlights Mermaid as a user-friendly software that simplifies the creation and editing of mind maps for applications in IT solution design, business decision-making, and knowledge organization.

View File

@ -6,6 +6,18 @@
# Blog
## [From Chaos to Clarity: Exploring Mind Maps with MermaidJS](https://www.mermaidchart.com/blog/posts/from-chaos-to-clarity-exploring-mind-maps-with-mermaidjs)
24 July 2023 · 4 mins
Introducing the concept of mind mapping as a tool for organizing complex information, and highlights Mermaid as a user-friendly software that simplifies the creation and editing of mind maps for applications in IT solution design, business decision-making, and knowledge organization.
## [Mermaid Chart Announces Visual Studio Code Plugin to Simplify Development Workflows](https://www.mermaidchart.com/blog/posts/mermaid-chart-announces-visual-studio-code-plugin)
17 July 2023 · 3 mins
New Integration Enhances Workflows By Enabling Developers To Reference And Edit Diagrams Within Visual Studio Code.
## [Mermaid Charts ChatGPT Plugin Combines Generative AI and Smart Diagramming For Users](https://www.mermaidchart.com/blog/posts/mermaid-chart-chatgpt-plugin-combines-generative-ai-and-smart-diagramming)
29 June 2023 · 4 mins

View File

@ -2,13 +2,13 @@
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/syntax/c4c.md](../../packages/mermaid/src/docs/syntax/c4c.md).
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/syntax/c4.md](../../packages/mermaid/src/docs/syntax/c4.md).
# C4 Diagrams
> C4 Diagram: This is an experimental diagram for now. The syntax and properties can change in future releases. Proper documentation will be provided when the syntax is stable.
Mermaid's c4 diagram syntax is compatible with plantUML. See example below:
Mermaid's C4 diagram syntax is compatible with plantUML. See example below:
```mermaid-example
C4Context
@ -114,7 +114,7 @@ For an example, see the source code demos/index.html
- Dynamic diagram (C4Dynamic)
- Deployment diagram (C4Deployment)
Please refer to the linked document [C4-PlantUML syntax](https://github.com/plantuml-stdlib/C4-PlantUML/blob/master/README.md) for how to write the c4 diagram.
Please refer to the linked document [C4-PlantUML syntax](https://github.com/plantuml-stdlib/C4-PlantUML/blob/master/README.md) for how to write the C4 diagram.
C4 diagram is fixed style, such as css color, so different css is not provided under different skins.
updateElementStyle and UpdateElementStyle are written in the diagram last part. updateElementStyle is inconsistent with the original definition and updates the style of the relationship, including the offset of the text label relative to the original position.

View File

@ -608,12 +608,12 @@ It is possible to escape characters using the syntax exemplified here.
```mermaid-example
flowchart LR
A["A double quote:#quot;"] -->B["A dec char:#9829;"]
A["A double quote:#quot;"] --> B["A dec char:#9829;"]
```
```mermaid
flowchart LR
A["A double quote:#quot;"] -->B["A dec char:#9829;"]
A["A double quote:#quot;"] --> B["A dec char:#9829;"]
```
Numbers given are base 10, so `#` can be encoded as `#35;`. It is also supported to use HTML character names.
@ -748,6 +748,48 @@ flowchart LR
B1 --> B2
```
#### Limitation
If any of a subgraph's nodes are linked to the outside, subgraph direction will be ignored. Instead the subgraph will inherit the direction of the parent graph:
```mermaid-example
flowchart LR
subgraph subgraph1
direction TB
top1[top] --> bottom1[bottom]
end
subgraph subgraph2
direction TB
top2[top] --> bottom2[bottom]
end
%% ^ These subgraphs are identical, except for the links to them:
%% Link *to* subgraph1: subgraph1 direction is mantained
outside --> subgraph1
%% Link *within* subgraph2:
%% subgraph2 inherits the direction of the top-level graph (LR)
outside ---> top2
```
```mermaid
flowchart LR
subgraph subgraph1
direction TB
top1[top] --> bottom1[bottom]
end
subgraph subgraph2
direction TB
top2[top] --> bottom2[bottom]
end
%% ^ These subgraphs are identical, except for the links to them:
%% Link *to* subgraph1: subgraph1 direction is mantained
outside --> subgraph1
%% Link *within* subgraph2:
%% subgraph2 inherits the direction of the top-level graph (LR)
outside ---> top2
```
## Markdown Strings
The "Markdown Strings" feature enhances flowcharts and mind maps by offering a more versatile string type, which supports text formatting options such as bold and italics, and automatically wraps text within labels.

View File

@ -271,6 +271,8 @@ gantt
weekday monday
```
Support: v10.3.0+
## Output in compact mode
The compact mode allows you to display multiple tasks in the same row. Compact mode can be enabled for a gantt chart by setting the display mode of the graph via preceeding YAML settings.

View File

@ -825,6 +825,82 @@ NOTE: Because we have overridden the `mainBranchOrder` to `2`, the `main` branch
Here, we have changed the default main branch name to `MetroLine1`.
## Orientation (v10.3.0+)
In Mermaid, the default orientation is Left to Right. The branches are lined vertically.
Usage example:
```mermaid-example
gitGraph
commit
commit
branch develop
commit
commit
commit
checkout main
commit
commit
merge develop
commit
commit
```
```mermaid
gitGraph
commit
commit
branch develop
commit
commit
commit
checkout main
commit
commit
merge develop
commit
commit
```
Sometimes we may want to change the orientation. Currently, Mermaid supports two orientations: **Left to Right**(default) and **Top to Bottom**.
In order to change the orientation from top to bottom i.e. branches lined horizontally, you need to add `TB` along with `gitGraph`.
Usage example:
```mermaid-example
gitGraph TB:
commit
commit
branch develop
commit
commit
commit
checkout main
commit
commit
merge develop
commit
commit
```
```mermaid
gitGraph TB:
commit
commit
branch develop
commit
commit
commit
checkout main
commit
commit
merge develop
commit
commit
```
## Themes
Mermaid supports a bunch of pre-defined themes which you can use to find the right one for you. PS: you can actually override an existing theme's variable to get your own custom theme going. Learn more about theming your diagram [here](../config/theming.md).

View File

@ -4,7 +4,7 @@
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/syntax/sankey.md](../../packages/mermaid/src/docs/syntax/sankey.md).
# Sankey diagrams
# Sankey diagram (v10.3.0+)
> A sankey diagram is a visualization used to depict a flow from one set of values to another.

View File

@ -94,7 +94,7 @@ sequenceDiagram
J->>A: Great!
```
### Actor Creation and Destruction
### Actor Creation and Destruction (v10.3.0+)
It is possible to create and destroy actors by messages. To do so, add a create or destroy directive before the message.

View File

@ -4,7 +4,7 @@
"version": "10.2.4",
"description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.",
"type": "module",
"packageManager": "pnpm@8.6.7",
"packageManager": "pnpm@8.6.12",
"keywords": [
"diagram",
"markdown",
@ -78,15 +78,15 @@
"@types/rollup-plugin-visualizer": "^4.2.1",
"@typescript-eslint/eslint-plugin": "^5.59.0",
"@typescript-eslint/parser": "^5.59.0",
"@vitest/coverage-v8": "^0.33.0",
"@vitest/spy": "^0.33.0",
"@vitest/ui": "^0.33.0",
"@vitest/coverage-v8": "^0.34.0",
"@vitest/spy": "^0.34.0",
"@vitest/ui": "^0.34.0",
"ajv": "^8.12.0",
"concurrently": "^8.0.1",
"cors": "^2.8.5",
"cypress": "^12.10.0",
"cypress-image-snapshot": "^4.0.1",
"esbuild": "^0.18.0",
"esbuild": "^0.19.0",
"eslint": "^8.39.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-cypress": "^2.13.2",
@ -109,7 +109,7 @@
"lint-staged": "^13.2.1",
"nyc": "^15.1.0",
"path-browserify": "^1.0.1",
"pnpm": "^8.3.1",
"pnpm": "^8.6.8",
"prettier": "^2.8.8",
"prettier-plugin-jsdoc": "^0.4.2",
"rimraf": "^5.0.0",
@ -119,10 +119,10 @@
"typescript": "^5.1.3",
"vite": "^4.3.9",
"vite-plugin-istanbul": "^4.1.0",
"vitest": "^0.33.0"
"vitest": "^0.34.0"
},
"volta": {
"node": "18.16.1"
"node": "18.17.1"
},
"nyc": {
"report-dir": "coverage/cypress"

View File

@ -38,7 +38,7 @@
]
},
"dependencies": {
"@braintree/sanitize-url": "^6.0.0",
"@braintree/sanitize-url": "^6.0.1",
"cytoscape": "^3.23.0",
"cytoscape-cose-bilkent": "^4.1.0",
"cytoscape-fcose": "^2.1.0",

View File

@ -1,6 +1,6 @@
{
"name": "@mermaid-js/mermaid-zenuml",
"version": "0.1.0",
"version": "0.1.2",
"description": "MermaidJS plugin for ZenUML integration",
"module": "dist/mermaid-zenuml.core.mjs",
"types": "dist/detector.d.ts",
@ -33,7 +33,7 @@
],
"license": "MIT",
"dependencies": {
"@zenuml/core": "^3.0.0"
"@zenuml/core": "^3.0.6"
},
"devDependencies": {
"mermaid": "workspace:^"

View File

@ -1,6 +1,6 @@
{
"name": "mermaid",
"version": "10.2.4",
"version": "10.3.1",
"description": "Markdown-ish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.",
"type": "module",
"module": "./dist/mermaid.core.mjs",
@ -24,15 +24,18 @@
],
"scripts": {
"clean": "rimraf dist",
"dev": "pnpm -w dev",
"docs:code": "typedoc src/defaultConfig.ts src/config.ts src/mermaidAPI.ts && prettier --write ./src/docs/config/setup",
"docs:build": "rimraf ../../docs && pnpm docs:spellcheck && pnpm docs:code && ts-node-esm src/docs.mts",
"docs:verify": "pnpm docs:spellcheck && pnpm docs:code && ts-node-esm src/docs.mts --verify",
"docs:pre:vitepress": "pnpm --filter ./src/docs prefetch && rimraf src/vitepress && pnpm docs:code && ts-node-esm src/docs.mts --vitepress && pnpm --filter ./src/vitepress install --no-frozen-lockfile --ignore-scripts",
"docs:build": "rimraf ../../docs && pnpm docs:spellcheck && pnpm docs:code && ts-node-esm scripts/docs.cli.mts",
"docs:verify": "pnpm docs:spellcheck && pnpm docs:code && ts-node-esm scripts/docs.cli.mts --verify",
"docs:pre:vitepress": "pnpm --filter ./src/docs prefetch && rimraf src/vitepress && pnpm docs:code && ts-node-esm scripts/docs.cli.mts --vitepress && pnpm --filter ./src/vitepress install --no-frozen-lockfile --ignore-scripts",
"docs:build:vitepress": "pnpm docs:pre:vitepress && (cd src/vitepress && pnpm run build) && cpy --flat src/docs/landing/ ./src/vitepress/.vitepress/dist/landing",
"docs:dev": "pnpm docs:pre:vitepress && concurrently \"pnpm --filter ./src/vitepress dev\" \"ts-node-esm src/docs.mts --watch --vitepress\"",
"docs:dev:docker": "pnpm docs:pre:vitepress && concurrently \"pnpm --filter ./src/vitepress dev:docker\" \"ts-node-esm src/docs.mts --watch --vitepress\"",
"docs:dev": "pnpm docs:pre:vitepress && concurrently \"pnpm --filter ./src/vitepress dev\" \"ts-node-esm scripts/docs.cli.mts --watch --vitepress\"",
"docs:dev:docker": "pnpm docs:pre:vitepress && concurrently \"pnpm --filter ./src/vitepress dev:docker\" \"ts-node-esm scripts/docs.cli.mts --watch --vitepress\"",
"docs:serve": "pnpm docs:build:vitepress && vitepress serve src/vitepress",
"docs:spellcheck": "cspell --config ../../cSpell.json \"src/docs/**/*.md\"",
"docs:release-version": "ts-node-esm scripts/update-release-version.mts",
"docs:verify-version": "ts-node-esm scripts/update-release-version.mts --verify",
"types:build-config": "ts-node-esm --transpileOnly scripts/create-types-from-json-schema.mts",
"types:verify-config": "ts-node-esm scripts/create-types-from-json-schema.mts --verify",
"release": "pnpm build",
@ -55,7 +58,7 @@
]
},
"dependencies": {
"@braintree/sanitize-url": "^6.0.2",
"@braintree/sanitize-url": "^6.0.1",
"@types/d3-scale": "^4.0.3",
"@types/d3-scale-chromatic": "^3.0.0",
"cytoscape": "^3.23.0",
@ -65,7 +68,7 @@
"d3-sankey": "^0.12.3",
"dagre-d3-es": "7.0.10",
"dayjs": "^1.11.7",
"dompurify": "3.0.5",
"dompurify": "^3.0.5",
"elkjs": "^0.8.2",
"khroma": "^2.0.0",
"lodash-es": "^4.17.21",

View File

@ -18,6 +18,7 @@ import { promisify } from 'node:util';
import { load, JSON_SCHEMA } from 'js-yaml';
import { compile, type JSONSchema } from 'json-schema-to-typescript';
import prettier from 'prettier';
import _Ajv2019, { type JSONSchemaType } from 'ajv/dist/2019.js';
@ -208,6 +209,7 @@ async function generateTypescript(mermaidConfigSchema: JSONSchemaType<MermaidCon
{
additionalProperties: false, // in JSON Schema 2019-09, these are called `unevaluatedProperties`
unreachableDefinitions: true, // definition for FontConfig is unreachable
style: (await prettier.resolveConfig('.')) ?? {},
}
);

View File

@ -0,0 +1,3 @@
import { processDocs } from './docs.mjs';
void processDocs();

View File

@ -27,14 +27,21 @@
* get their absolute paths. Ensures that the location of those 2 directories is not dependent on
* where this file resides.
*
* @todo Write a test file for this. (Will need to be able to deal .mts file. Jest has trouble with
* it.)
*/
// @ts-ignore: we're importing internal jsonschema2md functions
import { default as schemaLoader } from '@adobe/jsonschema2md/lib/schemaProxy.js';
// @ts-ignore: we're importing internal jsonschema2md functions
import { default as traverseSchemas } from '@adobe/jsonschema2md/lib/traverseSchema.js';
// @ts-ignore: we're importing internal jsonschema2md functions
import { default as buildMarkdownFromSchema } from '@adobe/jsonschema2md/lib/markdownBuilder.js';
// @ts-ignore: we're importing internal jsonschema2md functions
import { default as jsonSchemaReadmeBuilder } from '@adobe/jsonschema2md/lib/readmeBuilder.js';
import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, rmdirSync } from 'fs';
import { exec } from 'child_process';
import { globby } from 'globby';
import { JSDOM } from 'jsdom';
import type { Code, ListItem, Root, Text } from 'mdast';
import { dump, load, JSON_SCHEMA } from 'js-yaml';
import type { Code, ListItem, Root, Text, YAML } from 'mdast';
import { posix, dirname, relative, join } from 'path';
import prettier from 'prettier';
import { remark } from 'remark';
@ -46,9 +53,9 @@ import mm from 'micromatch';
import flatmap from 'unist-util-flatmap';
import { visit } from 'unist-util-visit';
const MERMAID_MAJOR_VERSION = (
JSON.parse(readFileSync('../mermaid/package.json', 'utf8')).version as string
).split('.')[0];
export const MERMAID_RELEASE_VERSION = JSON.parse(readFileSync('../mermaid/package.json', 'utf8'))
.version as string;
const MERMAID_MAJOR_VERSION = MERMAID_RELEASE_VERSION.split('.')[0];
const CDN_URL = 'https://cdn.jsdelivr.net/npm'; // 'https://unpkg.com';
const MERMAID_KEYWORD = 'mermaid';
@ -71,7 +78,7 @@ const vitepress: boolean = process.argv.includes('--vitepress');
const noHeader: boolean = process.argv.includes('--noHeader') || vitepress;
// These paths are from the root of the mono-repo, not from the mermaid subdirectory
const SOURCE_DOCS_DIR = 'src/docs';
export const SOURCE_DOCS_DIR = 'src/docs';
const FINAL_DOCS_DIR = vitepress ? 'src/vitepress' : '../../docs';
const LOGMSG_TRANSFORMED = 'transformed';
@ -158,7 +165,7 @@ const copyTransformedContents = (filename: string, doCopy = false, transformedCo
logWasOrShouldBeTransformed(fileInFinalDocDir, doCopy);
};
const readSyncedUTF8file = (filename: string): string => {
export const readSyncedUTF8file = (filename: string): string => {
return readFileSync(filename, 'utf8');
};
@ -209,6 +216,8 @@ interface TransformMarkdownAstOptions {
originalFilename: string;
/** If `true`, add a warning that the file is autogenerated */
addAutogeneratedWarning?: boolean;
/** If `true`, adds an `editLink: "https://..."` YAML frontmatter field */
addEditLink?: boolean;
/**
* If `true`, remove the YAML metadata from the Markdown input.
* Generally, YAML metadata is only used for Vitepress.
@ -231,6 +240,7 @@ interface TransformMarkdownAstOptions {
export function transformMarkdownAst({
originalFilename,
addAutogeneratedWarning,
addEditLink,
removeYAML,
}: TransformMarkdownAstOptions) {
return (tree: Root, _file?: any): Root => {
@ -270,6 +280,27 @@ export function transformMarkdownAst({
}
}
if (addEditLink) {
// add originalFilename as custom editLink in YAML frontmatter
let yamlFrontMatter: YAML;
if (astWithTransformedBlocks.children[0].type === 'yaml') {
yamlFrontMatter = astWithTransformedBlocks.children[0];
} else {
yamlFrontMatter = {
type: 'yaml',
value: '',
};
astWithTransformedBlocks.children.unshift(yamlFrontMatter);
}
const filePathFromRoot = posix.join('packages/mermaid', originalFilename);
yamlFrontMatter.value = dump({
...(load(yamlFrontMatter.value, { schema: JSON_SCHEMA }) as
| Record<string, unknown>
| undefined),
editLink: `https://github.com/mermaid-js/mermaid/edit/develop/${filePathFromRoot}`,
});
}
if (removeYAML) {
const firstNode = astWithTransformedBlocks.children[0];
if (firstNode.type == 'yaml') {
@ -306,6 +337,7 @@ const transformMarkdown = (file: string) => {
// mermaid project specific plugin
originalFilename: file,
addAutogeneratedWarning: !noHeader,
addEditLink: noHeader,
removeYAML: !noHeader,
})
.processSync(doc)
@ -323,20 +355,10 @@ const transformMarkdown = (file: string) => {
copyTransformedContents(file, !verifyOnly, formatted);
};
import { load, JSON_SCHEMA } from 'js-yaml';
// @ts-ignore: we're importing internal jsonschema2md functions
import { default as schemaLoader } from '@adobe/jsonschema2md/lib/schemaProxy.js';
// @ts-ignore: we're importing internal jsonschema2md functions
import { default as traverseSchemas } from '@adobe/jsonschema2md/lib/traverseSchema.js';
// @ts-ignore: we're importing internal jsonschema2md functions
import { default as buildMarkdownFromSchema } from '@adobe/jsonschema2md/lib/markdownBuilder.js';
// @ts-ignore: we're importing internal jsonschema2md functions
import { default as jsonSchemaReadmeBuilder } from '@adobe/jsonschema2md/lib/readmeBuilder.js';
/**
* Transforms the given JSON Schema into Markdown documentation
*/
async function transormJsonSchema(file: string) {
async function transformJsonSchema(file: string) {
const yamlContents = readSyncedUTF8file(file);
const jsonSchema = load(yamlContents, {
filename: file,
@ -420,16 +442,18 @@ async function transormJsonSchema(file: string) {
}
});
const transformed = remark()
const transformer = remark()
.use(remarkGfm)
.use(remarkFrontmatter, ['yaml']) // support YAML front-matter in Markdown
.use(transformMarkdownAst, {
// mermaid project specific plugin
originalFilename: file,
addAutogeneratedWarning: !noHeader,
addEditLink: noHeader,
removeYAML: !noHeader,
})
.stringify(markdownAst as Root);
});
const transformed = transformer.stringify(await transformer.run(markdownAst as Root));
const formatted = prettier.format(transformed, {
parser: 'markdown',
@ -480,7 +504,7 @@ const transformHtml = (filename: string) => {
copyTransformedContents(filename, !verifyOnly, formattedHTML);
};
const getGlobs = (globs: string[]): string[] => {
export const getGlobs = (globs: string[]): string[] => {
globs.push('!**/dist/**', '!**/redirect.spec.ts', '!**/landing/**', '!**/node_modules/**');
if (!vitepress) {
globs.push(
@ -494,12 +518,12 @@ const getGlobs = (globs: string[]): string[] => {
return globs;
};
const getFilesFromGlobs = async (globs: string[]): Promise<string[]> => {
export const getFilesFromGlobs = async (globs: string[]): Promise<string[]> => {
return await globby(globs, { dot: true });
};
/** Main method (entry point) */
const main = async () => {
export const processDocs = async () => {
if (verifyOnly) {
console.log('Verifying that all files are in sync with the source files');
}
@ -509,7 +533,7 @@ const main = async () => {
if (vitepress) {
console.log(`${action} 1 .schema.yaml file`);
await transormJsonSchema('src/schemas/config.schema.yaml');
await transformJsonSchema('src/schemas/config.schema.yaml');
} else {
// skip because this creates so many Markdown files that it lags git
console.log('Skipping 1 .schema.yaml file');
@ -577,5 +601,3 @@ const main = async () => {
});
}
};
void main();

View File

@ -105,6 +105,29 @@ This Markdown should be kept.
});
});
it('should add an editLink in the YAML frontmatter if `addEditLink: true`', async () => {
const contents = `---
title: Flowcharts Syntax
---
This Markdown should be kept.
`;
const withYaml = (
await remarkBuilder()
.use(transformMarkdownAst, { originalFilename, addEditLink: true })
.process(contents)
).toString();
expect(withYaml).toEqual(`---
title: Flowcharts Syntax
editLink: >-
https://github.com/mermaid-js/mermaid/edit/develop/packages/mermaid/example-input-filename.md
---
This Markdown should be kept.
`);
});
describe('transformToBlockQuote', () => {
// TODO Is there a way to test this with --vitepress given as a process argument?

View File

@ -0,0 +1,53 @@
/* eslint-disable no-console */
/**
* @file Update the MERMAID_RELEASE_VERSION placeholder in the documentation source files with the current version of mermaid.
* So contributors adding new features will only have to add the placeholder and not worry about updating the version number.
*
*/
import { posix } from 'path';
import {
getGlobs,
getFilesFromGlobs,
SOURCE_DOCS_DIR,
readSyncedUTF8file,
MERMAID_RELEASE_VERSION,
} from './docs.mjs';
import { writeFile } from 'fs/promises';
const verifyOnly: boolean = process.argv.includes('--verify');
const versionPlaceholder = '<MERMAID_RELEASE_VERSION>';
const main = async () => {
const sourceDirGlob = posix.join('.', SOURCE_DOCS_DIR, '**');
const mdFileGlobs = getGlobs([posix.join(sourceDirGlob, '*.md')]);
mdFileGlobs.push('!**/community/development.md');
const mdFiles = await getFilesFromGlobs(mdFileGlobs);
mdFiles.sort();
const mdFilesWithPlaceholder: string[] = [];
for (const mdFile of mdFiles) {
const content = readSyncedUTF8file(mdFile);
if (content.includes(versionPlaceholder)) {
mdFilesWithPlaceholder.push(mdFile);
}
}
if (mdFilesWithPlaceholder.length === 0) {
return;
}
if (verifyOnly) {
console.log(
`${mdFilesWithPlaceholder.length} file(s) were found with the placeholder ${versionPlaceholder}. Run \`pnpm --filter mermaid docs:release-version\` to update them.`
);
process.exit(1);
}
for (const mdFile of mdFilesWithPlaceholder) {
const content = readSyncedUTF8file(mdFile);
const newContent = content.replace(versionPlaceholder, MERMAID_RELEASE_VERSION);
await writeFile(mdFile, newContent);
}
};
void main();

View File

@ -4,8 +4,9 @@ import { getDiagram, registerDiagram } from './diagram-api/diagramAPI.js';
import { detectType, getDiagramLoader } from './diagram-api/detectType.js';
import { extractFrontMatter } from './diagram-api/frontmatter.js';
import { UnknownDiagramError } from './errors.js';
import { DetailedError } from './utils.js';
import { cleanupComments } from './diagram-api/comments.js';
import type { DetailedError } from './utils.js';
import type { DiagramDefinition } from './diagram-api/types.js';
export type ParseErrorFunction = (err: string | DetailedError | unknown, hash?: any) => void;
@ -15,9 +16,11 @@ export type ParseErrorFunction = (err: string | DetailedError | unknown, hash?:
*/
export class Diagram {
type = 'graph';
parser;
renderer;
db;
parser: DiagramDefinition['parser'];
renderer: DiagramDefinition['renderer'];
db: DiagramDefinition['db'];
private init?: DiagramDefinition['init'];
private detectError?: UnknownDiagramError;
constructor(public text: string) {
this.text += '\n';
@ -32,7 +35,6 @@ export class Diagram {
log.debug('Type ' + this.type);
// Setup diagram
this.db = diagram.db;
this.db.clear?.();
this.renderer = diagram.renderer;
this.parser = diagram.parser;
const originalParse = this.parser.parse.bind(this.parser);
@ -49,10 +51,7 @@ export class Diagram {
originalParse(cleanupComments(extractFrontMatter(text, this.db)));
this.parser.parser.yy = this.db;
if (diagram.init) {
diagram.init(cnf);
log.info('Initialized diagram ' + this.type, cnf);
}
this.init = diagram.init;
this.parse();
}
@ -61,6 +60,7 @@ export class Diagram {
throw this.detectError;
}
this.db.clear?.();
this.init?.(configApi.getConfig());
this.parser.parse(this.text);
}

View File

@ -1,32 +1,36 @@
'use strict';
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* @function assignWithDepth Extends the functionality of {@link ObjectConstructor.assign} with the
* assignWithDepth Extends the functionality of {@link ObjectConstructor.assign} with the
* ability to merge arbitrary-depth objects For each key in src with path `k` (recursively)
* performs an Object.assign(dst[`k`], src[`k`]) with a slight change from the typical handling of
* undefined for dst[`k`]: instead of raising an error, dst[`k`] is auto-initialized to {} and
* undefined for dst[`k`]: instead of raising an error, dst[`k`] is auto-initialized to `{}` and
* effectively merged with src[`k`]<p> Additionally, dissimilar types will not clobber unless the
* config.clobber parameter === true. Example:
*
* ```js
* let config_0 = { foo: { bar: 'bar' }, bar: 'foo' };
* let config_1 = { foo: 'foo', bar: 'bar' };
* let result = assignWithDepth(config_0, config_1);
* console.log(result);
* //-> result: { foo: { bar: 'bar' }, bar: 'bar' }
* ```
* ```
* const config_0 = { foo: { bar: 'bar' }, bar: 'foo' };
* const config_1 = { foo: 'foo', bar: 'bar' };
* const result = assignWithDepth(config_0, config_1);
* console.log(result);
* //-> result: { foo: { bar: 'bar' }, bar: 'bar' }
* ```
*
* Traditional Object.assign would have clobbered foo in config_0 with foo in config_1. If src is a
* destructured array of objects and dst is not an array, assignWithDepth will apply each element
* of src to dst in order.
* @param {any} dst - The destination of the merge
* @param {any} src - The source object(s) to merge into destination
* @param {{ depth: number; clobber: boolean }} [config] - Depth: depth
* to traverse within src and dst for merging - clobber: should dissimilar types clobber (default:
* { depth: 2, clobber: false }). Default is `{ depth: 2, clobber: false }`
* @returns {any}
* @param dst - The destination of the merge
* @param src - The source object(s) to merge into destination
* @param config -
* * depth: depth to traverse within src and dst for merging
* * clobber: should dissimilar types clobber
*/
const assignWithDepth = function (dst, src, config) {
const { depth, clobber } = Object.assign({ depth: 2, clobber: false }, config);
const assignWithDepth = (
dst: any,
src: any,
{ depth = 2, clobber = false }: { depth?: number; clobber?: boolean } = {}
): any => {
const config: { depth: number; clobber: boolean } = { depth, clobber };
if (Array.isArray(src) && !Array.isArray(dst)) {
src.forEach((s) => assignWithDepth(dst, s, config));
return dst;

View File

@ -8,8 +8,25 @@ import note from './shapes/note.js';
import { parseMember } from '../diagrams/class/svgDraw.js';
import { evaluate } from '../diagrams/common/common.js';
const formatClass = (str) => {
if (str) {
return ' ' + str;
}
return '';
};
const getClassesFromNode = (node, otherClasses) => {
return `${otherClasses ? otherClasses : 'node default'}${formatClass(node.classes)} ${formatClass(
node.class
)}`;
};
const question = async (parent, node) => {
const { shapeSvg, bbox } = await labelHelper(parent, node, undefined, true);
const { shapeSvg, bbox } = await labelHelper(
parent,
node,
getClassesFromNode(node, undefined),
true
);
const w = bbox.width + node.padding;
const h = bbox.height + node.padding;
@ -70,7 +87,12 @@ const choice = (parent, node) => {
};
const hexagon = async (parent, node) => {
const { shapeSvg, bbox } = await labelHelper(parent, node, undefined, true);
const { shapeSvg, bbox } = await labelHelper(
parent,
node,
getClassesFromNode(node, undefined),
true
);
const f = 4;
const h = bbox.height + node.padding;
@ -97,7 +119,12 @@ const hexagon = async (parent, node) => {
};
const rect_left_inv_arrow = async (parent, node) => {
const { shapeSvg, bbox } = await labelHelper(parent, node, undefined, true);
const { shapeSvg, bbox } = await labelHelper(
parent,
node,
getClassesFromNode(node, undefined),
true
);
const w = bbox.width + node.padding;
const h = bbox.height + node.padding;
@ -123,7 +150,7 @@ const rect_left_inv_arrow = async (parent, node) => {
};
const lean_right = async (parent, node) => {
const { shapeSvg, bbox } = await labelHelper(parent, node, undefined, true);
const { shapeSvg, bbox } = await labelHelper(parent, node, getClassesFromNode(node), true);
const w = bbox.width + node.padding;
const h = bbox.height + node.padding;
@ -146,7 +173,12 @@ const lean_right = async (parent, node) => {
};
const lean_left = async (parent, node) => {
const { shapeSvg, bbox } = await labelHelper(parent, node, undefined, true);
const { shapeSvg, bbox } = await labelHelper(
parent,
node,
getClassesFromNode(node, undefined),
true
);
const w = bbox.width + node.padding;
const h = bbox.height + node.padding;
@ -169,7 +201,12 @@ const lean_left = async (parent, node) => {
};
const trapezoid = async (parent, node) => {
const { shapeSvg, bbox } = await labelHelper(parent, node, undefined, true);
const { shapeSvg, bbox } = await labelHelper(
parent,
node,
getClassesFromNode(node, undefined),
true
);
const w = bbox.width + node.padding;
const h = bbox.height + node.padding;
@ -192,7 +229,12 @@ const trapezoid = async (parent, node) => {
};
const inv_trapezoid = async (parent, node) => {
const { shapeSvg, bbox } = await labelHelper(parent, node, undefined, true);
const { shapeSvg, bbox } = await labelHelper(
parent,
node,
getClassesFromNode(node, undefined),
true
);
const w = bbox.width + node.padding;
const h = bbox.height + node.padding;
@ -215,7 +257,12 @@ const inv_trapezoid = async (parent, node) => {
};
const rect_right_inv_arrow = async (parent, node) => {
const { shapeSvg, bbox } = await labelHelper(parent, node, undefined, true);
const { shapeSvg, bbox } = await labelHelper(
parent,
node,
getClassesFromNode(node, undefined),
true
);
const w = bbox.width + node.padding;
const h = bbox.height + node.padding;
@ -239,7 +286,12 @@ const rect_right_inv_arrow = async (parent, node) => {
};
const cylinder = async (parent, node) => {
const { shapeSvg, bbox } = await labelHelper(parent, node, undefined, true);
const { shapeSvg, bbox } = await labelHelper(
parent,
node,
getClassesFromNode(node, undefined),
true
);
const w = bbox.width + node.padding;
const rx = w / 2;
@ -314,7 +366,7 @@ const rect = async (parent, node) => {
const { shapeSvg, bbox, halfPadding } = await labelHelper(
parent,
node,
'node ' + node.classes,
'node ' + node.classes + ' ' + node.class,
true
);
@ -360,7 +412,7 @@ const rect = async (parent, node) => {
const labelRect = async (parent, node) => {
const { shapeSvg } = await labelHelper(parent, node, 'label', true);
log.trace('Classes = ', node.classes);
log.trace('Classes = ', node.class);
// add the rect
const rect = shapeSvg.insert('rect', ':first-child');
@ -545,7 +597,12 @@ const rectWithTitle = (parent, node) => {
};
const stadium = async (parent, node) => {
const { shapeSvg, bbox } = await labelHelper(parent, node, undefined, true);
const { shapeSvg, bbox } = await labelHelper(
parent,
node,
getClassesFromNode(node, undefined),
true
);
const h = bbox.height + node.padding;
const w = bbox.width + h / 4 + node.padding;
@ -571,7 +628,12 @@ const stadium = async (parent, node) => {
};
const circle = async (parent, node) => {
const { shapeSvg, bbox, halfPadding } = await labelHelper(parent, node, undefined, true);
const { shapeSvg, bbox, halfPadding } = await labelHelper(
parent,
node,
getClassesFromNode(node, undefined),
true
);
const circle = shapeSvg.insert('circle', ':first-child');
// center the circle around its coordinate
@ -596,7 +658,12 @@ const circle = async (parent, node) => {
};
const doublecircle = async (parent, node) => {
const { shapeSvg, bbox, halfPadding } = await labelHelper(parent, node, undefined, true);
const { shapeSvg, bbox, halfPadding } = await labelHelper(
parent,
node,
getClassesFromNode(node, undefined),
true
);
const gap = 5;
const circleGroup = shapeSvg.insert('g', ':first-child');
const outerCircle = circleGroup.insert('circle');
@ -634,7 +701,12 @@ const doublecircle = async (parent, node) => {
};
const subroutine = async (parent, node) => {
const { shapeSvg, bbox } = await labelHelper(parent, node, undefined, true);
const { shapeSvg, bbox } = await labelHelper(
parent,
node,
getClassesFromNode(node, undefined),
true
);
const w = bbox.width + node.padding;
const h = bbox.height + node.padding;

View File

@ -13,6 +13,7 @@ export const labelHelper = async (parent, node, _classes, isNode) => {
} else {
classes = _classes;
}
// Add outer g element
const shapeSvg = parent
.insert('g')
@ -49,7 +50,6 @@ export const labelHelper = async (parent, node, _classes, isNode) => {
)
);
}
// Get the size of the label
let bbox = text.getBBox();
const halfPadding = node.padding / 2;

View File

@ -35,7 +35,12 @@ describe('DiagramAPI', () => {
'loki',
{
db: {},
parser: {},
parser: {
parse: (_text) => {
return;
},
parser: { yy: {} },
},
renderer: {},
styles: {},
},

View File

@ -69,11 +69,11 @@ export const getDiagram = (name: string): DiagramDefinition => {
if (name in diagrams) {
return diagrams[name];
}
throw new Error(`Diagram ${name} not found.`);
throw new DiagramNotFoundError(name);
};
export class DiagramNotFoundError extends Error {
constructor(message: string) {
super(`Diagram ${message} not found.`);
constructor(name: string) {
super(`Diagram ${name} not found.`);
}
}

View File

@ -1,5 +1,5 @@
import { Diagram } from '../Diagram.js';
import { MermaidConfig } from '../config.type.js';
import type { MermaidConfig } from '../config.type.js';
import type * as d3 from 'd3';
export interface InjectUtils {
@ -27,7 +27,7 @@ export interface DiagramDB {
export interface DiagramDefinition {
db: DiagramDB;
renderer: any;
parser: any;
parser: ParserDefinition;
styles?: any;
init?: (config: MermaidConfig) => void;
injectUtils?: (
@ -70,6 +70,11 @@ export type DrawDefinition = (
diagramObject: Diagram
) => void;
export interface ParserDefinition {
parse: (text: string) => void;
parser: { yy: DiagramDB };
}
/**
* Type for function parse directive from diagram code.
*
@ -79,8 +84,10 @@ export type DrawDefinition = (
*/
export type ParseDirectiveDefinition = (statement: string, context: string, type: string) => void;
export type HTML = d3.Selection<HTMLIFrameElement, unknown, Element, unknown>;
export type HTML = d3.Selection<HTMLIFrameElement, unknown, Element | null, unknown>;
export type SVG = d3.Selection<SVGSVGElement, unknown, Element, unknown>;
export type SVG = d3.Selection<SVGSVGElement, unknown, Element | null, unknown>;
export type Group = d3.Selection<SVGGElement, unknown, Element | null, unknown>;
export type DiagramStylesProvider = (options?: any) => string;

View File

@ -49,7 +49,7 @@ describe('diagram detection', () => {
"Parse error on line 2:
graph TD; A-->
--------------^
Expecting 'AMP', 'ALPHA', 'COLON', 'PIPE', 'TESTSTR', 'DOWN', 'DEFAULT', 'NUM', 'COMMA', 'MINUS', 'BRKT', 'DOT', 'PUNCTUATION', 'UNICODE_TEXT', 'PLUS', 'EQUALS', 'MULT', 'UNDERSCORE', got 'EOF'"
Expecting 'AMP', 'COLON', 'PIPE', 'TESTSTR', 'DOWN', 'DEFAULT', 'NUM', 'COMMA', 'NODE_STRING', 'BRKT', 'MINUS', 'MULT', 'UNICODE_TEXT', got 'EOF'"
`);
await expect(getDiagramFromText('sequenceDiagram; A-->B')).rejects
.toThrowErrorMatchingInlineSnapshot(`

View File

@ -1,4 +1,4 @@
// @ts-ignore: TODO Fix ts errors
// @ts-ignore: JISON doesn't support types
import c4Parser from './parser/c4Diagram.jison';
import c4Db from './c4Db.js';
import c4Renderer from './c4Renderer.js';

View File

@ -1,5 +1,5 @@
import common from '../common/common.js';
import * as svgDrawCommon from '../common/svgDrawCommon';
import * as svgDrawCommon from '../common/svgDrawCommon.js';
import { sanitizeUrl } from '@braintree/sanitize-url';
export const drawRect = function (elem, rectData) {

View File

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

View File

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

View File

@ -1,16 +0,0 @@
import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
// @ts-ignore - no types
import { LALRGenerator } from 'jison';
const getAbsolutePath = (relativePath: string) => {
return fileURLToPath(new URL(relativePath, import.meta.url));
};
describe('class diagram grammar', function () {
it('should have no conflicts', async function () {
const grammarSource = await readFile(getAbsolutePath('./parser/classDiagram.jison'), 'utf8');
const grammarParser = new LALRGenerator(grammarSource, {});
expect(grammarParser.conflicts).toBe(0);
});
});

View File

@ -1,15 +1,15 @@
import { sanitizeText, removeScript, parseGenericTypes } from './common.js';
describe('when securityLevel is antiscript, all script must be removed', function () {
describe('when securityLevel is antiscript, all script must be removed', () => {
/**
* @param {string} original The original text
* @param {string} result The expected sanitized text
* @param original - The original text
* @param result - The expected sanitized text
*/
function compareRemoveScript(original, result) {
function compareRemoveScript(original: string, result: string) {
expect(removeScript(original).trim()).toEqual(result);
}
it('should remove all script block, script inline.', function () {
it('should remove all script block, script inline.', () => {
const labelString = `1
Act1: Hello 1<script src="http://abc.com/script1.js"></script>1
<b>Act2</b>:
@ -25,7 +25,7 @@ describe('when securityLevel is antiscript, all script must be removed', functio
compareRemoveScript(labelString, exactlyString);
});
it('should remove all javascript urls', function () {
it('should remove all javascript urls', () => {
compareRemoveScript(
`This is a <a href="javascript:runHijackingScript();">clean link</a> + <a href="javascript:runHijackingScript();">clean link</a>
and <a href="javascript&colon;bipassedMining();">me too</a>`,
@ -34,11 +34,11 @@ describe('when securityLevel is antiscript, all script must be removed', functio
);
});
it('should detect malicious images', function () {
it('should detect malicious images', () => {
compareRemoveScript(`<img onerror="alert('hello');">`, `<img>`);
});
it('should detect iframes', function () {
it('should detect iframes', () => {
compareRemoveScript(
`<iframe src="http://abc.com/script1.js"></iframe>
<iframe src="http://example.com/iframeexample"></iframe>`,
@ -47,8 +47,8 @@ describe('when securityLevel is antiscript, all script must be removed', functio
});
});
describe('Sanitize text', function () {
it('should remove script tag', function () {
describe('Sanitize text', () => {
it('should remove script tag', () => {
const maliciousStr = 'javajavascript:script:alert(1)';
const result = sanitizeText(maliciousStr, {
securityLevel: 'strict',
@ -58,8 +58,8 @@ describe('Sanitize text', function () {
});
});
describe('generic parser', function () {
it('should parse generic types', function () {
describe('generic parser', () => {
it('should parse generic types', () => {
expect(parseGenericTypes('test~T~')).toEqual('test<T>');
expect(parseGenericTypes('test~Array~Array~string~~~')).toEqual('test<Array<Array<string>>>');
expect(parseGenericTypes('test~Array~Array~string[]~~~')).toEqual(

View File

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

View File

@ -0,0 +1,58 @@
export interface RectData {
x: number;
y: number;
fill: string;
width: number;
height: number;
stroke: string;
class?: string;
color?: string;
rx?: number;
ry?: number;
attrs?: Record<string, string | number>;
anchor?: string;
}
export interface Bound {
startx: number;
stopx: number;
starty: number;
stopy: number;
fill: string;
stroke: string;
}
export interface TextData {
x: number;
y: number;
anchor: string;
text: string;
textMargin: number;
class?: string;
}
export interface TextObject {
x: number;
y: number;
width: number;
height: number;
fill?: string;
anchor?: string;
'text-anchor': string;
style: string;
textMargin: number;
rx: number;
ry: number;
tspan: boolean;
valign?: string;
}
export type D3RectElement = d3.Selection<SVGRectElement, unknown, Element | null, unknown>;
export type D3UseElement = d3.Selection<SVGUseElement, unknown, Element | null, unknown>;
export type D3ImageElement = d3.Selection<SVGImageElement, unknown, Element | null, unknown>;
export type D3TextElement = d3.Selection<SVGTextElement, unknown, Element | null, unknown>;
export type D3TSpanElement = d3.Selection<SVGTSpanElement, unknown, Element | null, unknown>;

View File

@ -1,114 +0,0 @@
import { sanitizeUrl } from '@braintree/sanitize-url';
export const drawRect = function (elem, rectData) {
const rectElem = elem.append('rect');
rectElem.attr('x', rectData.x);
rectElem.attr('y', rectData.y);
rectElem.attr('fill', rectData.fill);
rectElem.attr('stroke', rectData.stroke);
rectElem.attr('width', rectData.width);
rectElem.attr('height', rectData.height);
rectElem.attr('rx', rectData.rx);
rectElem.attr('ry', rectData.ry);
if (rectData.attrs !== 'undefined' && rectData.attrs !== null) {
for (let attrKey in rectData.attrs) {
rectElem.attr(attrKey, rectData.attrs[attrKey]);
}
}
if (rectData.class !== 'undefined') {
rectElem.attr('class', rectData.class);
}
return rectElem;
};
/**
* Draws a background rectangle
*
* @param {any} elem Diagram (reference for bounds)
* @param {any} bounds Shape of the rectangle
*/
export const drawBackgroundRect = function (elem, bounds) {
const rectElem = drawRect(elem, {
x: bounds.startx,
y: bounds.starty,
width: bounds.stopx - bounds.startx,
height: bounds.stopy - bounds.starty,
fill: bounds.fill,
stroke: bounds.stroke,
class: 'rect',
});
rectElem.lower();
};
export const drawText = function (elem, textData) {
// Remove and ignore br:s
const nText = textData.text.replace(/<br\s*\/?>/gi, ' ');
const textElem = elem.append('text');
textElem.attr('x', textData.x);
textElem.attr('y', textData.y);
textElem.attr('class', 'legend');
textElem.style('text-anchor', textData.anchor);
if (textData.class !== undefined) {
textElem.attr('class', textData.class);
}
const span = textElem.append('tspan');
span.attr('x', textData.x + textData.textMargin * 2);
span.text(nText);
return textElem;
};
export const drawImage = function (elem, x, y, link) {
const imageElem = elem.append('image');
imageElem.attr('x', x);
imageElem.attr('y', y);
var sanitizedLink = sanitizeUrl(link);
imageElem.attr('xlink:href', sanitizedLink);
};
export const drawEmbeddedImage = function (elem, x, y, link) {
const imageElem = elem.append('use');
imageElem.attr('x', x);
imageElem.attr('y', y);
const sanitizedLink = sanitizeUrl(link);
imageElem.attr('xlink:href', '#' + sanitizedLink);
};
export const getNoteRect = function () {
return {
x: 0,
y: 0,
width: 100,
height: 100,
fill: '#EDF2AE',
stroke: '#666',
anchor: 'start',
rx: 0,
ry: 0,
};
};
export const getTextObj = function () {
return {
x: 0,
y: 0,
width: 100,
height: 100,
fill: undefined,
anchor: undefined,
'text-anchor': 'start',
style: '#666',
textMargin: 0,
rx: 0,
ry: 0,
tspan: true,
valign: undefined,
};
};

View File

@ -0,0 +1,126 @@
import { sanitizeUrl } from '@braintree/sanitize-url';
import type { Group, SVG } from '../../diagram-api/types.js';
import type {
Bound,
D3ImageElement,
D3RectElement,
D3TSpanElement,
D3TextElement,
D3UseElement,
RectData,
TextData,
TextObject,
} from './commonTypes.js';
import { lineBreakRegex } from './common.js';
export const drawRect = (element: SVG | Group, rectData: RectData): D3RectElement => {
const rectElement: D3RectElement = element.append('rect');
rectElement.attr('x', rectData.x);
rectElement.attr('y', rectData.y);
rectElement.attr('fill', rectData.fill);
rectElement.attr('stroke', rectData.stroke);
rectElement.attr('width', rectData.width);
rectElement.attr('height', rectData.height);
rectData.rx !== undefined && rectElement.attr('rx', rectData.rx);
rectData.ry !== undefined && rectElement.attr('ry', rectData.ry);
if (rectData.attrs !== undefined) {
for (const attrKey in rectData.attrs) {
rectElement.attr(attrKey, rectData.attrs[attrKey]);
}
}
rectData.class !== undefined && rectElement.attr('class', rectData.class);
return rectElement;
};
/**
* Draws a background rectangle
*
* @param element - Diagram (reference for bounds)
* @param bounds - Shape of the rectangle
*/
export const drawBackgroundRect = (element: SVG | Group, bounds: Bound): void => {
const rectData: RectData = {
x: bounds.startx,
y: bounds.starty,
width: bounds.stopx - bounds.startx,
height: bounds.stopy - bounds.starty,
fill: bounds.fill,
stroke: bounds.stroke,
class: 'rect',
};
const rectElement: D3RectElement = drawRect(element, rectData);
rectElement.lower();
};
export const drawText = (element: SVG | Group, textData: TextData): D3TextElement => {
const nText: string = textData.text.replace(lineBreakRegex, ' ');
const textElem: D3TextElement = element.append('text');
textElem.attr('x', textData.x);
textElem.attr('y', textData.y);
textElem.attr('class', 'legend');
textElem.style('text-anchor', textData.anchor);
textData.class !== undefined && textElem.attr('class', textData.class);
const tspan: D3TSpanElement = textElem.append('tspan');
tspan.attr('x', textData.x + textData.textMargin * 2);
tspan.text(nText);
return textElem;
};
export const drawImage = (elem: SVG | Group, x: number, y: number, link: string): void => {
const imageElement: D3ImageElement = elem.append('image');
imageElement.attr('x', x);
imageElement.attr('y', y);
const sanitizedLink: string = sanitizeUrl(link);
imageElement.attr('xlink:href', sanitizedLink);
};
export const drawEmbeddedImage = (
element: SVG | Group,
x: number,
y: number,
link: string
): void => {
const imageElement: D3UseElement = element.append('use');
imageElement.attr('x', x);
imageElement.attr('y', y);
const sanitizedLink: string = sanitizeUrl(link);
imageElement.attr('xlink:href', `#${sanitizedLink}`);
};
export const getNoteRect = (): RectData => {
const noteRectData: RectData = {
x: 0,
y: 0,
width: 100,
height: 100,
fill: '#EDF2AE',
stroke: '#666',
anchor: 'start',
rx: 0,
ry: 0,
};
return noteRectData;
};
export const getTextObj = (): TextObject => {
const testObject: TextObject = {
x: 0,
y: 0,
width: 100,
height: 100,
'text-anchor': 'start',
style: '#666',
textMargin: 0,
rx: 0,
ry: 0,
tspan: true,
};
return testObject;
};

View File

@ -555,7 +555,6 @@ const drawRelationshipFromLayout = function (svg, rel, g, insert, diagObj) {
export const draw = function (text, id, _version, diagObj) {
conf = getConfig().er;
log.info('Drawing ER diagram');
// diag.db.clear();
const securityLevel = getConfig().securityLevel;
// Handle root and Document for when rendering in sandbox mode
let sandboxElement;

View File

@ -1,23 +1,15 @@
import { DiagramDefinition } from '../../diagram-api/types.js';
import styles from './styles.js';
import renderer from './errorRenderer.js';
export const diagram: DiagramDefinition = {
db: {
clear: () => {
// Quite ok, clear needs to be there for error to work as a regular diagram
},
},
styles,
import type { DiagramDefinition } from '../../diagram-api/types.js';
import { renderer } from './errorRenderer.js';
const diagram: DiagramDefinition = {
db: {},
renderer,
parser: {
parser: { yy: {} },
parse: () => {
// no op
parse: (): void => {
return;
},
},
init: () => {
// no op
},
};
export default diagram;

View File

@ -1,100 +1,81 @@
/** Created by knut on 14-12-11. */
// @ts-ignore TODO: Investigate D3 issue
import { select } from 'd3';
import { log } from '../../logger.js';
import { getErrorMessage } from '../../utils.js';
/**
* Merges the value of `conf` with the passed `cnf`
*
* @param cnf - Config to merge
*/
export const setConf = function () {
// no-op
};
import type { Group, SVG } from '../../diagram-api/types.js';
import { selectSvgElement } from '../../rendering-util/selectSvgElement.js';
import { configureSvgSize } from '../../setupGraphViewbox.js';
/**
* Draws a an info picture in the tag with id: id based on the graph definition in text.
*
* @param _text - Mermaid graph definition.
* @param id - The text for the error
* @param mermaidVersion - The version
* @param version - The version
*/
export const draw = (_text: string, id: string, mermaidVersion: string) => {
try {
log.debug('Renering svg for syntax error\n');
export const draw = (_text: string, id: string, version: string) => {
log.debug('renering svg for syntax error\n');
const svg = select('#' + id);
const svg: SVG = selectSvgElement(id);
svg.attr('viewBox', '0 0 2412 512');
configureSvgSize(svg, 100, 512, true);
const g = svg.append('g');
const g: Group = svg.append('g');
g.append('path')
.attr('class', 'error-icon')
.attr(
'd',
'm411.313,123.313c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32-9.375,9.375-20.688-20.688c-12.484-12.5-32.766-12.5-45.25,0l-16,16c-1.261,1.261-2.304,2.648-3.31,4.051-21.739-8.561-45.324-13.426-70.065-13.426-105.867,0-192,86.133-192,192s86.133,192 192,192 192-86.133 192-192c0-24.741-4.864-48.327-13.426-70.065 1.402-1.007 2.79-2.049 4.051-3.31l16-16c12.5-12.492 12.5-32.758 0-45.25l-20.688-20.688 9.375-9.375 32.001-31.999zm-219.313,100.687c-52.938,0-96,43.063-96,96 0,8.836-7.164,16-16,16s-16-7.164-16-16c0-70.578 57.422-128 128-128 8.836,0 16,7.164 16,16s-7.164,16-16,16z'
);
g.append('path')
.attr('class', 'error-icon')
.attr(
'd',
'm411.313,123.313c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32-9.375,9.375-20.688-20.688c-12.484-12.5-32.766-12.5-45.25,0l-16,16c-1.261,1.261-2.304,2.648-3.31,4.051-21.739-8.561-45.324-13.426-70.065-13.426-105.867,0-192,86.133-192,192s86.133,192 192,192 192-86.133 192-192c0-24.741-4.864-48.327-13.426-70.065 1.402-1.007 2.79-2.049 4.051-3.31l16-16c12.5-12.492 12.5-32.758 0-45.25l-20.688-20.688 9.375-9.375 32.001-31.999zm-219.313,100.687c-52.938,0-96,43.063-96,96 0,8.836-7.164,16-16,16s-16-7.164-16-16c0-70.578 57.422-128 128-128 8.836,0 16,7.164 16,16s-7.164,16-16,16z'
);
g.append('path')
.attr('class', 'error-icon')
.attr(
'd',
'm459.02,148.98c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l16,16c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16.001-16z'
);
g.append('path')
.attr('class', 'error-icon')
.attr(
'd',
'm459.02,148.98c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l16,16c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16.001-16z'
);
g.append('path')
.attr('class', 'error-icon')
.attr(
'd',
'm340.395,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16-16c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l15.999,16z'
);
g.append('path')
.attr('class', 'error-icon')
.attr(
'd',
'm340.395,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16-16c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l15.999,16z'
);
g.append('path')
.attr('class', 'error-icon')
.attr(
'd',
'm400,64c8.844,0 16-7.164 16-16v-32c0-8.836-7.156-16-16-16-8.844,0-16,7.164-16,16v32c0,8.836 7.156,16 16,16z'
);
g.append('path')
.attr('class', 'error-icon')
.attr(
'd',
'm400,64c8.844,0 16-7.164 16-16v-32c0-8.836-7.156-16-16-16-8.844,0-16,7.164-16,16v32c0,8.836 7.156,16 16,16z'
);
g.append('path')
.attr('class', 'error-icon')
.attr(
'd',
'm496,96.586h-32c-8.844,0-16,7.164-16,16 0,8.836 7.156,16 16,16h32c8.844,0 16-7.164 16-16 0-8.836-7.156-16-16-16z'
);
g.append('path')
.attr('class', 'error-icon')
.attr(
'd',
'm496,96.586h-32c-8.844,0-16,7.164-16,16 0,8.836 7.156,16 16,16h32c8.844,0 16-7.164 16-16 0-8.836-7.156-16-16-16z'
);
g.append('path')
.attr('class', 'error-icon')
.attr(
'd',
'm436.98,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688l32-32c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32c-6.251,6.25-6.251,16.375-0.001,22.625z'
);
g.append('path')
.attr('class', 'error-icon')
.attr(
'd',
'm436.98,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688l32-32c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32c-6.251,6.25-6.251,16.375-0.001,22.625z'
);
g.append('text') // text label for the x axis
.attr('class', 'error-text')
.attr('x', 1440)
.attr('y', 250)
.attr('font-size', '150px')
.style('text-anchor', 'middle')
.text('Syntax error in text');
g.append('text') // text label for the x axis
.attr('class', 'error-text')
.attr('x', 1250)
.attr('y', 400)
.attr('font-size', '100px')
.style('text-anchor', 'middle')
.text('mermaid version ' + mermaidVersion);
svg.attr('height', 100);
svg.attr('width', 500);
svg.attr('viewBox', '768 0 912 512');
} catch (e) {
log.error('Error while rendering info diagram');
log.error(getErrorMessage(e));
}
g.append('text') // text label for the x axis
.attr('class', 'error-text')
.attr('x', 1440)
.attr('y', 250)
.attr('font-size', '150px')
.style('text-anchor', 'middle')
.text('Syntax error in text');
g.append('text') // text label for the x axis
.attr('class', 'error-text')
.attr('x', 1250)
.attr('y', 400)
.attr('font-size', '100px')
.style('text-anchor', 'middle')
.text(`mermaid version ${version}`);
};
export default {
setConf,
draw,
};
export const renderer = { draw };
export default renderer;

View File

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

View File

@ -655,14 +655,7 @@ const addMarkersToEdge = function (svgPath, edgeData, diagramType, arrowMarkerAb
*/
export const getClasses = function (text, diagObj) {
log.info('Extracting classes');
diagObj.db.clear('ver-2');
try {
// Parse the graph definition
diagObj.parse(text);
return diagObj.db.getClasses();
} catch (e) {
return {};
}
return diagObj.db.getClasses();
};
const addSubGraphs = function (db) {
@ -766,14 +759,8 @@ const insertChildren = (nodeArray, parentLookupDb) => {
*/
export const draw = async function (text, id, _version, diagObj) {
// Add temporary render element
diagObj.db.clear();
nodeDb = {};
portPos = {};
diagObj.db.setGen('gen-2');
// Parse the graph definition
diagObj.parser.parse(text);
const renderEl = select('body').append('div').attr('style', 'height:400px').attr('id', 'cy');
let graph = {
id: 'root',

View File

@ -1,4 +1,4 @@
// @ts-ignore: TODO Fix ts errors
// @ts-ignore: JISON doesn't support types
import flowParser from './parser/flow.jison';
import flowDb from './flowDb.js';
import flowRendererV2 from './flowRenderer-v2.js';

View File

@ -1,4 +1,4 @@
// @ts-ignore: TODO Fix ts errors
// @ts-ignore: JISON doesn't support types
import flowParser from './parser/flow.jison';
import flowDb from './flowDb.js';
import flowRenderer from './flowRenderer.js';

View File

@ -1,10 +1,7 @@
import * as graphlib from 'dagre-d3-es/src/graphlib/index.js';
import { select, curveLinear, selectAll } from 'd3';
import flowDb from './flowDb.js';
import { getConfig } from '../../config.js';
import utils from '../../utils.js';
import { render } from '../../dagre-wrapper/index.js';
import { addHtmlLabel } from 'dagre-d3-es/src/dagre-js/label/add-html-label.js';
import { log } from '../../logger.js';
@ -344,15 +341,7 @@ export const addEdges = function (edges, g, diagObj) {
* @returns {object} ClassDef styles
*/
export const getClasses = function (text, diagObj) {
log.info('Extracting classes');
diagObj.db.clear();
try {
// Parse the graph definition
diagObj.parse(text);
return diagObj.db.getClasses();
} catch (e) {
return;
}
return diagObj.db.getClasses();
};
/**
@ -364,10 +353,6 @@ export const getClasses = function (text, diagObj) {
export const draw = async function (text, id, _version, diagObj) {
log.info('Drawing flowchart');
diagObj.db.clear();
flowDb.setGen('gen-2');
// Parse the graph definition
diagObj.parser.parse(text);
// Fetch the default direction, use TD if none was found
let dir = diagObj.db.getDirection();

View File

@ -273,15 +273,7 @@ export const addEdges = function (edges, g, diagObj) {
*/
export const getClasses = function (text, diagObj) {
log.info('Extracting classes');
diagObj.db.clear();
try {
// Parse the graph definition
diagObj.parse(text);
return diagObj.db.getClasses();
} catch (e) {
log.error(e);
return {};
}
return diagObj.db.getClasses();
};
/**
@ -294,7 +286,6 @@ export const getClasses = function (text, diagObj) {
*/
export const draw = function (text, id, _version, diagObj) {
log.info('Drawing flowchart');
diagObj.db.clear();
const { securityLevel, flowchart: conf } = getConfig();
let sandboxElement;
if (securityLevel === 'sandbox') {

View File

@ -6,6 +6,40 @@ setConfig({
securityLevel: 'strict',
});
const keywords = [
'graph',
'flowchart',
'flowchart-elk',
'style',
'default',
'linkStyle',
'interpolate',
'classDef',
'class',
'href',
'call',
'click',
'_self',
'_blank',
'_parent',
'_top',
'end',
'subgraph',
'kitty',
];
const doubleEndedEdges = [
{ edgeStart: 'x--', edgeEnd: '--x', stroke: 'normal', type: 'double_arrow_cross' },
{ edgeStart: 'x==', edgeEnd: '==x', stroke: 'thick', type: 'double_arrow_cross' },
{ edgeStart: 'x-.', edgeEnd: '.-x', stroke: 'dotted', type: 'double_arrow_cross' },
{ edgeStart: 'o--', edgeEnd: '--o', stroke: 'normal', type: 'double_arrow_circle' },
{ edgeStart: 'o==', edgeEnd: '==o', stroke: 'thick', type: 'double_arrow_circle' },
{ edgeStart: 'o-.', edgeEnd: '.-o', stroke: 'dotted', type: 'double_arrow_circle' },
{ edgeStart: '<--', edgeEnd: '-->', stroke: 'normal', type: 'double_arrow_point' },
{ edgeStart: '<==', edgeEnd: '==>', stroke: 'thick', type: 'double_arrow_point' },
{ edgeStart: '<-.', edgeEnd: '.->', stroke: 'dotted', type: 'double_arrow_point' },
];
describe('[Edges] when parsing', () => {
beforeEach(function () {
flow.parser.yy = flowDb;
@ -39,211 +73,62 @@ describe('[Edges] when parsing', () => {
expect(edges[0].type).toBe('arrow_circle');
});
describe('cross', function () {
it('should handle double edged nodes and edges', function () {
const res = flow.parser.parse('graph TD;\nA x--x B;');
describe('edges', function () {
doubleEndedEdges.forEach((edgeType) => {
it(`should handle ${edgeType.stroke} ${edgeType.type} with no text`, function () {
const res = flow.parser.parse(`graph TD;\nA ${edgeType.edgeStart}${edgeType.edgeEnd} B;`);
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
expect(vert['A'].id).toBe('A');
expect(vert['B'].id).toBe('B');
expect(edges.length).toBe(1);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
expect(edges[0].type).toBe('double_arrow_cross');
expect(edges[0].text).toBe('');
expect(edges[0].stroke).toBe('normal');
expect(edges[0].length).toBe(1);
});
expect(vert['A'].id).toBe('A');
expect(vert['B'].id).toBe('B');
expect(edges.length).toBe(1);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
expect(edges[0].type).toBe(`${edgeType.type}`);
expect(edges[0].text).toBe('');
expect(edges[0].stroke).toBe(`${edgeType.stroke}`);
});
it('should handle double edged nodes with text', function () {
const res = flow.parser.parse('graph TD;\nA x-- text --x B;');
it(`should handle ${edgeType.stroke} ${edgeType.type} with text`, function () {
const res = flow.parser.parse(
`graph TD;\nA ${edgeType.edgeStart} text ${edgeType.edgeEnd} B;`
);
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
expect(vert['A'].id).toBe('A');
expect(vert['B'].id).toBe('B');
expect(edges.length).toBe(1);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
expect(edges[0].type).toBe('double_arrow_cross');
expect(edges[0].text).toBe('text');
expect(edges[0].stroke).toBe('normal');
expect(edges[0].length).toBe(1);
});
expect(vert['A'].id).toBe('A');
expect(vert['B'].id).toBe('B');
expect(edges.length).toBe(1);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
expect(edges[0].type).toBe(`${edgeType.type}`);
expect(edges[0].text).toBe('text');
expect(edges[0].stroke).toBe(`${edgeType.stroke}`);
});
it('should handle double edged nodes and edges on thick arrows', function () {
const res = flow.parser.parse('graph TD;\nA x==x B;');
it.each(keywords)(
`should handle ${edgeType.stroke} ${edgeType.type} with %s text`,
function (keyword) {
const res = flow.parser.parse(
`graph TD;\nA ${edgeType.edgeStart} ${keyword} ${edgeType.edgeEnd} B;`
);
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
expect(vert['A'].id).toBe('A');
expect(vert['B'].id).toBe('B');
expect(edges.length).toBe(1);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
expect(edges[0].type).toBe('double_arrow_cross');
expect(edges[0].text).toBe('');
expect(edges[0].stroke).toBe('thick');
expect(edges[0].length).toBe(1);
});
it('should handle double edged nodes with text on thick arrows', function () {
const res = flow.parser.parse('graph TD;\nA x== text ==x B;');
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
expect(vert['A'].id).toBe('A');
expect(vert['B'].id).toBe('B');
expect(edges.length).toBe(1);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
expect(edges[0].type).toBe('double_arrow_cross');
expect(edges[0].text).toBe('text');
expect(edges[0].stroke).toBe('thick');
expect(edges[0].length).toBe(1);
});
it('should handle double edged nodes and edges on dotted arrows', function () {
const res = flow.parser.parse('graph TD;\nA x-.-x B;');
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
expect(vert['A'].id).toBe('A');
expect(vert['B'].id).toBe('B');
expect(edges.length).toBe(1);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
expect(edges[0].type).toBe('double_arrow_cross');
expect(edges[0].text).toBe('');
expect(edges[0].stroke).toBe('dotted');
expect(edges[0].length).toBe(1);
});
it('should handle double edged nodes with text on dotted arrows', function () {
const res = flow.parser.parse('graph TD;\nA x-. text .-x B;');
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
expect(vert['A'].id).toBe('A');
expect(vert['B'].id).toBe('B');
expect(edges.length).toBe(1);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
expect(edges[0].type).toBe('double_arrow_cross');
expect(edges[0].text).toBe('text');
expect(edges[0].stroke).toBe('dotted');
expect(edges[0].length).toBe(1);
});
});
describe('circle', function () {
it('should handle double edged nodes and edges', function () {
const res = flow.parser.parse('graph TD;\nA o--o B;');
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
expect(vert['A'].id).toBe('A');
expect(vert['B'].id).toBe('B');
expect(edges.length).toBe(1);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
expect(edges[0].type).toBe('double_arrow_circle');
expect(edges[0].text).toBe('');
expect(edges[0].stroke).toBe('normal');
expect(edges[0].length).toBe(1);
});
it('should handle double edged nodes with text', function () {
const res = flow.parser.parse('graph TD;\nA o-- text --o B;');
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
expect(vert['A'].id).toBe('A');
expect(vert['B'].id).toBe('B');
expect(edges.length).toBe(1);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
expect(edges[0].type).toBe('double_arrow_circle');
expect(edges[0].text).toBe('text');
expect(edges[0].stroke).toBe('normal');
expect(edges[0].length).toBe(1);
});
it('should handle double edged nodes and edges on thick arrows', function () {
const res = flow.parser.parse('graph TD;\nA o==o B;');
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
expect(vert['A'].id).toBe('A');
expect(vert['B'].id).toBe('B');
expect(edges.length).toBe(1);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
expect(edges[0].type).toBe('double_arrow_circle');
expect(edges[0].text).toBe('');
expect(edges[0].stroke).toBe('thick');
expect(edges[0].length).toBe(1);
});
it('should handle double edged nodes with text on thick arrows', function () {
const res = flow.parser.parse('graph TD;\nA o== text ==o B;');
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
expect(vert['A'].id).toBe('A');
expect(vert['B'].id).toBe('B');
expect(edges.length).toBe(1);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
expect(edges[0].type).toBe('double_arrow_circle');
expect(edges[0].text).toBe('text');
expect(edges[0].stroke).toBe('thick');
expect(edges[0].length).toBe(1);
});
it('should handle double edged nodes and edges on dotted arrows', function () {
const res = flow.parser.parse('graph TD;\nA o-.-o B;');
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
expect(vert['A'].id).toBe('A');
expect(vert['B'].id).toBe('B');
expect(edges.length).toBe(1);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
expect(edges[0].type).toBe('double_arrow_circle');
expect(edges[0].text).toBe('');
expect(edges[0].stroke).toBe('dotted');
expect(edges[0].length).toBe(1);
});
it('should handle double edged nodes with text on dotted arrows', function () {
const res = flow.parser.parse('graph TD;\nA o-. text .-o B;');
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
expect(vert['A'].id).toBe('A');
expect(vert['B'].id).toBe('B');
expect(edges.length).toBe(1);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
expect(edges[0].type).toBe('double_arrow_circle');
expect(edges[0].text).toBe('text');
expect(edges[0].stroke).toBe('dotted');
expect(edges[0].length).toBe(1);
expect(vert['A'].id).toBe('A');
expect(vert['B'].id).toBe('B');
expect(edges.length).toBe(1);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
expect(edges[0].type).toBe(`${edgeType.type}`);
expect(edges[0].text).toBe(`${keyword}`);
expect(edges[0].stroke).toBe(`${edgeType.stroke}`);
}
);
});
});

View File

@ -24,7 +24,7 @@ A["\`The cat in **the** hat\`"]-- "\`The *bat* in the chat\`" -->B["The dog in t
expect(vert['A'].labelType).toBe('markdown');
expect(vert['B'].id).toBe('B');
expect(vert['B'].text).toBe('The dog in the hog');
expect(vert['B'].labelType).toBe('text');
expect(vert['B'].labelType).toBe('string');
expect(edges.length).toBe(2);
expect(edges[0].start).toBe('A');
expect(edges[0].end).toBe('B');
@ -35,7 +35,7 @@ A["\`The cat in **the** hat\`"]-- "\`The *bat* in the chat\`" -->B["The dog in t
expect(edges[1].end).toBe('C');
expect(edges[1].type).toBe('arrow_point');
expect(edges[1].text).toBe('The rat in the mat');
expect(edges[1].labelType).toBe('text');
expect(edges[1].labelType).toBe('string');
});
it('mardown formatting in subgraphs', function () {
const res = flow.parser.parse(`flowchart LR

View File

@ -6,6 +6,29 @@ setConfig({
securityLevel: 'strict',
});
const keywords = [
'graph',
'flowchart',
'flowchart-elk',
'style',
'default',
'linkStyle',
'interpolate',
'classDef',
'class',
'href',
'call',
'click',
'_self',
'_blank',
'_parent',
'_top',
'end',
'subgraph',
];
const specialChars = ['#', ':', '0', '&', ',', '*', '.', '\\', 'v', '-', '/', '_'];
describe('[Singlenodes] when parsing', () => {
beforeEach(function () {
flow.parser.yy = flowDb;
@ -259,4 +282,90 @@ describe('[Singlenodes] when parsing', () => {
expect(edges.length).toBe(0);
expect(vert['i_d'].styles.length).toBe(0);
});
it.each(keywords)('should handle keywords between dashes "-"', function (keyword) {
const res = flow.parser.parse(`graph TD;a-${keyword}-node;`);
const vert = flow.parser.yy.getVertices();
expect(vert[`a-${keyword}-node`].text).toBe(`a-${keyword}-node`);
});
it.each(keywords)('should handle keywords between periods "."', function (keyword) {
const res = flow.parser.parse(`graph TD;a.${keyword}.node;`);
const vert = flow.parser.yy.getVertices();
expect(vert[`a.${keyword}.node`].text).toBe(`a.${keyword}.node`);
});
it.each(keywords)('should handle keywords between underscores "_"', function (keyword) {
const res = flow.parser.parse(`graph TD;a_${keyword}_node;`);
const vert = flow.parser.yy.getVertices();
expect(vert[`a_${keyword}_node`].text).toBe(`a_${keyword}_node`);
});
it.each(keywords)('should handle nodes ending in %s', function (keyword) {
const res = flow.parser.parse(`graph TD;node_${keyword};node.${keyword};node-${keyword};`);
const vert = flow.parser.yy.getVertices();
expect(vert[`node_${keyword}`].text).toBe(`node_${keyword}`);
expect(vert[`node.${keyword}`].text).toBe(`node.${keyword}`);
expect(vert[`node-${keyword}`].text).toBe(`node-${keyword}`);
});
const errorKeywords = [
'graph',
'flowchart',
'flowchart-elk',
'style',
'linkStyle',
'interpolate',
'classDef',
'class',
'_self',
'_blank',
'_parent',
'_top',
'end',
'subgraph',
];
it.each(errorKeywords)('should throw error at nodes beginning with %s', function (keyword) {
const str = `graph TD;${keyword}.node;${keyword}-node;${keyword}/node`;
const vert = flow.parser.yy.getVertices();
expect(() => flow.parser.parse(str)).toThrowError();
});
const workingKeywords = ['default', 'href', 'click', 'call'];
it.each(workingKeywords)('should parse node beginning with %s', function (keyword) {
flow.parser.parse(`graph TD; ${keyword}.node;${keyword}-node;${keyword}/node;`);
const vert = flow.parser.yy.getVertices();
expect(vert[`${keyword}.node`].text).toBe(`${keyword}.node`);
expect(vert[`${keyword}-node`].text).toBe(`${keyword}-node`);
expect(vert[`${keyword}/node`].text).toBe(`${keyword}/node`);
});
it.each(specialChars)(
'should allow node ids of single special characters',
function (specialChar) {
flow.parser.parse(`graph TD; ${specialChar} --> A`);
const vert = flow.parser.yy.getVertices();
expect(vert[`${specialChar}`].text).toBe(`${specialChar}`);
}
);
it.each(specialChars)(
'should allow node ids with special characters at start of id',
function (specialChar) {
flow.parser.parse(`graph TD; ${specialChar}node --> A`);
const vert = flow.parser.yy.getVertices();
expect(vert[`${specialChar}node`].text).toBe(`${specialChar}node`);
}
);
it.each(specialChars)(
'should allow node ids with special characters at end of id',
function (specialChar) {
flow.parser.parse(`graph TD; node${specialChar} --> A`);
const vert = flow.parser.yy.getVertices();
expect(vert[`node${specialChar}`].text).toBe(`node${specialChar}`);
}
);
});

View File

@ -26,15 +26,6 @@ describe('[Style] when parsing', () => {
expect(vert['Q'].styles[0]).toBe('background:#fff');
});
// log.debug(flow.parser.parse('graph TD;style Q background:#fff;'));
it('should handle styles for edges', function () {
const res = flow.parser.parse('graph TD;a-->b;\nstyle #0 stroke: #f66;');
const edges = flow.parser.yy.getEdges();
expect(edges.length).toBe(1);
});
it('should handle multiple styles for a vortex', function () {
const res = flow.parser.parse('graph TD;style R background:#fff,border:1px solid red;');

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