Compare commits

..

32 Commits

Author SHA1 Message Date
Knut Sveidqvist
e78ac9b92a Updated version 2022-11-01 15:27:20 +01:00
Knut Sveidqvist
d4c19ffa59 Merge branch 'release/9.2.0' of github.com:mermaid-js/mermaid into release/9.2.0 2022-10-28 09:34:36 +02:00
Knut Sveidqvist
120940f9f4 Merge pull request #3731 from aloisklink/fix/load-lazy-loaded-diagrams-in-initThrowsErrors
[9.2.0] Support `lazyLoadedDiagrams` when calling `initThrowsErrorsAsync`
2022-10-28 09:33:58 +02:00
Alois Klink
48b1f489fc fix(mermaid): error if lazyLoadedDiagrams fails
Throws and logs a warning if lazyLoadedDiagrams fails to load properly.

Rendering is still performed, even on a lazyLoadedDiagrams failure.
2022-10-27 17:48:21 +01:00
Alois Klink
e62dd255bc feat: expose initThrowsErrorsAsync publicly
Expose the function `initThrowsErrorsAsync()` publicly
as `mermaid.initThrowsErrorsAsync()`.

It has the TSDoc `@alpha` and `@deprecated` tags, so people should
be warned that it might be modified in Mermaid v10 or earlier.

Needed for `mermaid-cli` to handle `lazyLoadedDiagrams`.
2022-10-27 17:48:12 +01:00
Alois Klink
13110c4ed9 docs(mermaid): document initThrowsErrorsAsync
Add some basic tsdoc for initThrowsErrorsAsync.
2022-10-27 17:02:50 +01:00
Alois Klink
327fcbf902 fix: lazy load diagrams in initThrowsErrorsAsync
Previously, calling initThrowsErrorsAsync would not
load any of the lazyLoadedDiagrams entries.

Adaptated from reverted commit 4601c90904
2022-10-27 16:50:57 +01:00
Alois Klink
81924f72c8 Revert "Merge branch 'release_9.2.0_buggfixes'"
This reverts commit 1a0309fb87, reversing
changes made to 56a8068a7f.

This is because the PR https://github.com/mermaid-js/mermaid/pull/3702
worked fine on the `develop` and `release_9.2.0_buggfixes` branches,
but had a bunch of git merge conflicts on the `release/9.2.0` branch.
2022-10-27 16:43:09 +01:00
Knut Sveidqvist
1a0309fb87 Merge branch 'release_9.2.0_buggfixes'
Conflicts:
	packages/mermaid/src/mermaid.ts
2022-10-24 10:28:27 +02:00
Knut Sveidqvist
e793aae0ec Merge pull request #3702 from aloisklink/fix/initThrowErrors-support-lazyLoadedDiagrams
Support `lazyLoadedDiagrams` when calling `initThrowsErrors`
2022-10-24 08:28:50 +02:00
Alois Klink
3a2669e634 fix(mermaid): error if lazyLoadedDiagrams fails
Throw an error if lazyLoadedDiagrams fails to load properly.

Rendering is still performed, even on a lazyLoadedDiagrams failure.
2022-10-23 13:19:40 +01:00
Alois Klink
895a5eb78a docs(mermaid): document initThrowsErrors
Add some basic tsdoc for initThrowsErrors
2022-10-23 13:19:33 +01:00
Alois Klink
4601c90904 fix: load lazyLoadedDiagrams in initThrowsErrors
Previously, calling initThrowsErrors would not
load any of the lazyLoadedDiagrams entries.
2022-10-23 13:19:26 +01:00
Knut Sveidqvist
8ad8d39fe4 Versions for latest rcs 2022-10-20 12:57:29 +02:00
Sidharth Vinod
56a8068a7f fix: Error handling 2022-10-19 20:30:07 +05:30
Sidharth Vinod
d17aa6ecdd Merge branch 'release_9.2.0_buggfixes' into release/9.2.0
* release_9.2.0_buggfixes:
  fix: Add default arg to options
  fix: Build types
  chore: Update creation date
  fix: getElementById type issue.
2022-10-19 19:21:19 +05:30
Knut Sveidqvist
6f27363862 Merge pull request #3683 from mermaid-js/sidv/TSMindmap
fix: Converts mindmapDB to TS
2022-10-19 15:47:08 +02:00
Sidharth Vinod
5192608f7c Merge branch 'release_9.2.0_buggfixes' into sidv/TSMindmap
* release_9.2.0_buggfixes:
  fix: Add default arg to options
2022-10-19 19:13:46 +05:30
Sidharth Vinod
77f5e0d5f3 fix: Add default arg to options 2022-10-19 19:13:05 +05:30
Sidharth Vinod
4c311ea4b1 fix: TS errors 2022-10-19 19:03:29 +05:30
Sidharth Vinod
bbb3712284 Merge branch 'release_9.2.0_buggfixes' into sidv/TSMindmap
* release_9.2.0_buggfixes:
  Color fix for default nodes in mindmap, line uses inv color
2022-10-19 18:42:13 +05:30
Knut Sveidqvist
1388e201e5 Adding queue for async calls in mermaidts and fixing icon color 2022-10-19 14:30:36 +02:00
Sidharth Vinod
125312c114 chore: Add CORS to vite dev 2022-10-19 12:48:09 +02:00
Knut Sveidqvist
ea314cd24a Setting version to rc7 2022-10-19 08:01:21 +02:00
Knut Sveidqvist
8230c8f8b4 Merge remote-tracking branch 'origin/release/9.2.0' into release/9.2.0 2022-10-19 07:52:14 +02:00
Knut Sveidqvist
d115fbc6da Merge branch 'release_9.2.0_buggfixes' into release/9.2.0 2022-10-19 07:52:05 +02:00
Knut Sveidqvist
2ae8bf2987 Color fix for default nodes in mindmap, line uses inv color 2022-10-18 16:04:14 +02:00
Knut Sveidqvist
e86d7894f5 #3680 Add font familiy in a way that does remove other configuration 2022-10-17 10:51:41 +02:00
Knut Sveidqvist
752a6b2cb0 #3687 Separating the render specific data from the data related to parsing 2022-10-17 10:46:46 +02:00
Sidharth Vinod
97a842e651 fix: Build types 2022-10-17 11:45:19 +05:30
Sidharth Vinod
c83e29c6e3 chore: Update creation date 2022-10-16 10:11:19 +05:30
Sidharth Vinod
a4af3704ba fix: getElementById type issue.
Converts mindmapDB to TS
2022-10-16 10:06:44 +05:30
16 changed files with 261 additions and 63 deletions

View File

@@ -1,7 +1,15 @@
import express from 'express'; import express, { NextFunction, Request, Response } from 'express';
import { createServer as createViteServer } from 'vite'; import { createServer as createViteServer } from 'vite';
// import { getBuildConfig } from './build'; // 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() { async function createServer() {
const app = express(); const app = express();
@@ -12,6 +20,7 @@ async function createServer() {
appType: 'custom', // don't include Vite's default HTML handling middlewares 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/dist'));
app.use(express.static('./packages/mermaid-example-diagram/dist')); app.use(express.static('./packages/mermaid-example-diagram/dist'));
app.use(express.static('./packages/mermaid-mindmap/dist')); app.use(express.static('./packages/mermaid-mindmap/dist'));

View File

@@ -28,7 +28,7 @@
"scripts": { "scripts": {
"build:mermaid": "ts-node-esm --transpileOnly --project=.vite/tsconfig.json .vite/build.ts --mermaid", "build:mermaid": "ts-node-esm --transpileOnly --project=.vite/tsconfig.json .vite/build.ts --mermaid",
"build:vite": "ts-node-esm --transpileOnly --project=.vite/tsconfig.json .vite/build.ts", "build:vite": "ts-node-esm --transpileOnly --project=.vite/tsconfig.json .vite/build.ts",
"build:types": "concurrently \"tsc -p ./packages/mermaid/tsconfig.json --emitDeclarationOnly\" \"tsc -p ./packages/mermaid-mindmap/tsconfig.json --emitDeclarationOnly\"", "build:types": "tsc -p ./packages/mermaid/tsconfig.json --emitDeclarationOnly && tsc -p ./packages/mermaid-mindmap/tsconfig.json --emitDeclarationOnly",
"build:watch": "pnpm build:vite --watch", "build:watch": "pnpm build:vite --watch",
"build": "pnpm run -r clean && concurrently \"pnpm build:vite\" \"pnpm build:types\"", "build": "pnpm run -r clean && concurrently \"pnpm build:vite\" \"pnpm build:types\"",
"dev": "concurrently \"pnpm build:vite --watch\" \"ts-node-esm .vite/server.ts\"", "dev": "concurrently \"pnpm build:vite --watch\" \"ts-node-esm .vite/server.ts\"",

View File

@@ -1,6 +1,6 @@
{ {
"name": "@mermaid-js/mermaid-mindmap", "name": "@mermaid-js/mermaid-mindmap",
"version": "9.2.0-rc3", "version": "9.2.0",
"description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.", "description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.",
"main": "dist/mermaid-mindmap.core.mjs", "main": "dist/mermaid-mindmap.core.mjs",
"module": "dist/mermaid-mindmap.core.mjs", "module": "dist/mermaid-mindmap.core.mjs",

View File

@@ -1,4 +1,4 @@
import type { MermaidConfig } from 'mermaid/dist/config.type'; import type { MermaidConfig } from 'mermaid';
const warning = (s: string) => { const warning = (s: string) => {
// Todo remove debug code // Todo remove debug code

View File

@@ -1,6 +1,6 @@
/** Created by knut on 15-01-14. */ /** Created by knut on 23-07-2022. */
import { sanitizeText, getConfig, log } from './mermaidUtils'; import { sanitizeText, getConfig, log } from './mermaidUtils';
import type { DetailedError } from 'mermaid/dist/utils'; import type { DetailedError } from 'mermaid';
interface Node { interface Node {
id: number; id: number;
@@ -17,11 +17,9 @@ interface Node {
let nodes: Node[] = []; let nodes: Node[] = [];
let cnt = 0; let cnt = 0;
let elements: Record<number, HTMLElement> = {};
export const clear = () => { export const clear = () => {
nodes = []; nodes = [];
cnt = 0; cnt = 0;
elements = {};
}; };
const getParent = function (level: number) { const getParent = function (level: number) {
@@ -107,10 +105,6 @@ export const getType = (startStr: string, endStr: string): number => {
} }
}; };
export const setElementForId = (id: number, element: HTMLElement) => {
elements[id] = element;
};
export const decorateNode = (decoration: { icon: string; class: string }) => { export const decorateNode = (decoration: { icon: string; class: string }) => {
const node = nodes[nodes.length - 1]; const node = nodes[nodes.length - 1];
if (decoration && decoration.icon) { if (decoration && decoration.icon) {
@@ -150,5 +144,3 @@ export const setErrorHandler = (handler: ParseErrorFunction) => {
export const getLogger = () => log; export const getLogger = () => log;
export const getNodeById = (id: number): Node => nodes[id]; export const getNodeById = (id: number): Node => nodes[id];
export const getElementById = (id: number | string): HTMLElement =>
elements[typeof id === 'string' ? parseInt(id) : id];

View File

@@ -1,10 +1,9 @@
/** Created by knut on 14-12-11. */ /** Created by knut on 23-07-2022. */
import { select } from 'd3'; import { select } from 'd3';
import { log, getConfig, setupGraphViewbox } from './mermaidUtils'; import { log, getConfig, setupGraphViewbox } from './mermaidUtils';
import svgDraw from './svgDraw'; import svgDraw, { getElementById, clearElementRefs } from './svgDraw';
import cytoscape from 'cytoscape'; import cytoscape from 'cytoscape';
import coseBilkent from 'cytoscape-cose-bilkent'; import coseBilkent from 'cytoscape-cose-bilkent';
import * as db from './mindmapDb';
// Inject the layout algorithm into cytoscape // Inject the layout algorithm into cytoscape
cytoscape.use(coseBilkent); cytoscape.use(coseBilkent);
@@ -155,7 +154,7 @@ function positionNodes(cy) {
data.x = node.position().x; data.x = node.position().x;
data.y = node.position().y; data.y = node.position().y;
svgDraw.positionNode(data); svgDraw.positionNode(data);
const el = db.getElementById(data.nodeId); const el = getElementById(data.nodeId);
log.info('Id:', id, 'Position: (', node.position().x, ', ', node.position().y, ')', data); log.info('Id:', id, 'Position: (', node.position().x, ', ', node.position().y, ')', data);
el.attr( el.attr(
'transform', 'transform',
@@ -179,6 +178,7 @@ export const draw = async (text, id, version, diagObj) => {
// This is done only for throwing the error if the text is not valid. // This is done only for throwing the error if the text is not valid.
diagObj.db.clear(); diagObj.db.clear();
clearElementRefs();
// Parse the graph definition // Parse the graph definition
diagObj.parser.parse(text); diagObj.parser.parse(text);

View File

@@ -22,12 +22,10 @@ const genSections = (options) => {
} }
.section-${i - 1} text { .section-${i - 1} text {
fill: ${options['cScaleLabel' + i]}; fill: ${options['cScaleLabel' + i]};
// fill: ${options['gitInv' + i]};
} }
.node-icon-${i - 1} { .node-icon-${i - 1} {
font-size: 40px; font-size: 40px;
color: ${options['cScaleLabel' + i]}; color: ${options['cScaleLabel' + i]};
// color: ${options['gitInv' + i]};
} }
.section-edge-${i - 1}{ .section-edge-${i - 1}{
stroke: ${options['cScale' + i]}; stroke: ${options['cScale' + i]};
@@ -36,7 +34,7 @@ const genSections = (options) => {
stroke-width: ${sw}; stroke-width: ${sw};
} }
.section-${i - 1} line { .section-${i - 1} line {
stroke: ${options['lineColor' + i]} ; stroke: ${options['cScaleInv' + i]} ;
stroke-width: 3; stroke-width: 3;
} }

View File

@@ -259,7 +259,7 @@ export const drawNode = function (elem, node, fullSection, conf) {
// if (typeof node.x !== 'undefined' && typeof node.y !== 'undefined') { // if (typeof node.x !== 'undefined' && typeof node.y !== 'undefined') {
// nodeElem.attr('transform', 'translate(' + node.x + ',' + node.y + ')'); // nodeElem.attr('transform', 'translate(' + node.x + ',' + node.y + ')');
// } // }
db.setElementForId(node.id, nodeElem); setElementById(node.id, nodeElem);
return node.height; return node.height;
}; };
@@ -286,7 +286,7 @@ export const drawEdge = function drawEdge(edgesElem, mindmap, parent, depth, ful
}; };
export const positionNode = function (node) { export const positionNode = function (node) {
const nodeElem = db.getElementById(node.id); const nodeElem = getElementById(node.id);
const x = node.x || 0; const x = node.x || 0;
const y = node.y || 0; const y = node.y || 0;
@@ -294,4 +294,18 @@ export const positionNode = function (node) {
nodeElem.attr('transform', 'translate(' + x + ',' + y + ')'); nodeElem.attr('transform', 'translate(' + x + ',' + y + ')');
}; };
let elements = {};
const setElementById = (id, element) => {
elements[id] = element;
};
export const getElementById = (id) => {
return elements[id];
};
export const clearElementRefs = () => {
elements = {};
};
export default { drawNode, positionNode, drawEdge }; export default { drawNode, positionNode, drawEdge };

View File

@@ -1,6 +1,6 @@
{ {
"name": "mermaid", "name": "mermaid",
"version": "9.2.0-rc6", "version": "9.2.0",
"description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.", "description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.",
"main": "./dist/mermaid.core.mjs", "main": "./dist/mermaid.core.mjs",
"module": "./dist/mermaid.core.mjs", "module": "./dist/mermaid.core.mjs",

View File

@@ -25,6 +25,7 @@ function parse(text: string, parseError?: Function): boolean {
// original version cannot be modified since it was frozen with `Object.freeze()` // original version cannot be modified since it was frozen with `Object.freeze()`
export const mermaidAPI = { export const mermaidAPI = {
render: vi.fn(), render: vi.fn(),
renderAsync: vi.fn(),
parse, parse,
parseDirective: vi.fn(), parseDirective: vi.fn(),
initialize: vi.fn(), initialize: vi.fn(),

View File

@@ -54,6 +54,29 @@ describe('when using mermaid and ', function () {
expect(mermaidAPI.render).toHaveBeenCalled(); 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;'));
mermaidAPI.setConfig({
lazyLoadedDiagrams: ['this-file-does-not-exist.mjs'],
});
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.renderAsync).toHaveBeenCalled();
});
afterEach(() => {
// we modify mermaid config in some tests, so we need to make sure to reset them
mermaidAPI.reset();
});
});
describe('checking validity of input ', function () { describe('checking validity of input ', function () {
it('should throw for an invalid definition', function () { it('should throw for an invalid definition', function () {

View File

@@ -2,14 +2,15 @@
* Web page integration module for the mermaid framework. It uses the mermaidAPI for mermaid * Web page integration module for the mermaid framework. It uses the mermaidAPI for mermaid
* functionality and to render the diagrams to svg code! * functionality and to render the diagrams to svg code!
*/ */
import { MermaidConfig } from './config.type'; import type { MermaidConfig } from './config.type';
import { log } from './logger'; import { log } from './logger';
import utils from './utils'; import utils from './utils';
import { mermaidAPI } from './mermaidAPI'; import { mermaidAPI } from './mermaidAPI';
import { addDetector } from './diagram-api/detectType'; import { addDetector } from './diagram-api/detectType';
import { isDetailedError } from './utils'; import { isDetailedError, type DetailedError } from './utils';
import { registerDiagram } from './diagram-api/diagramAPI'; import { registerDiagram } from './diagram-api/diagramAPI';
export type { MermaidConfig, DetailedError };
/** /**
* ## init * ## init
* *
@@ -48,7 +49,6 @@ const init = async function (
try { try {
const conf = mermaidAPI.getConfig(); const conf = mermaidAPI.getConfig();
if (conf?.lazyLoadedDiagrams && conf.lazyLoadedDiagrams.length > 0) { if (conf?.lazyLoadedDiagrams && conf.lazyLoadedDiagrams.length > 0) {
await registerLazyLoadedDiagrams(conf);
await initThrowsErrorsAsync(config, nodes, callback); await initThrowsErrorsAsync(config, nodes, callback);
} else { } else {
initThrowsErrors(config, nodes, callback); initThrowsErrors(config, nodes, callback);
@@ -64,6 +64,31 @@ const init = 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 ( const initThrowsErrors = function (
config?: MermaidConfig, config?: MermaidConfig,
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
@@ -72,7 +97,6 @@ const initThrowsErrors = function (
callback?: Function callback?: Function
) { ) {
const conf = mermaidAPI.getConfig(); const conf = mermaidAPI.getConfig();
// console.log('Starting rendering diagrams (init) - mermaid.init', conf);
if (config) { if (config) {
// This is a legacy way of setting config. It is not documented and should be removed in the future. // 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 // @ts-ignore: TODO Fix ts errors
@@ -104,7 +128,7 @@ const initThrowsErrors = function (
const idGenerator = new utils.initIdGenerator(conf.deterministicIds, conf.deterministicIDSeed); const idGenerator = new utils.initIdGenerator(conf.deterministicIds, conf.deterministicIDSeed);
let txt: string; let txt: string;
const errors = []; const errors: DetailedError[] = [];
// element is the current div with mermaid class // element is the current div with mermaid class
for (const element of Array.from(nodesToProcess)) { for (const element of Array.from(nodesToProcess)) {
@@ -144,13 +168,7 @@ const initThrowsErrors = function (
element element
); );
} catch (error) { } catch (error) {
log.warn('Catching Error (bootstrap)', error); handleError(error, errors, mermaid.parseError);
// @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);
} }
} }
if (errors.length > 0) { if (errors.length > 0) {
@@ -159,10 +177,12 @@ const initThrowsErrors = function (
} }
}; };
let lazyLoadingPromise: Promise<unknown> | undefined = undefined; let lazyLoadingPromise: Promise<PromiseSettledResult<void>[]> | undefined = undefined;
/** /**
* @param conf * This is an internal function and should not be made public, as it will likely change.
* @deprecated This is an internal function and should not be used. Will be removed in v10. * @internal
* @param conf - Mermaid config.
* @returns An array of {@link PromiseSettledResult}, showing the status of imports.
*/ */
const registerLazyLoadedDiagrams = async (conf: MermaidConfig) => { const registerLazyLoadedDiagrams = async (conf: MermaidConfig) => {
// Only lazy load once // Only lazy load once
@@ -176,7 +196,7 @@ const registerLazyLoadedDiagrams = async (conf: MermaidConfig) => {
}) })
); );
} }
await lazyLoadingPromise; return await lazyLoadingPromise;
}; };
let loadingPromise: Promise<unknown> | undefined = undefined; let loadingPromise: Promise<unknown> | undefined = undefined;
@@ -199,9 +219,20 @@ const loadExternalDiagrams = async (conf: MermaidConfig) => {
}; };
/** /**
* @deprecated This is an internal function and should not be used. Will be removed in v10. * 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 ( const initThrowsErrorsAsync = async function (
config?: MermaidConfig, config?: MermaidConfig,
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
@@ -210,7 +241,14 @@ const initThrowsErrorsAsync = async function (
callback?: Function callback?: Function
) { ) {
const conf = mermaidAPI.getConfig(); const conf = mermaidAPI.getConfig();
// console.log('Starting rendering diagrams (init) - mermaid.init', conf);
const registerLazyLoadedDiagramsErrors: Error[] = [];
for (const registerResult of await registerLazyLoadedDiagrams(conf)) {
if (registerResult.status == 'rejected') {
registerLazyLoadedDiagramsErrors.push(registerResult.reason);
}
}
if (config) { if (config) {
// This is a legacy way of setting config. It is not documented and should be removed in the future. // 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 // @ts-ignore: TODO Fix ts errors
@@ -242,7 +280,7 @@ const initThrowsErrorsAsync = async function (
const idGenerator = new utils.initIdGenerator(conf.deterministicIds, conf.deterministicIDSeed); const idGenerator = new utils.initIdGenerator(conf.deterministicIds, conf.deterministicIDSeed);
let txt: string; let txt: string;
const errors = []; const errors: DetailedError[] = [];
// element is the current div with mermaid class // element is the current div with mermaid class
for (const element of Array.from(nodesToProcess)) { for (const element of Array.from(nodesToProcess)) {
@@ -282,18 +320,13 @@ const initThrowsErrorsAsync = async function (
element element
); );
} catch (error) { } catch (error) {
log.warn('Catching Error (bootstrap)', error); handleError(error, errors, mermaid.parseError);
// @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);
} }
} }
if (errors.length > 0) { const allErrors = [...registerLazyLoadedDiagramsErrors, ...errors];
if (allErrors.length > 0) {
// TODO: We should be throwing an error object. // TODO: We should be throwing an error object.
throw errors[0]; throw allErrors[0];
} }
}; };
@@ -357,12 +390,123 @@ const parse = (txt: string) => {
return mermaidAPI.parse(txt, mermaid.parseError); 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 * @param txt
* @deprecated This is an internal function and should not be used. Will be removed in v10. * @deprecated This is an internal function and should not be used. Will be removed in v10.
*/ */
const parseAsync = (txt: string) => { const parseAsync = (txt: string) => {
return mermaidAPI.parseAsync(txt, mermaid.parseError); 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: { const mermaid: {
@@ -374,8 +518,10 @@ const mermaid: {
parse: typeof parse; parse: typeof parse;
parseAsync: typeof parseAsync; parseAsync: typeof parseAsync;
render: typeof mermaidAPI.render; render: typeof mermaidAPI.render;
renderAsync: typeof renderAsync;
init: typeof init; init: typeof init;
initThrowsErrors: typeof initThrowsErrors; initThrowsErrors: typeof initThrowsErrors;
initThrowsErrorsAsync: typeof initThrowsErrorsAsync;
initialize: typeof initialize; initialize: typeof initialize;
initializeAsync: typeof initializeAsync; initializeAsync: typeof initializeAsync;
contentLoaded: typeof contentLoaded; contentLoaded: typeof contentLoaded;
@@ -387,8 +533,10 @@ const mermaid: {
parse, parse,
parseAsync, parseAsync,
render: mermaidAPI.render, render: mermaidAPI.render,
renderAsync,
init, init,
initThrowsErrors, initThrowsErrors,
initThrowsErrorsAsync,
initialize, initialize,
initializeAsync, initializeAsync,
parseError: undefined, parseError: undefined,

View File

@@ -741,12 +741,13 @@ const handleDirective = function (p: any, directive: any, type: string): void {
}; };
/** @param {MermaidConfig} options */ /** @param {MermaidConfig} options */
function initialize(options: MermaidConfig) { function initialize(options: MermaidConfig = {}) {
// Handle legacy location of font-family configuration // Handle legacy location of font-family configuration
if (options?.fontFamily) { if (options.fontFamily) {
if (!options.themeVariables?.fontFamily) { if (!options.themeVariables) {
options.themeVariables = { fontFamily: options.fontFamily }; options.themeVariables = {};
} }
options.themeVariables.fontFamily = options.fontFamily;
} }
// Set default options // Set default options

View File

@@ -147,11 +147,18 @@ class Theme {
this['cScaleInv' + i] = this['cScaleInv' + i] || adjust(this['cScale' + i], { h: 180 }); this['cScaleInv' + i] = this['cScaleInv' + i] || adjust(this['cScale' + i], { h: 180 });
} }
// Setup teh label color for the set // Setup the 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++) { if (this.labelTextColor !== 'calculated') {
this['cScaleLabel' + i] = this['cScaleLabel' + i] || this.scaleLabelColor; 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 */ /* Flowchart variables */

View File

@@ -121,7 +121,10 @@ class Theme {
} }
// Setup teh label color for the set // 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++) { for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {
this['cScaleLabel' + i] = this['cScaleLabel' + i] || this.scaleLabelColor; this['cScaleLabel' + i] = this['cScaleLabel' + i] || this.scaleLabelColor;

View File

@@ -825,6 +825,8 @@ export const sanitizeCss = (str) => {
export interface DetailedError { export interface DetailedError {
str: string; str: string;
hash: any; hash: any;
error?: any;
message?: string;
} }
/** @param error */ /** @param error */