Compare commits

..

1 Commits

Author SHA1 Message Date
Sidharth Vinod
87cdc03e84 fix: getElementById type issue.
Converts mindmapDB to TS
2022-10-16 10:05:11 +05:30
16 changed files with 71 additions and 269 deletions

View File

@@ -1,15 +1,7 @@
import express, { NextFunction, Request, Response } from 'express';
import express 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();
@@ -20,7 +12,6 @@ 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'));

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@mermaid-js/mermaid-mindmap",
"version": "9.2.0",
"version": "9.2.0-rc3",
"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",

View File

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

View File

@@ -1,6 +1,6 @@
/** Created by knut on 23-07-2022. */
/** Created by knut on 15-01-14. */
import { sanitizeText, getConfig, log } from './mermaidUtils';
import type { DetailedError } from 'mermaid';
import type { DetailedError } from 'mermaid/dist/utils';
interface Node {
id: number;
@@ -17,9 +17,11 @@ interface Node {
let nodes: Node[] = [];
let cnt = 0;
let elements: Record<number, HTMLElement> = {};
export const clear = () => {
nodes = [];
cnt = 0;
elements = {};
};
const getParent = function (level: number) {
@@ -105,6 +107,10 @@ 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 }) => {
const node = nodes[nodes.length - 1];
if (decoration && decoration.icon) {
@@ -144,3 +150,5 @@ export const setErrorHandler = (handler: ParseErrorFunction) => {
export const getLogger = () => log;
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,9 +1,10 @@
/** Created by knut on 23-07-2022. */
/** Created by knut on 14-12-11. */
import { select } from 'd3';
import { log, getConfig, setupGraphViewbox } from './mermaidUtils';
import svgDraw, { getElementById, clearElementRefs } from './svgDraw';
import svgDraw from './svgDraw';
import cytoscape from 'cytoscape';
import coseBilkent from 'cytoscape-cose-bilkent';
import * as db from './mindmapDb';
// Inject the layout algorithm into cytoscape
cytoscape.use(coseBilkent);
@@ -154,7 +155,7 @@ function positionNodes(cy) {
data.x = node.position().x;
data.y = node.position().y;
svgDraw.positionNode(data);
const el = getElementById(data.nodeId);
const el = db.getElementById(data.nodeId);
log.info('Id:', id, 'Position: (', node.position().x, ', ', node.position().y, ')', data);
el.attr(
'transform',
@@ -178,7 +179,6 @@ export const draw = async (text, id, version, diagObj) => {
// This is done only for throwing the error if the text is not valid.
diagObj.db.clear();
clearElementRefs();
// Parse the graph definition
diagObj.parser.parse(text);

View File

@@ -22,10 +22,12 @@ 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]};
// color: ${options['gitInv' + i]};
}
.section-edge-${i - 1}{
stroke: ${options['cScale' + i]};
@@ -34,7 +36,7 @@ const genSections = (options) => {
stroke-width: ${sw};
}
.section-${i - 1} line {
stroke: ${options['cScaleInv' + i]} ;
stroke: ${options['lineColor' + i]} ;
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') {
// nodeElem.attr('transform', 'translate(' + node.x + ',' + node.y + ')');
// }
setElementById(node.id, nodeElem);
db.setElementForId(node.id, nodeElem);
return node.height;
};
@@ -286,7 +286,7 @@ export const drawEdge = function drawEdge(edgesElem, mindmap, parent, depth, ful
};
export const positionNode = function (node) {
const nodeElem = getElementById(node.id);
const nodeElem = db.getElementById(node.id);
const x = node.x || 0;
const y = node.y || 0;
@@ -294,18 +294,4 @@ export const positionNode = function (node) {
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 };

View File

@@ -1,11 +1,11 @@
{
"name": "mermaid",
"version": "9.2.0",
"version": "9.2.0-rc6",
"description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.",
"main": "./dist/mermaid.min.js",
"main": "./dist/mermaid.core.mjs",
"module": "./dist/mermaid.core.mjs",
"types": "./dist/mermaid.d.ts",
"type": "commonjs",
"type": "module",
"exports": {
".": {
"require": "./dist/mermaid.min.js",

View File

@@ -25,7 +25,6 @@ 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(),

View File

@@ -54,29 +54,6 @@ describe('when using mermaid and ', function () {
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 () {
it('should throw for an invalid definition', function () {

View File

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

View File

@@ -115,19 +115,19 @@ export const decodeEntities = function (text: string): string {
*
* @param {string} id The id of the element to be rendered
* @param {string} text The graph definition
* @param cb - Optional callback which
* @param {(svgCode: string, bindFunctions?: (element: Element) => void) => void} cb Callback which
* is called after rendering is finished with the svg code as inparam.
* @param {Element} container Selector to element in which a div with the graph temporarily will be
* inserted. If one is provided a hidden div will be inserted in the body of the page instead. The
* element will be removed when rendering is completed.
* @returns Returns the rendered element as a string containing the SVG definition.
* @returns {void}
*/
const render = function (
id: string,
text: string,
cb?: (svgCode: string, bindFunctions?: (element: Element) => void) => void,
cb: (svgCode: string, bindFunctions?: (element: Element) => void) => void,
container?: Element
): string {
): void {
addDiagrams();
configApi.reset();
text = text.replace(/\r\n?/g, '\n'); // parser problems on CRLF ignore all CR and leave LF;;
@@ -401,9 +401,9 @@ const render = function (
const renderAsync = async function (
id: string,
text: string,
cb?: (svgCode: string, bindFunctions?: (element: Element) => void) => void,
cb: (svgCode: string, bindFunctions?: (element: Element) => void) => void,
container?: Element
): Promise<string> {
): Promise<void> {
addDiagrams();
configApi.reset();
text = text.replace(/\r\n?/g, '\n'); // parser problems on CRLF ignore all CR and leave LF;;
@@ -741,13 +741,12 @@ const handleDirective = function (p: any, directive: any, type: string): void {
};
/** @param {MermaidConfig} options */
function initialize(options: MermaidConfig = {}) {
function initialize(options: MermaidConfig) {
// Handle legacy location of font-family configuration
if (options.fontFamily) {
if (!options.themeVariables) {
options.themeVariables = {};
if (options?.fontFamily) {
if (!options.themeVariables?.fontFamily) {
options.themeVariables = { fontFamily: options.fontFamily };
}
options.themeVariables.fontFamily = options.fontFamily;
}
// Set default options

View File

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

View File

@@ -121,10 +121,7 @@ class Theme {
}
// Setup teh label color for the set
this.scaleLabelColor =
this.scaleLabelColor !== 'calculated' && this.scaleLabelColor
? this.scaleLabelColor
: this.labelTextColor;
this.scaleLabelColor = this.scaleLabelColor || (this.darkMode ? 'black' : this.labelTextColor);
for (let i = 0; i < this.THEME_COLOR_LIMIT; i++) {
this['cScaleLabel' + i] = this['cScaleLabel' + i] || this.scaleLabelColor;

View File

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