mirror of
https://github.com/mermaid-js/mermaid.git
synced 2025-09-26 18:59:42 +02:00
Compare commits
37 Commits
release_9.
...
v9.2.0
Author | SHA1 | Date | |
---|---|---|---|
![]() |
e78ac9b92a | ||
![]() |
d4c19ffa59 | ||
![]() |
120940f9f4 | ||
![]() |
48b1f489fc | ||
![]() |
e62dd255bc | ||
![]() |
13110c4ed9 | ||
![]() |
327fcbf902 | ||
![]() |
81924f72c8 | ||
![]() |
1a0309fb87 | ||
![]() |
8ad8d39fe4 | ||
![]() |
56a8068a7f | ||
![]() |
d17aa6ecdd | ||
![]() |
4c311ea4b1 | ||
![]() |
1388e201e5 | ||
![]() |
125312c114 | ||
![]() |
ea314cd24a | ||
![]() |
8230c8f8b4 | ||
![]() |
d115fbc6da | ||
![]() |
775fb80c43 | ||
![]() |
b486177ca7 | ||
![]() |
957e64fe8a | ||
![]() |
7881d1e457 | ||
![]() |
fc8db95597 | ||
![]() |
cc10e62ebd | ||
![]() |
d348f2847c | ||
![]() |
ebef4a1416 | ||
![]() |
24605784f2 | ||
![]() |
3240f8ae56 | ||
![]() |
50f44c5cb0 | ||
![]() |
cc2f4f779a | ||
![]() |
00ce0fc034 | ||
![]() |
bc5ef5fb7d | ||
![]() |
c20b8a0664 | ||
![]() |
23e590e09b | ||
![]() |
60e4585e20 | ||
![]() |
ba436cc37a | ||
![]() |
960ea450e9 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -32,5 +32,6 @@ cypress/snapshots/
|
||||
.eslintcache
|
||||
.tsbuildinfo
|
||||
tsconfig.tsbuildinfo
|
||||
knsv*.html
|
||||
|
||||
local*.html
|
||||
|
@@ -1,7 +1,15 @@
|
||||
import express from 'express';
|
||||
import express, { NextFunction, Request, Response } from 'express';
|
||||
import { createServer as createViteServer } from 'vite';
|
||||
// import { getBuildConfig } from './build';
|
||||
|
||||
const cors = (req: Request, res: Response, next: NextFunction) => {
|
||||
res.header('Access-Control-Allow-Origin', '*');
|
||||
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
|
||||
res.header('Access-Control-Allow-Headers', 'Content-Type');
|
||||
|
||||
next();
|
||||
};
|
||||
|
||||
async function createServer() {
|
||||
const app = express();
|
||||
|
||||
@@ -12,6 +20,7 @@ async function createServer() {
|
||||
appType: 'custom', // don't include Vite's default HTML handling middlewares
|
||||
});
|
||||
|
||||
app.use(cors);
|
||||
app.use(express.static('./packages/mermaid/dist'));
|
||||
app.use(express.static('./packages/mermaid-example-diagram/dist'));
|
||||
app.use(express.static('./packages/mermaid-mindmap/dist'));
|
||||
|
@@ -75,16 +75,6 @@ classDiagram
|
||||
<pre id="diagram" class="mermaid2">
|
||||
mindmap
|
||||
root
|
||||
A
|
||||
B
|
||||
C
|
||||
D
|
||||
E
|
||||
A2
|
||||
B2
|
||||
C2
|
||||
D2
|
||||
E2
|
||||
child1((Circle))
|
||||
grandchild 1
|
||||
grandchild 2
|
||||
|
@@ -14,16 +14,14 @@
|
||||
mermaid.init({ startOnLoad: false });
|
||||
|
||||
mermaid.mermaidAPI.initialize({ securityLevel: 'strict' });
|
||||
(async () => {
|
||||
try {
|
||||
console.log('rendering');
|
||||
await mermaid.mermaidAPI.render('graphDiv', `>`);
|
||||
} catch (e) {}
|
||||
try {
|
||||
console.log('rendering');
|
||||
mermaid.mermaidAPI.render('graphDiv', `>`);
|
||||
} catch (e) {}
|
||||
|
||||
await mermaid.mermaidAPI.render('graphDiv', `graph LR\n a --> b`, (html) => {
|
||||
document.getElementById('graph').innerHTML = html;
|
||||
});
|
||||
})();
|
||||
mermaid.mermaidAPI.render('graphDiv', `graph LR\n a --> b`, (html) => {
|
||||
document.getElementById('graph').innerHTML = html;
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
@@ -19,10 +19,9 @@
|
||||
function rerender(text) {
|
||||
const graphText = `graph TD
|
||||
A[${text}] -->|Get money| B(Go shopping)`;
|
||||
mermaid.mermaidAPI.render('id', graphText).then((svg) => {
|
||||
console.log('\x1b[35m%s\x1b[0m', '>> graph', svg);
|
||||
document.getElementById('graph').innerHTML = svg;
|
||||
});
|
||||
const graph = mermaid.mermaidAPI.render('id', graphText);
|
||||
console.log('\x1b[35m%s\x1b[0m', '>> graph', graph);
|
||||
document.getElementById('graph').innerHTML = graph;
|
||||
}
|
||||
</script>
|
||||
<button id="rerender" onclick="rerender('Saturday')">Rerender</button>
|
||||
|
@@ -49,14 +49,39 @@
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module">
|
||||
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@9/dist/mermaid.esm.min.mjs';
|
||||
// import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@9/dist/mermaid.esm.min.mjs';
|
||||
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@9.2.0-rc6/dist/mermaid.esm.min.mjs';
|
||||
// import mermaid from 'http://localhost:9000/mermaid.esm.mjs';
|
||||
console.log(mermaid); // eslint-disable-line
|
||||
window.mermaid = mermaid;
|
||||
const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
|
||||
const conf = {
|
||||
logLevel: 4,
|
||||
startOnLoad: true,
|
||||
themeCSS: '.label { font-family: Source Sans Pro,Helvetica Neue,Arial,sans-serif; }',
|
||||
lazyLoadedDiagrams: [
|
||||
'https://cdn.jsdelivr.net/npm/@mermaid-js/mermaid-mindmap@9.2.0-rc3/dist/mermaid-mindmap-detector.esm.mjs',
|
||||
// 'http://localhost:9000/mermaid-mindmap-detector.esm.mjs',
|
||||
],
|
||||
};
|
||||
if (isDarkMode) conf.theme = 'dark';
|
||||
|
||||
async function loadMermaid() {
|
||||
await mermaid.initialize(conf);
|
||||
console.log('mermaid initialized'); // eslint-disable-line
|
||||
}
|
||||
mermaid.parseError = (e) => {
|
||||
console.log('parse error', e); // eslint-disable-line
|
||||
};
|
||||
await loadMermaid();
|
||||
</script>
|
||||
<script>
|
||||
let initEditor = exports.default;
|
||||
let parser = new DOMParser();
|
||||
let currentCodeExample = 0;
|
||||
let colorize = [];
|
||||
let num = 0;
|
||||
|
||||
function colorizeEverything(html) {
|
||||
initEditor(monaco);
|
||||
@@ -97,14 +122,12 @@
|
||||
renderer: {
|
||||
code: function (code, lang) {
|
||||
if (lang === 'mermaid-example') {
|
||||
console.log('An example'); // eslint-disable-line
|
||||
currentCodeExample++;
|
||||
colorize.push(currentCodeExample);
|
||||
return '<pre id="code' + currentCodeExample + '">' + escapeHTML(code) + '</pre>';
|
||||
} else if (lang === 'mermaid') {
|
||||
// TODO: This will need to be updated when render is async.
|
||||
return (
|
||||
'<pre class="mermaid">' + mermaid.render('mermaid-svg-' + num++, code) + '</pre>'
|
||||
);
|
||||
return '<pre class="mermaid">' + code + '</pre>';
|
||||
}
|
||||
return this.origin.code.apply(this, arguments);
|
||||
},
|
||||
@@ -123,6 +146,10 @@
|
||||
const editHtml = '[:memo: Edit this Page](' + url + ')\n';
|
||||
return editHtml + html;
|
||||
});
|
||||
// Invoked on each page load after new HTML has been appended to the DOM
|
||||
hook.doneEach(function () {
|
||||
window.mermaid.init();
|
||||
});
|
||||
|
||||
hook.afterEach(function (html, next) {
|
||||
next(html);
|
||||
@@ -138,28 +165,17 @@
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
|
||||
const conf = {
|
||||
logLevel: 4,
|
||||
startOnLoad: false,
|
||||
themeCSS: '.label { font-family: Source Sans Pro,Helvetica Neue,Arial,sans-serif; }',
|
||||
};
|
||||
if (isDarkMode) conf.theme = 'dark';
|
||||
mermaid.initialize(conf);
|
||||
</script>
|
||||
<script>
|
||||
window.onhashchange = function (a) {
|
||||
//code
|
||||
if (location) {
|
||||
ga('send', 'pageview', location.hash);
|
||||
}
|
||||
// if (location && ga) {
|
||||
// ga('send', 'pageview', location.hash);
|
||||
// }
|
||||
};
|
||||
</script>
|
||||
<script src="//cdn.jsdelivr.net/npm/docsify/lib/docsify.min.js"></script>
|
||||
<script src="//cdn.jsdelivr.net/npm/docsify/lib/plugins/search.min.js"></script>
|
||||
<script src="//cdn.jsdelivr.net/npm/docsify/lib/plugins/ga.min.js"></script>
|
||||
<!-- <script src="//cdn.jsdelivr.net/npm/docsify/lib/plugins/ga.min.js"></script> -->
|
||||
<script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-coffeescript.min.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "mermaid-monorepo",
|
||||
"private": true,
|
||||
"version": "9.2.0-rc2",
|
||||
"version": "9.2.0-rc4",
|
||||
"description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.",
|
||||
"main": "dist/mermaid.core.mjs",
|
||||
"module": "dist/mermaid.core.mjs",
|
||||
|
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@mermaid-js/mermaid-mindmap",
|
||||
"version": "9.2.0-rc4",
|
||||
"version": "9.2.0",
|
||||
"description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.",
|
||||
"main": "dist/mermaid-mindmap.core.mjs",
|
||||
"module": "dist/mermaid-mindmap.core.mjs",
|
||||
|
@@ -22,13 +22,10 @@ const genSections = (options) => {
|
||||
}
|
||||
.section-${i - 1} text {
|
||||
fill: ${options['cScaleLabel' + i]};
|
||||
// fill: ${options['gitInv' + i]};
|
||||
}
|
||||
.node-icon-${i - 1} {
|
||||
font-size: 40px;
|
||||
color: ${options['cScaleLabel' + i]};
|
||||
// fill: ${options['cScaleLabel' + i]};
|
||||
// color: ${options['gitInv' + i]};
|
||||
}
|
||||
.section-edge-${i - 1}{
|
||||
stroke: ${options['cScale' + i]};
|
||||
|
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mermaid",
|
||||
"version": "9.2.0-rc2",
|
||||
"version": "9.2.0",
|
||||
"description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.",
|
||||
"main": "./dist/mermaid.core.mjs",
|
||||
"module": "./dist/mermaid.core.mjs",
|
||||
@@ -72,7 +72,8 @@
|
||||
"lodash": "^4.17.21",
|
||||
"moment-mini": "^2.24.0",
|
||||
"non-layered-tidy-tree-layout": "^2.0.2",
|
||||
"stylis": "^4.1.2"
|
||||
"stylis": "^4.1.2",
|
||||
"uuid": "^9.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@applitools/eyes-cypress": "^3.25.7",
|
||||
@@ -86,6 +87,7 @@
|
||||
"@types/lodash": "^4.14.185",
|
||||
"@types/prettier": "^2.7.0",
|
||||
"@types/stylis": "^4.0.2",
|
||||
"@types/uuid": "^8.3.4",
|
||||
"@typescript-eslint/eslint-plugin": "^5.37.0",
|
||||
"@typescript-eslint/parser": "^5.37.0",
|
||||
"concurrently": "^7.4.0",
|
||||
|
@@ -81,12 +81,16 @@ export class Diagram {
|
||||
}
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
export const getDiagramFromText = async (txt: string, parseError?: Function): Promise<Diagram> => {
|
||||
export const getDiagramFromText = (
|
||||
txt: string,
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
parseError?: Function
|
||||
): Diagram | Promise<Diagram> => {
|
||||
const type = detectType(txt, configApi.getConfig());
|
||||
try {
|
||||
// Trying to find the diagram
|
||||
getDiagram(type);
|
||||
return new Diagram(txt, parseError);
|
||||
} catch (error) {
|
||||
if (!(error instanceof DiagramNotFoundError)) {
|
||||
log.error(error);
|
||||
@@ -96,14 +100,17 @@ export const getDiagramFromText = async (txt: string, parseError?: Function): Pr
|
||||
if (!loader) {
|
||||
throw new Error(`Loader for ${type} not found.`);
|
||||
}
|
||||
// Diagram not available, loading it
|
||||
const { diagram } = await loader();
|
||||
registerDiagram(type, diagram, undefined, diagram.injectUtils);
|
||||
// new diagram will try getDiagram again and if fails then it is a valid throw
|
||||
// TODO: Uncomment for v10
|
||||
// // Diagram not available, loading it
|
||||
// const { diagram } = await loader();
|
||||
// registerDiagram(type, diagram, undefined, diagram.injectUtils);
|
||||
// // new diagram will try getDiagram again and if fails then it is a valid throw
|
||||
return loader().then(({ diagram }) => {
|
||||
registerDiagram(type, diagram, undefined, diagram.injectUtils);
|
||||
return new Diagram(txt, parseError);
|
||||
});
|
||||
}
|
||||
// If either of the above worked, we have the diagram
|
||||
// logic and can continue
|
||||
return new Diagram(txt, parseError);
|
||||
// return new Diagram(txt, parseError);
|
||||
};
|
||||
|
||||
export default Diagram;
|
||||
|
@@ -25,6 +25,7 @@ function parse(text: string, parseError?: Function): boolean {
|
||||
// original version cannot be modified since it was frozen with `Object.freeze()`
|
||||
export const mermaidAPI = {
|
||||
render: vi.fn(),
|
||||
renderAsync: vi.fn(),
|
||||
parse,
|
||||
parseDirective: vi.fn(),
|
||||
initialize: vi.fn(),
|
||||
|
@@ -4,6 +4,7 @@ import DOMPurify from 'dompurify';
|
||||
|
||||
export interface MermaidConfig {
|
||||
lazyLoadedDiagrams?: string[];
|
||||
loadExternalDiagramsAtStartup?: boolean;
|
||||
theme?: string;
|
||||
themeVariables?: any;
|
||||
themeCSS?: string;
|
||||
|
@@ -49,14 +49,39 @@
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module">
|
||||
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@<MERMAID_VERSION>/dist/mermaid.esm.min.mjs';
|
||||
// import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@<MERMAID_VERSION>/dist/mermaid.esm.min.mjs';
|
||||
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@9.2.0-rc6/dist/mermaid.esm.min.mjs';
|
||||
// import mermaid from 'http://localhost:9000/mermaid.esm.mjs';
|
||||
console.log(mermaid); // eslint-disable-line
|
||||
window.mermaid = mermaid;
|
||||
const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
|
||||
const conf = {
|
||||
logLevel: 4,
|
||||
startOnLoad: true,
|
||||
themeCSS: '.label { font-family: Source Sans Pro,Helvetica Neue,Arial,sans-serif; }',
|
||||
lazyLoadedDiagrams: [
|
||||
'https://cdn.jsdelivr.net/npm/@mermaid-js/mermaid-mindmap@9.2.0-rc3/dist/mermaid-mindmap-detector.esm.mjs',
|
||||
// 'http://localhost:9000/mermaid-mindmap-detector.esm.mjs',
|
||||
],
|
||||
};
|
||||
if (isDarkMode) conf.theme = 'dark';
|
||||
|
||||
async function loadMermaid() {
|
||||
await mermaid.initialize(conf);
|
||||
console.log('mermaid initialized'); // eslint-disable-line
|
||||
}
|
||||
mermaid.parseError = (e) => {
|
||||
console.log('parse error', e); // eslint-disable-line
|
||||
};
|
||||
await loadMermaid();
|
||||
</script>
|
||||
<script>
|
||||
let initEditor = exports.default;
|
||||
let parser = new DOMParser();
|
||||
let currentCodeExample = 0;
|
||||
let colorize = [];
|
||||
let num = 0;
|
||||
|
||||
function colorizeEverything(html) {
|
||||
initEditor(monaco);
|
||||
@@ -97,14 +122,12 @@
|
||||
renderer: {
|
||||
code: function (code, lang) {
|
||||
if (lang === 'mermaid-example') {
|
||||
console.log('An example'); // eslint-disable-line
|
||||
currentCodeExample++;
|
||||
colorize.push(currentCodeExample);
|
||||
return '<pre id="code' + currentCodeExample + '">' + escapeHTML(code) + '</pre>';
|
||||
} else if (lang === 'mermaid') {
|
||||
// TODO: This will need to be updated when render is async.
|
||||
return (
|
||||
'<pre class="mermaid">' + mermaid.render('mermaid-svg-' + num++, code) + '</pre>'
|
||||
);
|
||||
return '<pre class="mermaid">' + code + '</pre>';
|
||||
}
|
||||
return this.origin.code.apply(this, arguments);
|
||||
},
|
||||
@@ -123,6 +146,10 @@
|
||||
const editHtml = '[:memo: Edit this Page](' + url + ')\n';
|
||||
return editHtml + html;
|
||||
});
|
||||
// Invoked on each page load after new HTML has been appended to the DOM
|
||||
hook.doneEach(function () {
|
||||
window.mermaid.init();
|
||||
});
|
||||
|
||||
hook.afterEach(function (html, next) {
|
||||
next(html);
|
||||
@@ -138,28 +165,17 @@
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
|
||||
const conf = {
|
||||
logLevel: 4,
|
||||
startOnLoad: false,
|
||||
themeCSS: '.label { font-family: Source Sans Pro,Helvetica Neue,Arial,sans-serif; }',
|
||||
};
|
||||
if (isDarkMode) conf.theme = 'dark';
|
||||
mermaid.initialize(conf);
|
||||
</script>
|
||||
<script>
|
||||
window.onhashchange = function (a) {
|
||||
//code
|
||||
if (location) {
|
||||
ga('send', 'pageview', location.hash);
|
||||
}
|
||||
// if (location && ga) {
|
||||
// ga('send', 'pageview', location.hash);
|
||||
// }
|
||||
};
|
||||
</script>
|
||||
<script src="//cdn.jsdelivr.net/npm/docsify/lib/docsify.min.js"></script>
|
||||
<script src="//cdn.jsdelivr.net/npm/docsify/lib/plugins/search.min.js"></script>
|
||||
<script src="//cdn.jsdelivr.net/npm/docsify/lib/plugins/ga.min.js"></script>
|
||||
<!-- <script src="//cdn.jsdelivr.net/npm/docsify/lib/plugins/ga.min.js"></script> -->
|
||||
<script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-coffeescript.min.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
@@ -48,6 +48,7 @@ export const setLogLevel = function (level: keyof typeof LEVELS | number | strin
|
||||
log.warn = () => {};
|
||||
log.error = () => {};
|
||||
log.fatal = () => {};
|
||||
|
||||
if (numericLevel <= LEVELS.fatal) {
|
||||
log.fatal = console.error
|
||||
? console.error.bind(console, format('FATAL'), 'color: orange')
|
||||
|
@@ -48,11 +48,13 @@ describe('when using mermaid and ', function () {
|
||||
const node = document.createElement('div');
|
||||
node.appendChild(document.createTextNode('graph TD;\na;'));
|
||||
|
||||
await mermaid.initThrowsErrors(undefined, node);
|
||||
mermaid.initThrowsErrors(undefined, node);
|
||||
// mermaidAPI.render function has been mocked, since it doesn't yet work
|
||||
// in Node.JS (only works in browser)
|
||||
expect(mermaidAPI.render).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
describe('when using #initThrowsErrorsAsync', function () {
|
||||
it('should throw error (but still render) if lazyLoadedDiagram fails', async () => {
|
||||
const node = document.createElement('div');
|
||||
node.appendChild(document.createTextNode('graph TD;\na;'));
|
||||
@@ -60,14 +62,14 @@ describe('when using mermaid and ', function () {
|
||||
mermaidAPI.setConfig({
|
||||
lazyLoadedDiagrams: ['this-file-does-not-exist.mjs'],
|
||||
});
|
||||
await expect(mermaid.initThrowsErrors(undefined, node)).rejects.toThrowError(
|
||||
await expect(mermaid.initThrowsErrorsAsync(undefined, node)).rejects.toThrowError(
|
||||
// this error message is probably different on every platform
|
||||
// this one is just for vite-note (node/jest/browser may be different)
|
||||
'Failed to load this-file-does-not-exist.mjs'
|
||||
);
|
||||
|
||||
// should still render, even if lazyLoadedDiagrams fails
|
||||
expect(mermaidAPI.render).toHaveBeenCalled();
|
||||
expect(mermaidAPI.renderAsync).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
@@ -7,7 +7,8 @@ import { log } from './logger';
|
||||
import utils from './utils';
|
||||
import { mermaidAPI } from './mermaidAPI';
|
||||
import { addDetector } from './diagram-api/detectType';
|
||||
import { isDetailedError, DetailedError } from './utils';
|
||||
import { isDetailedError, type DetailedError } from './utils';
|
||||
import { registerDiagram } from './diagram-api/diagramAPI';
|
||||
|
||||
export type { MermaidConfig, DetailedError };
|
||||
/**
|
||||
@@ -46,7 +47,12 @@ const init = async function (
|
||||
callback?: Function
|
||||
) {
|
||||
try {
|
||||
await initThrowsErrors(config, nodes, callback);
|
||||
const conf = mermaidAPI.getConfig();
|
||||
if (conf?.lazyLoadedDiagrams && conf.lazyLoadedDiagrams.length > 0) {
|
||||
await initThrowsErrorsAsync(config, nodes, callback);
|
||||
} else {
|
||||
initThrowsErrors(config, nodes, callback);
|
||||
}
|
||||
} catch (e) {
|
||||
log.warn('Syntax Error rendering');
|
||||
if (isDetailedError(e)) {
|
||||
@@ -58,19 +64,32 @@ const init = async function (
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Equivalent to {@link init()}, except an error will be thrown on error.
|
||||
*
|
||||
* @param config - **Deprecated** Mermaid sequenceConfig.
|
||||
* @param nodes - One of:
|
||||
* - A DOM Node
|
||||
* - An array of DOM nodes (as would come from a jQuery selector)
|
||||
* - A W3C selector, a la `.mermaid` (default)
|
||||
* @param callback - Function that is called with the id of each generated mermaid diagram.
|
||||
*
|
||||
* @returns Resolves on success, otherwise the {@link Promise} will be rejected with an Error.
|
||||
*/
|
||||
const initThrowsErrors = async function (
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
const handleError = (error: unknown, errors: DetailedError[], parseError?: Function) => {
|
||||
log.warn(error);
|
||||
if (isDetailedError(error)) {
|
||||
// handle case where error string and hash were
|
||||
// wrapped in object like`const error = { str, hash };`
|
||||
if (parseError) {
|
||||
parseError(error.str, error.hash);
|
||||
}
|
||||
errors.push({ ...error, message: error.str, error });
|
||||
} else {
|
||||
// assume it is just error string and pass it on
|
||||
if (parseError) {
|
||||
parseError(error);
|
||||
}
|
||||
if (error instanceof Error) {
|
||||
errors.push({
|
||||
str: error.message,
|
||||
message: error.message,
|
||||
hash: error.name,
|
||||
error,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
const initThrowsErrors = function (
|
||||
config?: MermaidConfig,
|
||||
// eslint-disable-next-line no-undef
|
||||
nodes?: string | HTMLElement | NodeListOf<HTMLElement>,
|
||||
@@ -78,31 +97,12 @@ const initThrowsErrors = async function (
|
||||
callback?: Function
|
||||
) {
|
||||
const conf = mermaidAPI.getConfig();
|
||||
// console.log('Starting rendering diagrams (init) - mermaid.init', conf);
|
||||
if (config) {
|
||||
// This is a legacy way of setting config. It is not documented and should be removed in the future.
|
||||
// @ts-ignore: TODO Fix ts errors
|
||||
mermaid.sequenceConfig = config;
|
||||
}
|
||||
|
||||
const errors = [];
|
||||
|
||||
if (conf?.lazyLoadedDiagrams && conf.lazyLoadedDiagrams.length > 0) {
|
||||
// Load all lazy loaded diagrams in parallel
|
||||
const results = await Promise.allSettled(
|
||||
conf.lazyLoadedDiagrams.map(async (diagram: string) => {
|
||||
const { id, detector, loadDiagram } = await import(diagram);
|
||||
addDetector(id, detector, loadDiagram);
|
||||
})
|
||||
);
|
||||
for (const result of results) {
|
||||
if (result.status == 'rejected') {
|
||||
log.warn(`Failed to lazyLoadedDiagram due to `, result.reason);
|
||||
errors.push(result.reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// if last argument is a function this is the callback function
|
||||
log.debug(`${!callback ? 'No ' : ''}Callback function found`);
|
||||
let nodesToProcess: ArrayLike<HTMLElement>;
|
||||
@@ -128,6 +128,7 @@ const initThrowsErrors = async function (
|
||||
const idGenerator = new utils.initIdGenerator(conf.deterministicIds, conf.deterministicIDSeed);
|
||||
|
||||
let txt: string;
|
||||
const errors: DetailedError[] = [];
|
||||
|
||||
// element is the current div with mermaid class
|
||||
for (const element of Array.from(nodesToProcess)) {
|
||||
@@ -154,7 +155,7 @@ const initThrowsErrors = async function (
|
||||
log.debug('Detected early reinit: ', init);
|
||||
}
|
||||
try {
|
||||
await mermaidAPI.render(
|
||||
mermaidAPI.render(
|
||||
id,
|
||||
txt,
|
||||
(svgCode: string, bindFunctions?: (el: Element) => void) => {
|
||||
@@ -167,13 +168,7 @@ const initThrowsErrors = async function (
|
||||
element
|
||||
);
|
||||
} catch (error) {
|
||||
log.warn('Catching Error (bootstrap)', error);
|
||||
// @ts-ignore: TODO Fix ts errors
|
||||
const mermaidError = { error, str: error.str, hash: error.hash, message: error.str };
|
||||
if (typeof mermaid.parseError === 'function') {
|
||||
mermaid.parseError(mermaidError);
|
||||
}
|
||||
errors.push(mermaidError);
|
||||
handleError(error, errors, mermaid.parseError);
|
||||
}
|
||||
}
|
||||
if (errors.length > 0) {
|
||||
@@ -182,8 +177,174 @@ const initThrowsErrors = async function (
|
||||
}
|
||||
};
|
||||
|
||||
const initialize = async function (config: MermaidConfig) {
|
||||
await mermaidAPI.initialize(config);
|
||||
let lazyLoadingPromise: Promise<PromiseSettledResult<void>[]> | undefined = undefined;
|
||||
/**
|
||||
* This is an internal function and should not be made public, as it will likely change.
|
||||
* @internal
|
||||
* @param conf - Mermaid config.
|
||||
* @returns An array of {@link PromiseSettledResult}, showing the status of imports.
|
||||
*/
|
||||
const registerLazyLoadedDiagrams = async (conf: MermaidConfig) => {
|
||||
// Only lazy load once
|
||||
// TODO: This is a hack. We should either throw error when new diagrams are added, or load them anyway.
|
||||
if (lazyLoadingPromise === undefined) {
|
||||
// Load all lazy loaded diagrams in parallel
|
||||
lazyLoadingPromise = Promise.allSettled(
|
||||
(conf?.lazyLoadedDiagrams ?? []).map(async (diagram: string) => {
|
||||
const { id, detector, loadDiagram } = await import(diagram);
|
||||
addDetector(id, detector, loadDiagram);
|
||||
})
|
||||
);
|
||||
}
|
||||
return await lazyLoadingPromise;
|
||||
};
|
||||
|
||||
let loadingPromise: Promise<unknown> | undefined = undefined;
|
||||
|
||||
const loadExternalDiagrams = async (conf: MermaidConfig) => {
|
||||
// Only lazy load once
|
||||
// TODO: This is a hack. We should either throw error when new diagrams are added, or load them anyway.
|
||||
if (loadingPromise === undefined) {
|
||||
log.debug(`Loading ${conf?.lazyLoadedDiagrams?.length} external diagrams`);
|
||||
// Load all lazy loaded diagrams in parallel
|
||||
loadingPromise = Promise.allSettled(
|
||||
(conf?.lazyLoadedDiagrams ?? []).map(async (url: string) => {
|
||||
const { id, detector, loadDiagram } = await import(url);
|
||||
const { diagram } = await loadDiagram();
|
||||
registerDiagram(id, diagram, detector, diagram.injectUtils);
|
||||
})
|
||||
);
|
||||
}
|
||||
await loadingPromise;
|
||||
};
|
||||
|
||||
/**
|
||||
* Equivalent to {@link init()}, except an error will be thrown on error.
|
||||
*
|
||||
* @alpha
|
||||
* @deprecated This is an internal function and will very likely be modified in v10, or earlier.
|
||||
* We recommend staying with {@link initThrowsErrors} if you don't need `lazyLoadedDiagrams`.
|
||||
*
|
||||
* @param config - **Deprecated** Mermaid sequenceConfig.
|
||||
* @param nodes - One of:
|
||||
* - A DOM Node
|
||||
* - An array of DOM nodes (as would come from a jQuery selector)
|
||||
* - A W3C selector, a la `.mermaid` (default)
|
||||
* @param callback - Function that is called with the id of each generated mermaid diagram.
|
||||
* @returns Resolves on success, otherwise the {@link Promise} will be rejected.
|
||||
*/
|
||||
const initThrowsErrorsAsync = async function (
|
||||
config?: MermaidConfig,
|
||||
// eslint-disable-next-line no-undef
|
||||
nodes?: string | HTMLElement | NodeListOf<HTMLElement>,
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
callback?: Function
|
||||
) {
|
||||
const conf = mermaidAPI.getConfig();
|
||||
|
||||
const registerLazyLoadedDiagramsErrors: Error[] = [];
|
||||
for (const registerResult of await registerLazyLoadedDiagrams(conf)) {
|
||||
if (registerResult.status == 'rejected') {
|
||||
registerLazyLoadedDiagramsErrors.push(registerResult.reason);
|
||||
}
|
||||
}
|
||||
|
||||
if (config) {
|
||||
// This is a legacy way of setting config. It is not documented and should be removed in the future.
|
||||
// @ts-ignore: TODO Fix ts errors
|
||||
mermaid.sequenceConfig = config;
|
||||
}
|
||||
|
||||
// if last argument is a function this is the callback function
|
||||
log.debug(`${!callback ? 'No ' : ''}Callback function found`);
|
||||
let nodesToProcess: ArrayLike<HTMLElement>;
|
||||
if (typeof nodes === 'undefined') {
|
||||
nodesToProcess = document.querySelectorAll('.mermaid');
|
||||
} else if (typeof nodes === 'string') {
|
||||
nodesToProcess = document.querySelectorAll(nodes);
|
||||
} else if (nodes instanceof HTMLElement) {
|
||||
nodesToProcess = [nodes];
|
||||
} else if (nodes instanceof NodeList) {
|
||||
nodesToProcess = nodes;
|
||||
} else {
|
||||
throw new Error('Invalid argument nodes for mermaid.init');
|
||||
}
|
||||
|
||||
log.debug(`Found ${nodesToProcess.length} diagrams`);
|
||||
if (typeof config?.startOnLoad !== 'undefined') {
|
||||
log.debug('Start On Load: ' + config?.startOnLoad);
|
||||
mermaidAPI.updateSiteConfig({ startOnLoad: config?.startOnLoad });
|
||||
}
|
||||
|
||||
// generate the id of the diagram
|
||||
const idGenerator = new utils.initIdGenerator(conf.deterministicIds, conf.deterministicIDSeed);
|
||||
|
||||
let txt: string;
|
||||
const errors: DetailedError[] = [];
|
||||
|
||||
// element is the current div with mermaid class
|
||||
for (const element of Array.from(nodesToProcess)) {
|
||||
log.info('Rendering diagram: ' + element.id);
|
||||
/*! Check if previously processed */
|
||||
if (element.getAttribute('data-processed')) {
|
||||
continue;
|
||||
}
|
||||
element.setAttribute('data-processed', 'true');
|
||||
|
||||
const id = `mermaid-${idGenerator.next()}`;
|
||||
|
||||
// Fetch the graph definition including tags
|
||||
txt = element.innerHTML;
|
||||
|
||||
// transforms the html to pure text
|
||||
txt = utils
|
||||
.entityDecode(txt)
|
||||
.trim()
|
||||
.replace(/<br\s*\/?>/gi, '<br/>');
|
||||
|
||||
const init = utils.detectInit(txt);
|
||||
if (init) {
|
||||
log.debug('Detected early reinit: ', init);
|
||||
}
|
||||
try {
|
||||
await mermaidAPI.renderAsync(
|
||||
id,
|
||||
txt,
|
||||
(svgCode: string, bindFunctions?: (el: Element) => void) => {
|
||||
element.innerHTML = svgCode;
|
||||
if (typeof callback !== 'undefined') {
|
||||
callback(id);
|
||||
}
|
||||
if (bindFunctions) bindFunctions(element);
|
||||
},
|
||||
element
|
||||
);
|
||||
} catch (error) {
|
||||
handleError(error, errors, mermaid.parseError);
|
||||
}
|
||||
}
|
||||
const allErrors = [...registerLazyLoadedDiagramsErrors, ...errors];
|
||||
if (allErrors.length > 0) {
|
||||
// TODO: We should be throwing an error object.
|
||||
throw allErrors[0];
|
||||
}
|
||||
};
|
||||
|
||||
const initialize = function (config: MermaidConfig) {
|
||||
mermaidAPI.initialize(config);
|
||||
};
|
||||
|
||||
/**
|
||||
* @param config
|
||||
* @deprecated This is an internal function and should not be used. Will be removed in v10.
|
||||
*/
|
||||
const initializeAsync = async function (config: MermaidConfig) {
|
||||
if (config.loadExternalDiagramsAtStartup) {
|
||||
await loadExternalDiagrams(config);
|
||||
} else {
|
||||
await registerLazyLoadedDiagrams(config);
|
||||
}
|
||||
mermaidAPI.initialize(config);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -219,7 +380,7 @@ if (typeof document !== 'undefined') {
|
||||
* This is provided for environments where the mermaid object can't directly have a new member added
|
||||
* to it (eg. dart interop wrapper). (Initially there is no parseError member of mermaid).
|
||||
*
|
||||
* @param {function (err, hash)} newParseErrorHandler New parseError() callback.
|
||||
* @param newParseErrorHandler New parseError() callback.
|
||||
*/
|
||||
const setParseErrorHandler = function (newParseErrorHandler: (err: any, hash: any) => void) {
|
||||
mermaid.parseError = newParseErrorHandler;
|
||||
@@ -229,6 +390,125 @@ const parse = (txt: string) => {
|
||||
return mermaidAPI.parse(txt, mermaid.parseError);
|
||||
};
|
||||
|
||||
const executionQueue: (() => Promise<unknown>)[] = [];
|
||||
let executionQueueRunning = false;
|
||||
const executeQueue = async () => {
|
||||
if (executionQueueRunning) {
|
||||
return;
|
||||
}
|
||||
executionQueueRunning = true;
|
||||
while (executionQueue.length > 0) {
|
||||
const f = executionQueue.shift();
|
||||
if (f) {
|
||||
try {
|
||||
await f();
|
||||
} catch (e) {
|
||||
log.error('Error executing queue', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
executionQueueRunning = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* @param txt
|
||||
* @deprecated This is an internal function and should not be used. Will be removed in v10.
|
||||
*/
|
||||
const parseAsync = (txt: string) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
// This promise will resolve when the mermaidAPI.render call is done.
|
||||
// It will be queued first and will be executed when it is first in line
|
||||
const performCall = () =>
|
||||
new Promise((res, rej) => {
|
||||
mermaidAPI.parseAsync(txt, mermaid.parseError).then(
|
||||
(r) => {
|
||||
// This resolves for the promise for the queue handling
|
||||
res(r);
|
||||
// This fullfills the promise sent to the value back to the original caller
|
||||
resolve(r);
|
||||
},
|
||||
(e) => {
|
||||
log.error('Error parsing', e);
|
||||
rej(e);
|
||||
reject(e);
|
||||
}
|
||||
);
|
||||
});
|
||||
executionQueue.push(performCall);
|
||||
executeQueue();
|
||||
});
|
||||
};
|
||||
|
||||
// const asynco = (id: string, delay: number) =>
|
||||
// new Promise((res) => {
|
||||
// setTimeout(() => {
|
||||
// // This resolves for the promise for the queue handling
|
||||
// res(id);
|
||||
// }, delay);
|
||||
// });
|
||||
|
||||
/**
|
||||
* @param txt
|
||||
* @param id
|
||||
* @param delay
|
||||
* @deprecated This is an internal function and should not be used. Will be removed in v10.
|
||||
*/
|
||||
// const test1 = (id: string, delay: number) => {
|
||||
// const p = new Promise((resolve, reject) => {
|
||||
// // This promise will resolve when the mermaidAPI.render call is done.
|
||||
// // It will be queued first and will be executed when it is first in line
|
||||
// const performCall = () =>
|
||||
// new Promise((res) => {
|
||||
// asynco(id, delay).then((r) => {
|
||||
// // This resolves for the promise for the queue handling
|
||||
// res(r);
|
||||
// // This fullfills the promise sent to the value back to the original caller
|
||||
// resolve(r + ' result to caller');
|
||||
// });
|
||||
// });
|
||||
// executionQueue.push(performCall);
|
||||
// });
|
||||
// return p;
|
||||
// };
|
||||
|
||||
/**
|
||||
* @param txt
|
||||
* @param id
|
||||
* @param text
|
||||
* @param cb
|
||||
* @param container
|
||||
* @deprecated This is an internal function and should not be used. Will be removed in v10.
|
||||
*/
|
||||
const renderAsync = (
|
||||
id: string,
|
||||
text: string,
|
||||
cb: (svgCode: string, bindFunctions?: (element: Element) => void) => void,
|
||||
container?: Element
|
||||
): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
// This promise will resolve when the mermaidAPI.render call is done.
|
||||
// It will be queued first and will be executed when it is first in line
|
||||
const performCall = () =>
|
||||
new Promise((res, rej) => {
|
||||
mermaidAPI.renderAsync(id, text, cb, container).then(
|
||||
(r) => {
|
||||
// This resolves for the promise for the queue handling
|
||||
res(r);
|
||||
// This fullfills the promise sent to the value back to the original caller
|
||||
resolve(r);
|
||||
},
|
||||
(e) => {
|
||||
log.error('Error parsing', e);
|
||||
rej(e);
|
||||
reject(e);
|
||||
}
|
||||
);
|
||||
});
|
||||
executionQueue.push(performCall);
|
||||
executeQueue();
|
||||
});
|
||||
};
|
||||
|
||||
const mermaid: {
|
||||
startOnLoad: boolean;
|
||||
diagrams: any;
|
||||
@@ -236,10 +516,14 @@ const mermaid: {
|
||||
parseError?: Function;
|
||||
mermaidAPI: typeof mermaidAPI;
|
||||
parse: typeof parse;
|
||||
parseAsync: typeof parseAsync;
|
||||
render: typeof mermaidAPI.render;
|
||||
renderAsync: typeof renderAsync;
|
||||
init: typeof init;
|
||||
initThrowsErrors: typeof initThrowsErrors;
|
||||
initThrowsErrorsAsync: typeof initThrowsErrorsAsync;
|
||||
initialize: typeof initialize;
|
||||
initializeAsync: typeof initializeAsync;
|
||||
contentLoaded: typeof contentLoaded;
|
||||
setParseErrorHandler: typeof setParseErrorHandler;
|
||||
} = {
|
||||
@@ -247,10 +531,14 @@ const mermaid: {
|
||||
diagrams: {},
|
||||
mermaidAPI,
|
||||
parse,
|
||||
parseAsync,
|
||||
render: mermaidAPI.render,
|
||||
renderAsync,
|
||||
init,
|
||||
initThrowsErrors,
|
||||
initThrowsErrorsAsync,
|
||||
initialize,
|
||||
initializeAsync,
|
||||
parseError: undefined,
|
||||
contentLoaded,
|
||||
setParseErrorHandler,
|
||||
|
@@ -44,6 +44,18 @@ function parse(text: string, parseError?: Function): boolean {
|
||||
return diagram.parse(text, parseError);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param text
|
||||
* @param parseError
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
async function parseAsync(text: string, parseError?: Function): Promise<boolean> {
|
||||
addDiagrams();
|
||||
const diagram = await getDiagramFromText(text, parseError);
|
||||
return diagram.parse(text, parseError);
|
||||
}
|
||||
|
||||
export const encodeEntities = function (text: string): string {
|
||||
let txt = text;
|
||||
|
||||
@@ -110,7 +122,283 @@ export const decodeEntities = function (text: string): string {
|
||||
* element will be removed when rendering is completed.
|
||||
* @returns {void}
|
||||
*/
|
||||
const render = async function (
|
||||
const render = function (
|
||||
id: string,
|
||||
text: string,
|
||||
cb: (svgCode: string, bindFunctions?: (element: Element) => void) => void,
|
||||
container?: Element
|
||||
): void {
|
||||
addDiagrams();
|
||||
configApi.reset();
|
||||
text = text.replace(/\r\n?/g, '\n'); // parser problems on CRLF ignore all CR and leave LF;;
|
||||
const graphInit = utils.detectInit(text);
|
||||
if (graphInit) {
|
||||
directiveSanitizer(graphInit);
|
||||
configApi.addDirective(graphInit);
|
||||
}
|
||||
const cnf = configApi.getConfig();
|
||||
|
||||
log.debug(cnf);
|
||||
|
||||
// Check the maximum allowed text size
|
||||
if (text.length > cnf.maxTextSize!) {
|
||||
text = 'graph TB;a[Maximum text size in diagram exceeded];style a fill:#faa';
|
||||
}
|
||||
|
||||
let root: any = select('body');
|
||||
|
||||
// In regular execution the container will be the div with a mermaid class
|
||||
if (typeof container !== 'undefined') {
|
||||
// A container was provided by the caller
|
||||
if (container) {
|
||||
container.innerHTML = '';
|
||||
}
|
||||
|
||||
if (cnf.securityLevel === 'sandbox') {
|
||||
// IF we are in sandboxed mode, we do everyting mermaid related
|
||||
// in a sandboxed div
|
||||
const iframe = select(container)
|
||||
.append('iframe')
|
||||
.attr('id', 'i' + id)
|
||||
.attr('style', 'width: 100%; height: 100%;')
|
||||
.attr('sandbox', '');
|
||||
// const iframeBody = ;
|
||||
root = select(iframe.nodes()[0]!.contentDocument!.body);
|
||||
root.node().style.margin = 0;
|
||||
} else {
|
||||
root = select(container);
|
||||
}
|
||||
|
||||
root
|
||||
.append('div')
|
||||
.attr('id', 'd' + id)
|
||||
.attr('style', 'font-family: ' + cnf.fontFamily)
|
||||
.append('svg')
|
||||
.attr('id', id)
|
||||
.attr('width', '100%')
|
||||
.attr('xmlns', 'http://www.w3.org/2000/svg')
|
||||
.attr('xmlns:xlink', 'http://www.w3.org/1999/xlink')
|
||||
.append('g');
|
||||
} else {
|
||||
// No container was provided
|
||||
// If there is an existing element with the id, we remove it
|
||||
// this likely a previously rendered diagram
|
||||
const existingSvg = document.getElementById(id);
|
||||
if (existingSvg) {
|
||||
existingSvg.remove();
|
||||
}
|
||||
|
||||
// Remove previous tpm element if it exists
|
||||
let element;
|
||||
if (cnf.securityLevel === 'sandbox') {
|
||||
element = document.querySelector('#i' + id);
|
||||
} else {
|
||||
element = document.querySelector('#d' + id);
|
||||
}
|
||||
|
||||
if (element) {
|
||||
element.remove();
|
||||
}
|
||||
|
||||
// Add the tmp div used for rendering with the id `d${id}`
|
||||
// d+id it will contain a svg with the id "id"
|
||||
|
||||
if (cnf.securityLevel === 'sandbox') {
|
||||
// IF we are in sandboxed mode, we do everyting mermaid related
|
||||
// in a sandboxed div
|
||||
const iframe = select('body')
|
||||
.append('iframe')
|
||||
.attr('id', 'i' + id)
|
||||
.attr('style', 'width: 100%; height: 100%;')
|
||||
.attr('sandbox', '');
|
||||
|
||||
root = select(iframe.nodes()[0]!.contentDocument!.body);
|
||||
root.node().style.margin = 0;
|
||||
} else {
|
||||
root = select('body');
|
||||
}
|
||||
|
||||
// This is the temporary div
|
||||
root
|
||||
.append('div')
|
||||
.attr('id', 'd' + id)
|
||||
// this is the seed of the svg to be rendered
|
||||
.append('svg')
|
||||
.attr('id', id)
|
||||
.attr('width', '100%')
|
||||
.attr('xmlns', 'http://www.w3.org/2000/svg')
|
||||
.append('g');
|
||||
}
|
||||
|
||||
text = encodeEntities(text);
|
||||
|
||||
// Important that we do not create the diagram until after the directives have been included
|
||||
let diag;
|
||||
let parseEncounteredException;
|
||||
try {
|
||||
// diag = new Diagram(text);
|
||||
diag = getDiagramFromText(text);
|
||||
if ('then' in diag) {
|
||||
throw new Error('Diagram is a promise');
|
||||
}
|
||||
} catch (error) {
|
||||
diag = new Diagram('error');
|
||||
parseEncounteredException = error;
|
||||
}
|
||||
// Get the tmp element containing the the svg
|
||||
const element = root.select('#d' + id).node();
|
||||
const graphType = diag.type;
|
||||
|
||||
// insert inline style into svg
|
||||
const svg = element.firstChild;
|
||||
const firstChild = svg.firstChild;
|
||||
|
||||
let userStyles = '';
|
||||
// user provided theme CSS
|
||||
// If you add more configuration driven data into the user styles make sure that the value is
|
||||
// sanitized bye the santiizeCSS function
|
||||
if (cnf.themeCSS !== undefined) {
|
||||
userStyles += `\n${cnf.themeCSS}`;
|
||||
}
|
||||
// user provided theme CSS
|
||||
if (cnf.fontFamily !== undefined) {
|
||||
userStyles += `\n:root { --mermaid-font-family: ${cnf.fontFamily}}`;
|
||||
}
|
||||
// user provided theme CSS
|
||||
if (cnf.altFontFamily !== undefined) {
|
||||
userStyles += `\n:root { --mermaid-alt-font-family: ${cnf.altFontFamily}}`;
|
||||
}
|
||||
|
||||
// classDef
|
||||
if (graphType === 'flowchart' || graphType === 'flowchart-v2' || graphType === 'graph') {
|
||||
const classes: any = flowRenderer.getClasses(text, diag);
|
||||
const htmlLabels = cnf.htmlLabels || cnf.flowchart?.htmlLabels;
|
||||
for (const className in classes) {
|
||||
if (htmlLabels) {
|
||||
userStyles += `\n.${className} > * { ${classes[className].styles.join(
|
||||
' !important; '
|
||||
)} !important; }`;
|
||||
userStyles += `\n.${className} span { ${classes[className].styles.join(
|
||||
' !important; '
|
||||
)} !important; }`;
|
||||
} else {
|
||||
userStyles += `\n.${className} path { ${classes[className].styles.join(
|
||||
' !important; '
|
||||
)} !important; }`;
|
||||
userStyles += `\n.${className} rect { ${classes[className].styles.join(
|
||||
' !important; '
|
||||
)} !important; }`;
|
||||
userStyles += `\n.${className} polygon { ${classes[className].styles.join(
|
||||
' !important; '
|
||||
)} !important; }`;
|
||||
userStyles += `\n.${className} ellipse { ${classes[className].styles.join(
|
||||
' !important; '
|
||||
)} !important; }`;
|
||||
userStyles += `\n.${className} circle { ${classes[className].styles.join(
|
||||
' !important; '
|
||||
)} !important; }`;
|
||||
if (classes[className].textStyles) {
|
||||
userStyles += `\n.${className} tspan { ${classes[className].textStyles.join(
|
||||
' !important; '
|
||||
)} !important; }`;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const stylis = (selector: string, styles: string) =>
|
||||
serialize(compile(`${selector}{${styles}}`), stringify);
|
||||
const rules = stylis(`#${id}`, getStyles(graphType, userStyles, cnf.themeVariables));
|
||||
|
||||
const style1 = document.createElement('style');
|
||||
style1.innerHTML = `#${id} ` + rules;
|
||||
svg.insertBefore(style1, firstChild);
|
||||
|
||||
try {
|
||||
diag.renderer.draw(text, id, pkg.version, diag);
|
||||
} catch (e) {
|
||||
errorRenderer.draw(text, id, pkg.version);
|
||||
throw e;
|
||||
}
|
||||
|
||||
root
|
||||
.select(`[id="${id}"]`)
|
||||
.selectAll('foreignobject > *')
|
||||
.attr('xmlns', 'http://www.w3.org/1999/xhtml');
|
||||
|
||||
// Fix for when the base tag is used
|
||||
let svgCode = root.select('#d' + id).node().innerHTML;
|
||||
|
||||
log.debug('cnf.arrowMarkerAbsolute', cnf.arrowMarkerAbsolute);
|
||||
if (!evaluate(cnf.arrowMarkerAbsolute) && cnf.securityLevel !== 'sandbox') {
|
||||
svgCode = svgCode.replace(/marker-end="url\(.*?#/g, 'marker-end="url(#', 'g');
|
||||
}
|
||||
|
||||
svgCode = decodeEntities(svgCode);
|
||||
|
||||
// Fix for when the br tag is used
|
||||
svgCode = svgCode.replace(/<br>/g, '<br/>');
|
||||
|
||||
if (cnf.securityLevel === 'sandbox') {
|
||||
const svgEl = root.select('#d' + id + ' svg').node();
|
||||
const width = '100%';
|
||||
let height = '100%';
|
||||
if (svgEl) {
|
||||
height = svgEl.viewBox.baseVal.height + 'px';
|
||||
}
|
||||
svgCode = `<iframe style="width:${width};height:${height};border:0;margin:0;" src="data:text/html;base64,${btoa(
|
||||
'<body style="margin:0">' + svgCode + '</body>'
|
||||
)}" sandbox="allow-top-navigation-by-user-activation allow-popups">
|
||||
The “iframe” tag is not supported by your browser.
|
||||
</iframe>`;
|
||||
} else {
|
||||
if (cnf.securityLevel !== 'loose') {
|
||||
svgCode = DOMPurify.sanitize(svgCode, {
|
||||
ADD_TAGS: ['foreignobject'],
|
||||
ADD_ATTR: ['dominant-baseline'],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof cb !== 'undefined') {
|
||||
switch (graphType) {
|
||||
case 'flowchart':
|
||||
case 'flowchart-v2':
|
||||
cb(svgCode, flowDb.bindFunctions);
|
||||
break;
|
||||
case 'gantt':
|
||||
cb(svgCode, ganttDb.bindFunctions);
|
||||
break;
|
||||
case 'class':
|
||||
case 'classDiagram':
|
||||
cb(svgCode, classDb.bindFunctions);
|
||||
break;
|
||||
default:
|
||||
cb(svgCode);
|
||||
}
|
||||
} else {
|
||||
log.debug('CB = undefined!');
|
||||
}
|
||||
attachFunctions();
|
||||
|
||||
const tmpElementSelector = cnf.securityLevel === 'sandbox' ? '#i' + id : '#d' + id;
|
||||
const node = select(tmpElementSelector).node();
|
||||
if (node && 'remove' in node) {
|
||||
node.remove();
|
||||
}
|
||||
|
||||
if (parseEncounteredException) {
|
||||
throw parseEncounteredException;
|
||||
}
|
||||
|
||||
return svgCode;
|
||||
};
|
||||
|
||||
/**
|
||||
* @deprecated This is an internal function and should not be used. Will be removed in v10.
|
||||
*/
|
||||
|
||||
const renderAsync = async function (
|
||||
id: string,
|
||||
text: string,
|
||||
cb: (svgCode: string, bindFunctions?: (element: Element) => void) => void,
|
||||
@@ -302,7 +590,7 @@ const render = async function (
|
||||
try {
|
||||
await diag.renderer.draw(text, id, pkg.version, diag);
|
||||
} catch (e) {
|
||||
await errorRenderer.draw(text, id, pkg.version);
|
||||
errorRenderer.draw(text, id, pkg.version);
|
||||
throw e;
|
||||
}
|
||||
|
||||
@@ -453,7 +741,7 @@ const handleDirective = function (p: any, directive: any, type: string): void {
|
||||
};
|
||||
|
||||
/** @param {MermaidConfig} options */
|
||||
async function initialize(options: MermaidConfig = {}) {
|
||||
function initialize(options: MermaidConfig = {}) {
|
||||
// Handle legacy location of font-family configuration
|
||||
if (options.fontFamily) {
|
||||
if (!options.themeVariables) {
|
||||
@@ -483,7 +771,9 @@ async function initialize(options: MermaidConfig = {}) {
|
||||
|
||||
export const mermaidAPI = Object.freeze({
|
||||
render,
|
||||
renderAsync,
|
||||
parse,
|
||||
parseAsync,
|
||||
parseDirective,
|
||||
initialize,
|
||||
getConfig: configApi.getConfig,
|
||||
@@ -502,6 +792,7 @@ export const mermaidAPI = Object.freeze({
|
||||
setLogLevel(configApi.getConfig().logLevel);
|
||||
configApi.reset(configApi.getConfig());
|
||||
export default mermaidAPI;
|
||||
|
||||
/**
|
||||
* ## mermaidAPI configuration defaults
|
||||
*
|
||||
|
@@ -147,11 +147,18 @@ class Theme {
|
||||
this['cScaleInv' + i] = this['cScaleInv' + i] || adjust(this['cScale' + i], { h: 180 });
|
||||
}
|
||||
|
||||
// Setup teh label color for the set
|
||||
this.scaleLabelColor = this.scaleLabelColor || (this.darkMode ? 'black' : this.labelTextColor);
|
||||
// Setup the label color for the set
|
||||
this.scaleLabelColor =
|
||||
this.scaleLabelColor !== 'calculated' && this.scaleLabelColor
|
||||
? this.scaleLabelColor
|
||||
: this.labelTextColor;
|
||||
|
||||
for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {
|
||||
this['cScaleLabel' + i] = this['cScaleLabel' + i] || this.scaleLabelColor;
|
||||
if (this.labelTextColor !== 'calculated') {
|
||||
this.cScaleLabel0 = this.cScaleLabel0 || invert(this.labelTextColor);
|
||||
this.cScaleLabel3 = this.cScaleLabel3 || invert(this.labelTextColor);
|
||||
for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {
|
||||
this['cScaleLabel' + i] = this['cScaleLabel' + i] || this.labelTextColor;
|
||||
}
|
||||
}
|
||||
|
||||
/* Flowchart variables */
|
||||
|
@@ -121,7 +121,10 @@ class Theme {
|
||||
}
|
||||
|
||||
// Setup teh label color for the set
|
||||
this.scaleLabelColor = this.scaleLabelColor || (this.darkMode ? 'black' : this.labelTextColor);
|
||||
this.scaleLabelColor =
|
||||
this.scaleLabelColor !== 'calculated' && this.scaleLabelColor
|
||||
? this.scaleLabelColor
|
||||
: this.labelTextColor;
|
||||
|
||||
for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {
|
||||
this['cScaleLabel' + i] = this['cScaleLabel' + i] || this.scaleLabelColor;
|
||||
|
@@ -825,6 +825,8 @@ export const sanitizeCss = (str) => {
|
||||
export interface DetailedError {
|
||||
str: string;
|
||||
hash: any;
|
||||
error?: any;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/** @param error */
|
||||
|
1433
pnpm-lock.yaml
generated
1433
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user