diff --git a/.eslintrc.json b/.eslintrc.json
index 1d052e22b..9d7eacecd 100644
--- a/.eslintrc.json
+++ b/.eslintrc.json
@@ -29,7 +29,8 @@
"jsdoc",
"json",
"@cspell",
- "lodash"
+ "lodash",
+ "unicorn"
],
"rules": {
"curly": "error",
@@ -63,7 +64,29 @@
}
],
"no-only-tests/no-only-tests": "error",
- "lodash/import-scope": ["error", "method"]
+ "lodash/import-scope": ["error", "method"],
+ "unicorn/better-regex": "error",
+ "unicorn/no-abusive-eslint-disable": "error",
+ "unicorn/no-array-push-push": "error",
+ "unicorn/no-for-loop": "error",
+ "unicorn/no-instanceof-array": "error",
+ "unicorn/no-typeof-undefined": "error",
+ "unicorn/no-unnecessary-await": "error",
+ "unicorn/no-unsafe-regex": "warn",
+ "unicorn/no-useless-promise-resolve-reject": "error",
+ "unicorn/prefer-array-find": "error",
+ "unicorn/prefer-array-flat-map": "error",
+ "unicorn/prefer-array-index-of": "error",
+ "unicorn/prefer-array-some": "error",
+ "unicorn/prefer-default-parameters": "error",
+ "unicorn/prefer-includes": "error",
+ "unicorn/prefer-negative-index": "error",
+ "unicorn/prefer-object-from-entries": "error",
+ "unicorn/prefer-string-starts-ends-with": "error",
+ "unicorn/prefer-string-trim-start-end": "error",
+ "unicorn/string-content": "error",
+ "unicorn/prefer-spread": "error",
+ "unicorn/no-lonely-if": "error"
},
"overrides": [
{
diff --git a/cSpell.json b/cSpell.json
index 03891165f..0a66bf8c8 100644
--- a/cSpell.json
+++ b/cSpell.json
@@ -15,6 +15,7 @@
"bisheng",
"brolin",
"brotli",
+ "classdef",
"codedoc",
"colour",
"cpettitt",
diff --git a/cypress/integration/rendering/gantt.spec.js b/cypress/integration/rendering/gantt.spec.js
index b75e682c6..325cca065 100644
--- a/cypress/integration/rendering/gantt.spec.js
+++ b/cypress/integration/rendering/gantt.spec.js
@@ -326,7 +326,7 @@ describe('Gantt diagram', () => {
);
cy.get('svg').should((svg) => {
const el = svg.get(0);
- const children = Array.from(el.children);
+ const children = [...el.children];
const titleEl = children.find(function (node) {
return node.tagName === 'title';
diff --git a/cypress/integration/rendering/requirement.spec.js b/cypress/integration/rendering/requirement.spec.js
index be27f39fa..8a8d188ff 100644
--- a/cypress/integration/rendering/requirement.spec.js
+++ b/cypress/integration/rendering/requirement.spec.js
@@ -96,7 +96,7 @@ describe('Requirement diagram', () => {
);
cy.get('svg').should((svg) => {
const el = svg.get(0);
- const children = Array.from(el.children);
+ const children = [...el.children];
const titleEl = children.find(function (node) {
return node.tagName === 'title';
diff --git a/cypress/platform/viewer.js b/cypress/platform/viewer.js
index 1f02c578b..c06976e97 100644
--- a/cypress/platform/viewer.js
+++ b/cypress/platform/viewer.js
@@ -54,7 +54,7 @@ function merge(current, update) {
if (
current.hasOwnProperty(key) &&
typeof current[key] === 'object' &&
- !(current[key] instanceof Array)
+ !Array.isArray(current[key])
) {
merge(current[key], update[key]);
diff --git a/docs/config/setup/modules/config.md b/docs/config/setup/modules/config.md
index 993a7627b..8381dc8c7 100644
--- a/docs/config/setup/modules/config.md
+++ b/docs/config/setup/modules/config.md
@@ -36,7 +36,7 @@ Pushes in a directive to the configuration
#### Defined in
-[config.ts:193](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L193)
+[config.ts:191](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L191)
---
@@ -60,7 +60,7 @@ The currentConfig
#### Defined in
-[config.ts:138](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L138)
+[config.ts:137](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L137)
---
@@ -84,7 +84,7 @@ The siteConfig
#### Defined in
-[config.ts:97](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L97)
+[config.ts:96](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L96)
---
@@ -118,7 +118,7 @@ The siteConfig
#### Defined in
-[config.ts:225](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L225)
+[config.ts:223](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L223)
---
@@ -147,7 +147,7 @@ options in-place
#### Defined in
-[config.ts:153](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L153)
+[config.ts:152](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L152)
---
@@ -167,7 +167,7 @@ options in-place
#### Defined in
-[config.ts:76](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L76)
+[config.ts:75](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L75)
---
@@ -199,7 +199,7 @@ The currentConfig merged with the sanitized conf
#### Defined in
-[config.ts:114](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L114)
+[config.ts:113](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L113)
---
@@ -232,7 +232,7 @@ The new siteConfig
#### Defined in
-[config.ts:62](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L62)
+[config.ts:61](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L61)
---
@@ -273,4 +273,4 @@ The new siteConfig
#### Defined in
-[config.ts:80](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L80)
+[config.ts:79](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/config.ts#L79)
diff --git a/docs/config/setup/modules/mermaidAPI.md b/docs/config/setup/modules/mermaidAPI.md
index 0acfe4f97..d24369c3c 100644
--- a/docs/config/setup/modules/mermaidAPI.md
+++ b/docs/config/setup/modules/mermaidAPI.md
@@ -80,7 +80,7 @@ mermaid.initialize(config);
#### Defined in
-[mermaidAPI.ts:949](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L949)
+[mermaidAPI.ts:939](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L939)
## Functions
@@ -111,7 +111,7 @@ Return the last node appended
#### Defined in
-[mermaidAPI.ts:292](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L292)
+[mermaidAPI.ts:284](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L284)
---
@@ -137,7 +137,7 @@ the cleaned up svgCode
#### Defined in
-[mermaidAPI.ts:243](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L243)
+[mermaidAPI.ts:235](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L235)
---
@@ -163,7 +163,7 @@ the string with all the user styles
#### Defined in
-[mermaidAPI.ts:170](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L170)
+[mermaidAPI.ts:164](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L164)
---
@@ -186,7 +186,7 @@ the string with all the user styles
#### Defined in
-[mermaidAPI.ts:220](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L220)
+[mermaidAPI.ts:212](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L212)
---
@@ -213,7 +213,7 @@ with an enclosing block that has each of the cssClasses followed by !important;
#### Defined in
-[mermaidAPI.ts:154](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L154)
+[mermaidAPI.ts:148](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L148)
---
@@ -279,7 +279,7 @@ Put the svgCode into an iFrame. Return the iFrame code
#### Defined in
-[mermaidAPI.ts:271](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L271)
+[mermaidAPI.ts:263](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L263)
---
@@ -305,4 +305,4 @@ Remove any existing elements from the given document
#### Defined in
-[mermaidAPI.ts:343](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L343)
+[mermaidAPI.ts:335](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L335)
diff --git a/packages/mermaid-mindmap/src/mermaidUtils.ts b/packages/mermaid-mindmap/src/mermaidUtils.ts
index 7d8ac38bf..b575c201b 100644
--- a/packages/mermaid-mindmap/src/mermaidUtils.ts
+++ b/packages/mermaid-mindmap/src/mermaidUtils.ts
@@ -1,6 +1,7 @@
const warning = (s: string) => {
// Todo remove debug code
- console.error('Log function was called before initialization', s); // eslint-disable-line
+ // eslint-disable-next-line no-console
+ console.error('Log function was called before initialization', s);
};
export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
diff --git a/packages/mermaid/src/accessibility.js b/packages/mermaid/src/accessibility.js
index c59ba270c..4d4837fff 100644
--- a/packages/mermaid/src/accessibility.js
+++ b/packages/mermaid/src/accessibility.js
@@ -11,7 +11,7 @@
* @param id
*/
export default function addSVGAccessibilityFields(yy_parser, svg, id) {
- if (typeof svg.insert === 'undefined') {
+ if (svg.insert === undefined) {
return;
}
diff --git a/packages/mermaid/src/assignWithDepth.js b/packages/mermaid/src/assignWithDepth.js
index eff568d3e..898481c30 100644
--- a/packages/mermaid/src/assignWithDepth.js
+++ b/packages/mermaid/src/assignWithDepth.js
@@ -32,20 +32,20 @@ const assignWithDepth = function (dst, src, config) {
return dst;
} else if (Array.isArray(src) && Array.isArray(dst)) {
src.forEach((s) => {
- if (dst.indexOf(s) === -1) {
+ if (!dst.includes(s)) {
dst.push(s);
}
});
return dst;
}
- if (typeof dst === 'undefined' || depth <= 0) {
+ if (dst === undefined || depth <= 0) {
if (dst !== undefined && dst !== null && typeof dst === 'object' && typeof src === 'object') {
return Object.assign(dst, src);
} else {
return src;
}
}
- if (typeof src !== 'undefined' && typeof dst === 'object' && typeof src === 'object') {
+ if (src !== undefined && typeof dst === 'object' && typeof src === 'object') {
Object.keys(src).forEach((key) => {
if (
typeof src[key] === 'object' &&
diff --git a/packages/mermaid/src/config.ts b/packages/mermaid/src/config.ts
index 3ff946af2..8750c8fa5 100644
--- a/packages/mermaid/src/config.ts
+++ b/packages/mermaid/src/config.ts
@@ -18,8 +18,7 @@ export const updateCurrentConfig = (siteCfg: MermaidConfig, _directives: any[])
// Join directives
let sumOfDirectives: MermaidConfig = {};
- for (let i = 0; i < _directives.length; i++) {
- const d = _directives[i];
+ for (const d of _directives) {
sanitize(d);
// Apply the data from the directive where the the overrides the themeVariables
@@ -153,7 +152,7 @@ export const getConfig = (): MermaidConfig => {
export const sanitize = (options: any) => {
// Checking that options are not in the list of excluded options
['secure', ...(siteConfig.secure ?? [])].forEach((key) => {
- if (typeof options[key] !== 'undefined') {
+ if (options[key] !== undefined) {
// DO NOT attempt to print options[key] within `${}` as a malicious script
// can exploit the logger's attempt to stringify the value and execute arbitrary code
log.debug(`Denied attempt to modify a secure key ${key}`, options[key]);
@@ -170,14 +169,13 @@ export const sanitize = (options: any) => {
// Check that there no attempts of xss, there should be no tags at all in the directive
// blocking data urls as base64 urls can contain svg's with inline script tags
Object.keys(options).forEach((key) => {
- if (typeof options[key] === 'string') {
- if (
- options[key].indexOf('<') > -1 ||
- options[key].indexOf('>') > -1 ||
- options[key].indexOf('url(data:') > -1
- ) {
- delete options[key];
- }
+ if (
+ typeof options[key] === 'string' &&
+ (options[key].includes('<') ||
+ options[key].includes('>') ||
+ options[key].includes('url(data:'))
+ ) {
+ delete options[key];
}
if (typeof options[key] === 'object') {
sanitize(options[key]);
diff --git a/packages/mermaid/src/dagre-wrapper/createLabel.js b/packages/mermaid/src/dagre-wrapper/createLabel.js
index 9d7951798..af5032096 100644
--- a/packages/mermaid/src/dagre-wrapper/createLabel.js
+++ b/packages/mermaid/src/dagre-wrapper/createLabel.js
@@ -54,7 +54,7 @@ const createLabel = (_vertexText, style, isTitle, isNode) => {
const node = {
isNode,
label: decodeEntities(vertexText).replace(
- /fa[lrsb]?:fa-[\w-]+/g,
+ /fa[blrs]?:fa-[\w-]+/g,
(s) => ``
),
labelStyle: style.replace('fill:', 'color:'),
@@ -74,7 +74,7 @@ const createLabel = (_vertexText, style, isTitle, isNode) => {
rows = [];
}
- for (let j = 0; j < rows.length; j++) {
+ for (const row of rows) {
const tspan = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
tspan.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', 'preserve');
tspan.setAttribute('dy', '1em');
@@ -84,7 +84,7 @@ const createLabel = (_vertexText, style, isTitle, isNode) => {
} else {
tspan.setAttribute('class', 'row');
}
- tspan.textContent = rows[j].trim();
+ tspan.textContent = row.trim();
svgLabel.appendChild(tspan);
}
return svgLabel;
diff --git a/packages/mermaid/src/dagre-wrapper/edges.js b/packages/mermaid/src/dagre-wrapper/edges.js
index 4d23ca3ea..5213d0684 100644
--- a/packages/mermaid/src/dagre-wrapper/edges.js
+++ b/packages/mermaid/src/dagre-wrapper/edges.js
@@ -324,7 +324,7 @@ const cutPathAtIntersect = (_points, boundryNode) => {
pointPresent = pointPresent || (p.x === inter.x && p.y === inter.y);
});
// // if (!pointPresent) {
- if (!points.find((e) => e.x === inter.x && e.y === inter.y)) {
+ if (!points.some((e) => e.x === inter.x && e.y === inter.y)) {
points.push(inter);
} else {
log.warn('abc88 no intersect', inter, points);
diff --git a/packages/mermaid/src/dagre-wrapper/index.js b/packages/mermaid/src/dagre-wrapper/index.js
index 8b77c8520..e2d7d51f4 100644
--- a/packages/mermaid/src/dagre-wrapper/index.js
+++ b/packages/mermaid/src/dagre-wrapper/index.js
@@ -37,7 +37,7 @@ const recursiveRender = (_elem, graph, diagramtype, parentCluster) => {
// to the abstract node and is later used by dagre for the layout
graph.nodes().forEach(function (v) {
const node = graph.node(v);
- if (typeof parentCluster !== 'undefined') {
+ if (parentCluster !== undefined) {
const data = JSON.parse(JSON.stringify(parentCluster.clusterData));
// data.clusterPositioning = true;
log.info('Setting data for cluster XXX (', v, ') ', data, parentCluster);
diff --git a/packages/mermaid/src/dagre-wrapper/mermaid-graphlib.js b/packages/mermaid/src/dagre-wrapper/mermaid-graphlib.js
index 15fadc940..5722f7cc0 100644
--- a/packages/mermaid/src/dagre-wrapper/mermaid-graphlib.js
+++ b/packages/mermaid/src/dagre-wrapper/mermaid-graphlib.js
@@ -4,27 +4,20 @@ import * as graphlibJson from 'dagre-d3-es/src/graphlib/json';
import * as graphlib from 'dagre-d3-es/src/graphlib';
export let clusterDb = {};
-let decendants = {};
+let descendants = {};
let parents = {};
export const clear = () => {
- decendants = {};
+ descendants = {};
parents = {};
clusterDb = {};
};
-const isDecendant = (id, ancenstorId) => {
+const isDescendant = (id, ancenstorId) => {
// if (id === ancenstorId) return true;
- log.trace(
- 'In isDecendant',
- ancenstorId,
- ' ',
- id,
- ' = ',
- decendants[ancenstorId].indexOf(id) >= 0
- );
- if (decendants[ancenstorId].indexOf(id) >= 0) {
+ log.trace('In isDecendant', ancenstorId, ' ', id, ' = ', descendants[ancenstorId].includes(id));
+ if (descendants[ancenstorId].includes(id)) {
return true;
}
@@ -32,7 +25,7 @@ const isDecendant = (id, ancenstorId) => {
};
const edgeInCluster = (edge, clusterId) => {
- log.info('Decendants of ', clusterId, ' is ', decendants[clusterId]);
+ log.info('Decendants of ', clusterId, ' is ', descendants[clusterId]);
log.info('Edge is ', edge);
// Edges to/from the cluster is not in the cluster, they are in the parent
if (edge.v === clusterId) {
@@ -42,15 +35,15 @@ const edgeInCluster = (edge, clusterId) => {
return false;
}
- if (!decendants[clusterId]) {
+ if (!descendants[clusterId]) {
log.debug('Tilt, ', clusterId, ',not in decendants');
return false;
}
return (
- decendants[clusterId].indexOf(edge.v) >= 0 ||
- isDecendant(edge.v, clusterId) ||
- isDecendant(edge.w, clusterId) ||
- decendants[clusterId].indexOf(edge.w) >= 0
+ descendants[clusterId].includes(edge.v) ||
+ isDescendant(edge.v, clusterId) ||
+ isDescendant(edge.w, clusterId) ||
+ descendants[clusterId].includes(edge.w)
);
};
@@ -132,14 +125,14 @@ const copy = (clusterId, graph, newGraph, rootId) => {
graph.removeNode(node);
});
};
-export const extractDecendants = (id, graph) => {
+export const extractDescendants = (id, graph) => {
// log.debug('Extracting ', id);
const children = graph.children(id);
- let res = [].concat(children);
+ let res = [...children];
- for (let i = 0; i < children.length; i++) {
- parents[children[i]] = id;
- res = res.concat(extractDecendants(children[i], graph));
+ for (const child of children) {
+ parents[child] = id;
+ res = [...res, ...extractDescendants(child, graph)];
}
return res;
@@ -154,13 +147,13 @@ export const extractDecendants = (id, graph) => {
export const validate = (graph) => {
const edges = graph.edges();
log.trace('Edges: ', edges);
- for (let i = 0; i < edges.length; i++) {
- if (graph.children(edges[i].v).length > 0) {
- log.trace('The node ', edges[i].v, ' is part of and edge even though it has children');
+ for (const edge of edges) {
+ if (graph.children(edge.v).length > 0) {
+ log.trace('The node ', edge.v, ' is part of and edge even though it has children');
return false;
}
- if (graph.children(edges[i].w).length > 0) {
- log.trace('The node ', edges[i].w, ' is part of and edge even though it has children');
+ if (graph.children(edge.w).length > 0) {
+ log.trace('The node ', edge.w, ' is part of and edge even though it has children');
return false;
}
}
@@ -183,8 +176,8 @@ export const findNonClusterChild = (id, graph) => {
log.trace('This is a valid node', id);
return id;
}
- for (let i = 0; i < children.length; i++) {
- const _id = findNonClusterChild(children[i], graph);
+ for (const child of children) {
+ const _id = findNonClusterChild(child, graph);
if (_id) {
log.trace('Found replacement for', id, ' => ', _id);
return _id;
@@ -226,7 +219,7 @@ export const adjustClustersAndEdges = (graph, depth) => {
' Replacement id in edges: ',
findNonClusterChild(id, graph)
);
- decendants[id] = extractDecendants(id, graph);
+ descendants[id] = extractDescendants(id, graph);
clusterDb[id] = { id: findNonClusterChild(id, graph), clusterData: graph.node(id) };
}
});
@@ -236,7 +229,7 @@ export const adjustClustersAndEdges = (graph, depth) => {
const children = graph.children(id);
const edges = graph.edges();
if (children.length > 0) {
- log.debug('Cluster identified', id, decendants);
+ log.debug('Cluster identified', id, descendants);
edges.forEach((edge) => {
// log.debug('Edge, decendants: ', edge, decendants[id]);
@@ -245,19 +238,19 @@ export const adjustClustersAndEdges = (graph, depth) => {
// Any edge where either the one of the nodes is descending to the cluster but not the other
// if (decendants[id].indexOf(edge.v) < 0 && decendants[id].indexOf(edge.w) < 0) {
- const d1 = isDecendant(edge.v, id);
- const d2 = isDecendant(edge.w, id);
+ const d1 = isDescendant(edge.v, id);
+ const d2 = isDescendant(edge.w, id);
// d1 xor d2 - if either d1 is true and d2 is false or the other way around
if (d1 ^ d2) {
log.warn('Edge: ', edge, ' leaves cluster ', id);
- log.warn('Decendants of XXX ', id, ': ', decendants[id]);
+ log.warn('Decendants of XXX ', id, ': ', descendants[id]);
clusterDb[id].externalConnections = true;
}
}
});
} else {
- log.debug('Not a cluster ', id, decendants);
+ log.debug('Not a cluster ', id, descendants);
}
});
@@ -277,7 +270,7 @@ export const adjustClustersAndEdges = (graph, depth) => {
'ids:',
e.v,
e.w,
- 'Translateing: ',
+ 'Translating: ',
clusterDb[e.v],
' --- ',
clusterDb[e.w]
@@ -347,8 +340,7 @@ export const extractor = (graph, depth) => {
// for (let i = 0;)
let nodes = graph.nodes();
let hasChildren = false;
- for (let i = 0; i < nodes.length; i++) {
- const node = nodes[i];
+ for (const node of nodes) {
const children = graph.children(node);
hasChildren = hasChildren || children.length > 0;
}
@@ -360,9 +352,7 @@ export const extractor = (graph, depth) => {
// const clusters = Object.keys(clusterDb);
// clusters.forEach(clusterId => {
log.debug('Nodes = ', nodes, depth);
- for (let i = 0; i < nodes.length; i++) {
- const node = nodes[i];
-
+ for (const node of nodes) {
log.debug(
'Extracting node',
node,
@@ -394,11 +384,9 @@ export const extractor = (graph, depth) => {
const graphSettings = graph.graph();
let dir = graphSettings.rankdir === 'TB' ? 'LR' : 'TB';
- if (clusterDb[node]) {
- if (clusterDb[node].clusterData && clusterDb[node].clusterData.dir) {
- dir = clusterDb[node].clusterData.dir;
- log.warn('Fixing dir', clusterDb[node].clusterData.dir, dir);
- }
+ if (clusterDb[node] && clusterDb[node].clusterData && clusterDb[node].clusterData.dir) {
+ dir = clusterDb[node].clusterData.dir;
+ log.warn('Fixing dir', clusterDb[node].clusterData.dir, dir);
}
const clusterGraph = new graphlib.Graph({
@@ -446,8 +434,7 @@ export const extractor = (graph, depth) => {
nodes = graph.nodes();
log.warn('New list of nodes', nodes);
- for (let i = 0; i < nodes.length; i++) {
- const node = nodes[i];
+ for (const node of nodes) {
const data = graph.node(node);
log.warn(' Now next level', node, data);
if (data.clusterNode) {
@@ -464,7 +451,7 @@ const sorter = (graph, nodes) => {
nodes.forEach((node) => {
const children = graph.children(node);
const sorted = sorter(graph, children);
- result = result.concat(sorted);
+ result = [...result, ...sorted];
});
return result;
diff --git a/packages/mermaid/src/dagre-wrapper/mermaid-graphlib.spec.js b/packages/mermaid/src/dagre-wrapper/mermaid-graphlib.spec.js
index 49b022f4d..f594e3430 100644
--- a/packages/mermaid/src/dagre-wrapper/mermaid-graphlib.spec.js
+++ b/packages/mermaid/src/dagre-wrapper/mermaid-graphlib.spec.js
@@ -3,7 +3,7 @@ import * as graphlib from 'dagre-d3-es/src/graphlib';
import {
validate,
adjustClustersAndEdges,
- extractDecendants,
+ extractDescendants,
sortNodesByHierarchy,
} from './mermaid-graphlib';
import { setLogLevel, log } from '../logger';
@@ -400,7 +400,7 @@ flowchart TB
expect(aGraph.parent('B')).toBe(undefined);
});
});
-describe('extractDecendants', function () {
+describe('extractDescendants', function () {
let g;
beforeEach(function () {
setLogLevel(1);
@@ -443,9 +443,9 @@ describe('extractDecendants', function () {
g.setEdge('A', 'C', { data: 'link2' }, '2');
// log.info(g.edges())
- const d1 = extractDecendants('A', g);
- const d2 = extractDecendants('B', g);
- const d3 = extractDecendants('C', g);
+ const d1 = extractDescendants('A', g);
+ const d2 = extractDescendants('B', g);
+ const d3 = extractDescendants('C', g);
expect(d1).toEqual(['a']);
expect(d2).toEqual(['b']);
diff --git a/packages/mermaid/src/dagre-wrapper/nodes.js b/packages/mermaid/src/dagre-wrapper/nodes.js
index 316432b95..fda789323 100644
--- a/packages/mermaid/src/dagre-wrapper/nodes.js
+++ b/packages/mermaid/src/dagre-wrapper/nodes.js
@@ -391,12 +391,10 @@ const labelRect = (parent, node) => {
function applyNodePropertyBorders(rect, borders, totalWidth, totalHeight) {
const strokeDashArray = [];
const addBorder = (length) => {
- strokeDashArray.push(length);
- strokeDashArray.push(0);
+ strokeDashArray.push(length, 0);
};
const skipBorder = (length) => {
- strokeDashArray.push(0);
- strokeDashArray.push(length);
+ strokeDashArray.push(0, length);
};
if (borders.includes('t')) {
log.debug('add top border');
diff --git a/packages/mermaid/src/dagre-wrapper/shapes/util.js b/packages/mermaid/src/dagre-wrapper/shapes/util.js
index dfd1a93ba..6de0da638 100644
--- a/packages/mermaid/src/dagre-wrapper/shapes/util.js
+++ b/packages/mermaid/src/dagre-wrapper/shapes/util.js
@@ -21,7 +21,7 @@ export const labelHelper = (parent, node, _classes, isNode) => {
// Replace labelText with default value if undefined
let labelText;
- if (typeof node.labelText === 'undefined') {
+ if (node.labelText === undefined) {
labelText = '';
} else {
labelText = typeof node.labelText === 'string' ? node.labelText : node.labelText[0];
diff --git a/packages/mermaid/src/diagram-api/detectType.ts b/packages/mermaid/src/diagram-api/detectType.ts
index 6f9857221..2ff0b5532 100644
--- a/packages/mermaid/src/diagram-api/detectType.ts
+++ b/packages/mermaid/src/diagram-api/detectType.ts
@@ -3,8 +3,7 @@ import { log } from '../logger';
import { DetectorRecord, DiagramDetector, DiagramLoader } from './types';
import { frontMatterRegex } from './frontmatter';
-const directive =
- /[%]{2}[{]\s*(?:(?:(\w+)\s*:|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi;
+const directive = /%{2}{\s*(?:(\w+)\s*:|(\w+))\s*(?:(\w+)|((?:(?!}%{2}).|\r?\n)*))?\s*(?:}%{2})?/gi;
const anyComment = /\s*%%.*\n/gm;
const detectors: Record = {};
diff --git a/packages/mermaid/src/diagram-api/frontmatter.ts b/packages/mermaid/src/diagram-api/frontmatter.ts
index 800e7399b..d6811388c 100644
--- a/packages/mermaid/src/diagram-api/frontmatter.ts
+++ b/packages/mermaid/src/diagram-api/frontmatter.ts
@@ -7,7 +7,7 @@ import * as yaml from 'js-yaml';
// Note that JS doesn't support the "\A" anchor, which means we can't use
// multiline mode.
// Relevant YAML spec: https://yaml.org/spec/1.2.2/#914-explicit-documents
-export const frontMatterRegex = /^(?:---\s*[\r\n])(.*?)(?:[\r\n]---\s*[\r\n]+)/s;
+export const frontMatterRegex = /^-{3}\s*[\n\r](.*?)[\n\r]-{3}\s*[\n\r]+/s;
type FrontMatterMetadata = {
title?: string;
diff --git a/packages/mermaid/src/diagrams/c4/c4Renderer.js b/packages/mermaid/src/diagrams/c4/c4Renderer.js
index a9072346a..6490a8e19 100644
--- a/packages/mermaid/src/diagrams/c4/c4Renderer.js
+++ b/packages/mermaid/src/diagrams/c4/c4Renderer.js
@@ -48,7 +48,7 @@ class Bounds {
}
updateVal(obj, key, val, fun) {
- if (typeof obj[key] === 'undefined') {
+ if (obj[key] === undefined) {
obj[key] = val;
} else {
obj[key] = fun(val, obj[key]);
@@ -177,12 +177,12 @@ function calcC4ShapeTextWH(textType, c4Shape, c4ShapeTextWrap, textConf, textLim
let lineHeight = 0;
c4Shape[textType].height = 0;
c4Shape[textType].width = 0;
- for (let i = 0; i < lines.length; i++) {
+ for (const line of lines) {
c4Shape[textType].width = Math.max(
- calculateTextWidth(lines[i], textConf),
+ calculateTextWidth(line, textConf),
c4Shape[textType].width
);
- lineHeight = calculateTextHeight(lines[i], textConf);
+ lineHeight = calculateTextHeight(line, textConf);
c4Shape[textType].height = c4Shape[textType].height + lineHeight;
}
// c4Shapes[textType].height = c4Shapes[textType].textLines * textConf.fontSize;
@@ -212,9 +212,9 @@ export const drawC4ShapeArray = function (currentBounds, diagram, c4ShapeArray,
// Upper Y is relative point
let Y = 0;
// Draw the c4ShapeArray
- for (let i = 0; i < c4ShapeKeys.length; i++) {
+ for (const c4ShapeKey of c4ShapeKeys) {
Y = 0;
- const c4Shape = c4ShapeArray[c4ShapeKeys[i]];
+ const c4Shape = c4ShapeArray[c4ShapeKey];
// calc c4 shape type width and height
@@ -461,8 +461,7 @@ function drawInsideBoundary(
// conf.width * conf.c4ShapeInRow + conf.c4ShapeMargin * conf.c4ShapeInRow * 2,
// parentBounds.data.widthLimit / Math.min(conf.c4BoundaryInRow, currentBoundaries.length)
// );
- for (let i = 0; i < currentBoundaries.length; i++) {
- let currentBoundary = currentBoundaries[i];
+ for (let [i, currentBoundary] of currentBoundaries.entries()) {
let Y = 0;
currentBoundary.image = { width: 0, height: 0, Y: 0 };
if (currentBoundary.sprite) {
diff --git a/packages/mermaid/src/diagrams/c4/svgDraw.js b/packages/mermaid/src/diagrams/c4/svgDraw.js
index 437a24bcb..d9727f074 100644
--- a/packages/mermaid/src/diagrams/c4/svgDraw.js
+++ b/packages/mermaid/src/diagrams/c4/svgDraw.js
@@ -52,8 +52,8 @@ export const drawText = function (elem, textData) {
let dy = 0;
let yfunc = () => textData.y;
if (
- typeof textData.valign !== 'undefined' &&
- typeof textData.textMargin !== 'undefined' &&
+ textData.valign !== undefined &&
+ textData.textMargin !== undefined &&
textData.textMargin > 0
) {
switch (textData.valign) {
@@ -78,9 +78,9 @@ export const drawText = function (elem, textData) {
}
}
if (
- typeof textData.anchor !== 'undefined' &&
- typeof textData.textMargin !== 'undefined' &&
- typeof textData.width !== 'undefined'
+ textData.anchor !== undefined &&
+ textData.textMargin !== undefined &&
+ textData.width !== undefined
) {
switch (textData.anchor) {
case 'left':
@@ -106,12 +106,11 @@ export const drawText = function (elem, textData) {
break;
}
}
- for (let i = 0; i < lines.length; i++) {
- let line = lines[i];
+ for (let [i, line] of lines.entries()) {
if (
- typeof textData.textMargin !== 'undefined' &&
+ textData.textMargin !== undefined &&
textData.textMargin === 0 &&
- typeof textData.fontSize !== 'undefined'
+ textData.fontSize !== undefined
) {
dy = i * textData.fontSize;
}
@@ -119,28 +118,28 @@ export const drawText = function (elem, textData) {
const textElem = elem.append('text');
textElem.attr('x', textData.x);
textElem.attr('y', yfunc());
- if (typeof textData.anchor !== 'undefined') {
+ if (textData.anchor !== undefined) {
textElem
.attr('text-anchor', textData.anchor)
.attr('dominant-baseline', textData.dominantBaseline)
.attr('alignment-baseline', textData.alignmentBaseline);
}
- if (typeof textData.fontFamily !== 'undefined') {
+ if (textData.fontFamily !== undefined) {
textElem.style('font-family', textData.fontFamily);
}
- if (typeof textData.fontSize !== 'undefined') {
+ if (textData.fontSize !== undefined) {
textElem.style('font-size', textData.fontSize);
}
- if (typeof textData.fontWeight !== 'undefined') {
+ if (textData.fontWeight !== undefined) {
textElem.style('font-weight', textData.fontWeight);
}
- if (typeof textData.fill !== 'undefined') {
+ if (textData.fill !== undefined) {
textElem.attr('fill', textData.fill);
}
- if (typeof textData.class !== 'undefined') {
+ if (textData.class !== undefined) {
textElem.attr('class', textData.class);
}
- if (typeof textData.dy !== 'undefined') {
+ if (textData.dy !== undefined) {
textElem.attr('dy', textData.dy);
} else if (dy !== 0) {
textElem.attr('dy', dy);
@@ -149,7 +148,7 @@ export const drawText = function (elem, textData) {
if (textData.tspan) {
const span = textElem.append('tspan');
span.attr('x', textData.x);
- if (typeof textData.fill !== 'undefined') {
+ if (textData.fill !== undefined) {
span.attr('fill', textData.fill);
}
span.text(line);
@@ -157,8 +156,8 @@ export const drawText = function (elem, textData) {
textElem.text(line);
}
if (
- typeof textData.valign !== 'undefined' &&
- typeof textData.textMargin !== 'undefined' &&
+ textData.valign !== undefined &&
+ textData.textMargin !== undefined &&
textData.textMargin > 0
) {
textHeight += (textElem._groups || textElem)[0][0].getBBox().height;
diff --git a/packages/mermaid/src/diagrams/class/classDb.js b/packages/mermaid/src/diagrams/class/classDb.js
index 9830c059e..2c6690e39 100644
--- a/packages/mermaid/src/diagrams/class/classDb.js
+++ b/packages/mermaid/src/diagrams/class/classDb.js
@@ -52,7 +52,7 @@ const splitClassNameAndType = function (id) {
export const addClass = function (id) {
let classId = splitClassNameAndType(id);
// Only add class if not exists
- if (typeof classes[classId.className] !== 'undefined') {
+ if (classes[classId.className] !== undefined) {
return;
}
@@ -77,9 +77,9 @@ export const addClass = function (id) {
*/
export const lookUpDomId = function (id) {
const classKeys = Object.keys(classes);
- for (let i = 0; i < classKeys.length; i++) {
- if (classes[classKeys[i]].id === id) {
- return classes[classKeys[i]].domId;
+ for (const classKey of classKeys) {
+ if (classes[classKey].id === id) {
+ return classes[classKey].domId;
}
}
};
@@ -207,7 +207,7 @@ export const setCssClass = function (ids, className) {
if (_id[0].match(/\d/)) {
id = MERMAID_DOM_ID_PREFIX + id;
}
- if (typeof classes[id] !== 'undefined') {
+ if (classes[id] !== undefined) {
classes[id].cssClasses.push(className);
}
});
@@ -222,7 +222,7 @@ export const setCssClass = function (ids, className) {
const setTooltip = function (ids, tooltip) {
const config = configApi.getConfig();
ids.split(',').forEach(function (id) {
- if (typeof tooltip !== 'undefined') {
+ if (tooltip !== undefined) {
classes[id].tooltip = common.sanitizeText(tooltip, config);
}
});
@@ -244,7 +244,7 @@ export const setLink = function (ids, linkStr, target) {
if (_id[0].match(/\d/)) {
id = MERMAID_DOM_ID_PREFIX + id;
}
- if (typeof classes[id] !== 'undefined') {
+ if (classes[id] !== undefined) {
classes[id].link = utils.formatUrl(linkStr, config);
if (config.securityLevel === 'sandbox') {
classes[id].linkTarget = '_top';
@@ -281,10 +281,10 @@ const setClickFunc = function (domId, functionName, functionArgs) {
if (config.securityLevel !== 'loose') {
return;
}
- if (typeof functionName === 'undefined') {
+ if (functionName === undefined) {
return;
}
- if (typeof classes[id] !== 'undefined') {
+ if (classes[id] !== undefined) {
let argList = [];
if (typeof functionArgs === 'string') {
/* Splits functionArgs by ',', ignoring all ',' in double quoted strings */
diff --git a/packages/mermaid/src/diagrams/class/classRenderer-v2.js b/packages/mermaid/src/diagrams/class/classRenderer-v2.js
index 905e6ee2f..c4e7e0291 100644
--- a/packages/mermaid/src/diagrams/class/classRenderer-v2.js
+++ b/packages/mermaid/src/diagrams/class/classRenderer-v2.js
@@ -10,8 +10,6 @@ import { setupGraphViewbox } from '../../setupGraphViewbox';
import common from '../common/common';
import addSVGAccessibilityFields from '../../accessibility';
-let idCache = {};
-
const sanitizeText = (txt) => common.sanitizeText(txt, getConfig());
let conf = {
@@ -275,16 +273,16 @@ export const addRelations = function (relations, g) {
let style = '';
let labelStyle = '';
- if (typeof edge.style !== 'undefined') {
+ if (edge.style !== undefined) {
const styles = getStylesFromArray(edge.style);
style = styles.style;
labelStyle = styles.labelStyle;
} else {
style = 'fill:none';
- if (typeof defaultStyle !== 'undefined') {
+ if (defaultStyle !== undefined) {
style = defaultStyle;
}
- if (typeof defaultLabelStyle !== 'undefined') {
+ if (defaultLabelStyle !== undefined) {
labelStyle = defaultLabelStyle;
}
}
@@ -292,17 +290,17 @@ export const addRelations = function (relations, g) {
edgeData.style = style;
edgeData.labelStyle = labelStyle;
- if (typeof edge.interpolate !== 'undefined') {
+ if (edge.interpolate !== undefined) {
edgeData.curve = interpolateToCurve(edge.interpolate, curveLinear);
- } else if (typeof relations.defaultInterpolate !== 'undefined') {
+ } else if (relations.defaultInterpolate !== undefined) {
edgeData.curve = interpolateToCurve(relations.defaultInterpolate, curveLinear);
} else {
edgeData.curve = interpolateToCurve(conf.curve, curveLinear);
}
edge.text = edge.title;
- if (typeof edge.text === 'undefined') {
- if (typeof edge.style !== 'undefined') {
+ if (edge.text === undefined) {
+ if (edge.style !== undefined) {
edgeData.arrowheadStyle = 'fill: #333';
}
} else {
@@ -316,7 +314,7 @@ export const addRelations = function (relations, g) {
edgeData.labelType = 'text';
edgeData.label = edge.text.replace(common.lineBreakRegex, '\n');
- if (typeof edge.style === 'undefined') {
+ if (edge.style === undefined) {
edgeData.style = edgeData.style || 'stroke: #333; stroke-width: 1.5px;fill:none';
}
@@ -438,9 +436,7 @@ export const draw = function (text, id, _version, diagObj) {
if (!conf.htmlLabels) {
const doc = securityLevel === 'sandbox' ? sandboxElement.nodes()[0].contentDocument : document;
const labels = doc.querySelectorAll('[id="' + id + '"] .edgeLabel .label');
- for (let k = 0; k < labels.length; k++) {
- const label = labels[k];
-
+ for (const label of labels) {
// Get dimensions of label
const dim = label.getBBox();
diff --git a/packages/mermaid/src/diagrams/class/classRenderer.js b/packages/mermaid/src/diagrams/class/classRenderer.js
index 74e2a48c2..c500a73a7 100644
--- a/packages/mermaid/src/diagrams/class/classRenderer.js
+++ b/packages/mermaid/src/diagrams/class/classRenderer.js
@@ -180,8 +180,8 @@ export const draw = function (text, id, _version, diagObj) {
const classes = diagObj.db.getClasses();
const keys = Object.keys(classes);
- for (let i = 0; i < keys.length; i++) {
- const classDef = classes[keys[i]];
+ for (const key of keys) {
+ const classDef = classes[key];
const node = svgDraw.drawClass(diagram, classDef, conf, diagObj);
idCache[node.id] = node;
@@ -240,7 +240,7 @@ export const draw = function (text, id, _version, diagObj) {
dagreLayout(g);
g.nodes().forEach(function (v) {
- if (typeof v !== 'undefined' && typeof g.node(v) !== 'undefined') {
+ if (v !== undefined && g.node(v) !== undefined) {
log.debug('Node ' + v + ': ' + JSON.stringify(g.node(v)));
root
.select('#' + (diagObj.db.lookUpDomId(v) || v))
@@ -256,7 +256,7 @@ export const draw = function (text, id, _version, diagObj) {
});
g.edges().forEach(function (e) {
- if (typeof e !== 'undefined' && typeof g.edge(e) !== 'undefined') {
+ if (e !== undefined && g.edge(e) !== undefined) {
log.debug('Edge ' + e.v + ' -> ' + e.w + ': ' + JSON.stringify(g.edge(e)));
svgDraw.drawEdge(diagram, g.edge(e), g.edge(e).relation, conf, diagObj);
}
diff --git a/packages/mermaid/src/diagrams/class/svgDraw.js b/packages/mermaid/src/diagrams/class/svgDraw.js
index 35f793460..cc6909280 100644
--- a/packages/mermaid/src/diagrams/class/svgDraw.js
+++ b/packages/mermaid/src/diagrams/class/svgDraw.js
@@ -102,7 +102,7 @@ export const drawEdge = function (elem, path, relation, conf, diagObj) {
p2_card_y = cardinality_2_point.y;
}
- if (typeof relation.title !== 'undefined') {
+ if (relation.title !== undefined) {
const g = elem.append('g').attr('class', 'classLabel');
const label = g
.append('text')
@@ -125,7 +125,7 @@ export const drawEdge = function (elem, path, relation, conf, diagObj) {
}
log.info('Rendering relation ' + JSON.stringify(relation));
- if (typeof relation.relationTitle1 !== 'undefined' && relation.relationTitle1 !== 'none') {
+ if (relation.relationTitle1 !== undefined && relation.relationTitle1 !== 'none') {
const g = elem.append('g').attr('class', 'cardinality');
g.append('text')
.attr('class', 'type1')
@@ -135,7 +135,7 @@ export const drawEdge = function (elem, path, relation, conf, diagObj) {
.attr('font-size', '6')
.text(relation.relationTitle1);
}
- if (typeof relation.relationTitle2 !== 'undefined' && relation.relationTitle2 !== 'none') {
+ if (relation.relationTitle2 !== undefined && relation.relationTitle2 !== 'none') {
const g = elem.append('g').attr('class', 'cardinality');
g.append('text')
.attr('class', 'type2')
@@ -355,8 +355,8 @@ export const drawNote = function (elem, note, conf, diagObj) {
};
export const parseMember = function (text) {
- const fieldRegEx = /^(\+|-|~|#)?(\w+)(~\w+~|\[\])?\s+(\w+) *(\*|\$)?$/;
- const methodRegEx = /^([+|\-|~|#])?(\w+) *\( *(.*)\) *(\*|\$)? *(\w*[~|[\]]*\s*\w*~?)$/;
+ const fieldRegEx = /^([#+~-])?(\w+)(~\w+~|\[])?\s+(\w+) *([$*])?$/;
+ const methodRegEx = /^([#+|~-])?(\w+) *\( *(.*)\) *([$*])? *(\w*[[\]|~]*\s*\w*~?)$/;
let fieldMatch = text.match(fieldRegEx);
let methodMatch = text.match(methodRegEx);
@@ -420,7 +420,6 @@ const buildLegacyDisplay = function (text) {
// if for some reason we don't have any match, use old format to parse text
let displayText = '';
let cssStyle = '';
- let memberText = '';
let returnType = '';
let methodStart = text.indexOf('(');
let methodEnd = text.indexOf(')');
@@ -433,7 +432,7 @@ const buildLegacyDisplay = function (text) {
if (firstChar.match(/\w/)) {
methodName = text.substring(0, methodStart).trim();
} else {
- if (firstChar.match(/\+|-|~|#/)) {
+ if (firstChar.match(/[#+~-]/)) {
visibility = firstChar;
}
diff --git a/packages/mermaid/src/diagrams/common/common.ts b/packages/mermaid/src/diagrams/common/common.ts
index 782915cc1..194a9a4c0 100644
--- a/packages/mermaid/src/diagrams/common/common.ts
+++ b/packages/mermaid/src/diagrams/common/common.ts
@@ -152,7 +152,7 @@ export const evaluate = (val?: string | boolean): boolean =>
export const parseGenericTypes = function (text: string): string {
let cleanedText = text;
- if (text.indexOf('~') !== -1) {
+ if (text.includes('~')) {
cleanedText = cleanedText.replace(/~([^~].*)/, '<$1');
cleanedText = cleanedText.replace(/~([^~]*)$/, '>$1');
diff --git a/packages/mermaid/src/diagrams/er/erDb.js b/packages/mermaid/src/diagrams/er/erDb.js
index 96b60836b..026e08420 100644
--- a/packages/mermaid/src/diagrams/er/erDb.js
+++ b/packages/mermaid/src/diagrams/er/erDb.js
@@ -32,7 +32,7 @@ export const parseDirective = function (statement, context, type) {
};
const addEntity = function (name) {
- if (typeof entities[name] === 'undefined') {
+ if (entities[name] === undefined) {
entities[name] = { attributes: [] };
log.info('Added new entity :', name);
}
diff --git a/packages/mermaid/src/diagrams/er/erRenderer.js b/packages/mermaid/src/diagrams/er/erRenderer.js
index 36267f415..101beebb9 100644
--- a/packages/mermaid/src/diagrams/er/erRenderer.js
+++ b/packages/mermaid/src/diagrams/er/erRenderer.js
@@ -11,7 +11,7 @@ import { parseGenericTypes } from '../common/common';
import { v4 as uuid4 } from 'uuid';
/** Regex used to remove chars from the entity name so the result can be used in an id */
-const BAD_ID_CHARS_REGEXP = /[^A-Za-z0-9]([\W])*/g;
+const BAD_ID_CHARS_REGEXP = /[^\dA-Za-z](\W)*/g;
// Configuration
let conf = {};
@@ -28,8 +28,8 @@ let entityNameIds = new Map();
*/
export const setConf = function (cnf) {
const keys = Object.keys(cnf);
- for (let i = 0; i < keys.length; i++) {
- conf[keys[i]] = cnf[keys[i]];
+ for (const key of keys) {
+ conf[key] = cnf[key];
}
};
@@ -356,7 +356,7 @@ const drawEntities = function (svgNode, entities, graph) {
const adjustEntities = function (svgNode, graph) {
graph.nodes().forEach(function (v) {
- if (typeof v !== 'undefined' && typeof graph.node(v) !== 'undefined') {
+ if (v !== undefined && graph.node(v) !== undefined) {
svgNode
.select('#' + v)
.attr(
@@ -387,7 +387,7 @@ const getEdgeName = function (rel) {
* Add each relationship to the graph
*
* @param relationships The relationships to be added
- * @param {Graph} g The graph
+ * @param g The graph
* @returns {Array} The array of relationships
*/
const addRelationships = function (relationships, g) {
@@ -652,10 +652,8 @@ export const draw = function (text, id, _version, diagObj) {
* Although the official XML standard for ids says that many more characters are valid in the id,
* this keeps things simple by accepting only A-Za-z0-9.
*
- * @param {string} [str?=''] Given string to use as the basis for the id. Default is `''`
- * @param {string} [prefix?=''] String to put at the start, followed by '-'. Default is `''`
- * @param str
- * @param prefix
+ * @param {string} str Given string to use as the basis for the id. Default is `''`
+ * @param {string} prefix String to put at the start, followed by '-'. Default is `''`
* @returns {string}
* @see https://www.w3.org/TR/xml/#NT-Name
*/
diff --git a/packages/mermaid/src/diagrams/flowchart/flowDb.js b/packages/mermaid/src/diagrams/flowchart/flowDb.js
index 38754c667..9181ab9cc 100644
--- a/packages/mermaid/src/diagrams/flowchart/flowDb.js
+++ b/packages/mermaid/src/diagrams/flowchart/flowDb.js
@@ -46,9 +46,9 @@ export const parseDirective = function (statement, context, type) {
*/
export const lookUpDomId = function (id) {
const veritceKeys = Object.keys(vertices);
- for (let i = 0; i < veritceKeys.length; i++) {
- if (vertices[veritceKeys[i]].id === id) {
- return vertices[veritceKeys[i]].domId;
+ for (const veritceKey of veritceKeys) {
+ if (vertices[veritceKey].id === id) {
+ return vertices[veritceKey].domId;
}
}
return id;
@@ -68,7 +68,7 @@ export const lookUpDomId = function (id) {
export const addVertex = function (_id, text, type, style, classes, dir, props = {}) {
let txt;
let id = _id;
- if (typeof id === 'undefined') {
+ if (id === undefined) {
return;
}
if (id.trim().length === 0) {
@@ -77,7 +77,7 @@ export const addVertex = function (_id, text, type, style, classes, dir, props =
// if (id[0].match(/\d/)) id = MERMAID_DOM_ID_PREFIX + id;
- if (typeof vertices[id] === 'undefined') {
+ if (vertices[id] === undefined) {
vertices[id] = {
id: id,
domId: MERMAID_DOM_ID_PREFIX + id + '-' + vertexCounter,
@@ -86,7 +86,7 @@ export const addVertex = function (_id, text, type, style, classes, dir, props =
};
}
vertexCounter++;
- if (typeof text !== 'undefined') {
+ if (text !== undefined) {
config = configApi.getConfig();
txt = sanitizeText(text.trim());
@@ -97,33 +97,29 @@ export const addVertex = function (_id, text, type, style, classes, dir, props =
vertices[id].text = txt;
} else {
- if (typeof vertices[id].text === 'undefined') {
+ if (vertices[id].text === undefined) {
vertices[id].text = _id;
}
}
- if (typeof type !== 'undefined') {
+ if (type !== undefined) {
vertices[id].type = type;
}
- if (typeof style !== 'undefined') {
- if (style !== null) {
- style.forEach(function (s) {
- vertices[id].styles.push(s);
- });
- }
+ if (style !== undefined && style !== null) {
+ style.forEach(function (s) {
+ vertices[id].styles.push(s);
+ });
}
- if (typeof classes !== 'undefined') {
- if (classes !== null) {
- classes.forEach(function (s) {
- vertices[id].classes.push(s);
- });
- }
+ if (classes !== undefined && classes !== null) {
+ classes.forEach(function (s) {
+ vertices[id].classes.push(s);
+ });
}
- if (typeof dir !== 'undefined') {
+ if (dir !== undefined) {
vertices[id].dir = dir;
}
- if (typeof vertices[id].props === 'undefined') {
+ if (vertices[id].props === undefined) {
vertices[id].props = props;
- } else if (typeof props !== 'undefined') {
+ } else if (props !== undefined) {
Object.assign(vertices[id].props, props);
}
};
@@ -134,9 +130,9 @@ export const addVertex = function (_id, text, type, style, classes, dir, props =
* @param _start
* @param _end
* @param type
- * @param linktext
+ * @param linkText
*/
-export const addSingleLink = function (_start, _end, type, linktext) {
+export const addSingleLink = function (_start, _end, type, linkText) {
let start = _start;
let end = _end;
// if (start[0].match(/\d/)) start = MERMAID_DOM_ID_PREFIX + start;
@@ -144,18 +140,18 @@ export const addSingleLink = function (_start, _end, type, linktext) {
// log.info('Got edge...', start, end);
const edge = { start: start, end: end, type: undefined, text: '' };
- linktext = type.text;
+ linkText = type.text;
- if (typeof linktext !== 'undefined') {
- edge.text = sanitizeText(linktext.trim());
+ if (linkText !== undefined) {
+ edge.text = sanitizeText(linkText.trim());
- // strip quotes if string starts and exnds with a quote
+ // strip quotes if string starts and ends with a quote
if (edge.text[0] === '"' && edge.text[edge.text.length - 1] === '"') {
edge.text = edge.text.substring(1, edge.text.length - 1);
}
}
- if (typeof type !== 'undefined') {
+ if (type !== undefined) {
edge.type = type.type;
edge.stroke = type.stroke;
edge.length = type.length;
@@ -207,21 +203,19 @@ export const updateLink = function (positions, style) {
};
export const addClass = function (id, style) {
- if (typeof classes[id] === 'undefined') {
+ if (classes[id] === undefined) {
classes[id] = { id: id, styles: [], textStyles: [] };
}
- if (typeof style !== 'undefined') {
- if (style !== null) {
- style.forEach(function (s) {
- if (s.match('color')) {
- const newStyle1 = s.replace('fill', 'bgFill');
- const newStyle2 = newStyle1.replace('color', 'fill');
- classes[id].textStyles.push(newStyle2);
- }
- classes[id].styles.push(s);
- });
- }
+ if (style !== undefined && style !== null) {
+ style.forEach(function (s) {
+ if (s.match('color')) {
+ const newStyle1 = s.replace('fill', 'bgFill');
+ const newStyle2 = newStyle1.replace('color', 'fill');
+ classes[id].textStyles.push(newStyle2);
+ }
+ classes[id].styles.push(s);
+ });
}
};
@@ -257,11 +251,11 @@ export const setClass = function (ids, className) {
// let id = version === 'gen-2' ? lookUpDomId(_id) : _id;
let id = _id;
// if (_id[0].match(/\d/)) id = MERMAID_DOM_ID_PREFIX + id;
- if (typeof vertices[id] !== 'undefined') {
+ if (vertices[id] !== undefined) {
vertices[id].classes.push(className);
}
- if (typeof subGraphLookup[id] !== 'undefined') {
+ if (subGraphLookup[id] !== undefined) {
subGraphLookup[id].classes.push(className);
}
});
@@ -269,7 +263,7 @@ export const setClass = function (ids, className) {
const setTooltip = function (ids, tooltip) {
ids.split(',').forEach(function (id) {
- if (typeof tooltip !== 'undefined') {
+ if (tooltip !== undefined) {
tooltips[version === 'gen-1' ? lookUpDomId(id) : id] = sanitizeText(tooltip);
}
});
@@ -281,7 +275,7 @@ const setClickFun = function (id, functionName, functionArgs) {
if (configApi.getConfig().securityLevel !== 'loose') {
return;
}
- if (typeof functionName === 'undefined') {
+ if (functionName === undefined) {
return;
}
let argList = [];
@@ -304,7 +298,7 @@ const setClickFun = function (id, functionName, functionArgs) {
argList.push(id);
}
- if (typeof vertices[id] !== 'undefined') {
+ if (vertices[id] !== undefined) {
vertices[id].haveCallback = true;
funs.push(function () {
const elem = document.querySelector(`[id="${domId}"]`);
@@ -330,7 +324,7 @@ const setClickFun = function (id, functionName, functionArgs) {
*/
export const setLink = function (ids, linkStr, target) {
ids.split(',').forEach(function (id) {
- if (typeof vertices[id] !== 'undefined') {
+ if (vertices[id] !== undefined) {
vertices[id].link = utils.formatUrl(linkStr, config);
vertices[id].linkTarget = target;
}
@@ -484,7 +478,7 @@ export const addSubGraph = function (_id, list, _title) {
if (type in prims) {
return prims[type].hasOwnProperty(item) ? false : (prims[type][item] = true);
} else {
- return objs.indexOf(item) >= 0 ? false : objs.push(item);
+ return objs.includes(item) ? false : objs.push(item);
}
});
return { nodeList, dir };
@@ -530,8 +524,8 @@ export const addSubGraph = function (_id, list, _title) {
};
const getPosForId = function (id) {
- for (let i = 0; i < subGraphs.length; i++) {
- if (subGraphs[i].id === id) {
+ for (const [i, subGraph] of subGraphs.entries()) {
+ if (subGraph.id === id) {
return i;
}
}
@@ -622,11 +616,11 @@ const destructStartLink = (_str) => {
let stroke = 'normal';
- if (str.indexOf('=') !== -1) {
+ if (str.includes('=')) {
stroke = 'thick';
}
- if (str.indexOf('.') !== -1) {
+ if (str.includes('.')) {
stroke = 'dotted';
}
diff --git a/packages/mermaid/src/diagrams/flowchart/flowRenderer-v2.js b/packages/mermaid/src/diagrams/flowchart/flowRenderer-v2.js
index fa1b692cf..be3fffa0c 100644
--- a/packages/mermaid/src/diagrams/flowchart/flowRenderer-v2.js
+++ b/packages/mermaid/src/diagrams/flowchart/flowRenderer-v2.js
@@ -16,8 +16,8 @@ import addSVGAccessibilityFields from '../../accessibility';
const conf = {};
export const setConf = function (cnf) {
const keys = Object.keys(cnf);
- for (let i = 0; i < keys.length; i++) {
- conf[keys[i]] = cnf[keys[i]];
+ for (const key of keys) {
+ conf[key] = cnf[key];
}
};
@@ -60,7 +60,7 @@ export const addVertices = function (vert, g, svgId, root, doc, diagObj) {
// TODO: addHtmlLabel accepts a labelStyle. Do we possibly have that?
const node = {
label: vertexText.replace(
- /fa[lrsb]?:fa-[\w-]+/g,
+ /fa[blrs]?:fa-[\w-]+/g,
(s) => ``
),
};
@@ -72,12 +72,12 @@ export const addVertices = function (vert, g, svgId, root, doc, diagObj) {
const rows = vertexText.split(common.lineBreakRegex);
- for (let j = 0; j < rows.length; j++) {
+ for (const row of rows) {
const tspan = doc.createElementNS('http://www.w3.org/2000/svg', 'tspan');
tspan.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', 'preserve');
tspan.setAttribute('dy', '1em');
tspan.setAttribute('x', '1');
- tspan.textContent = rows[j];
+ tspan.textContent = row;
svgLabel.appendChild(tspan);
}
vertexNode = svgLabel;
@@ -198,7 +198,7 @@ export const addEdges = function (edges, g, diagObj) {
let defaultStyle;
let defaultLabelStyle;
- if (typeof edges.defaultStyle !== 'undefined') {
+ if (edges.defaultStyle !== undefined) {
const defaultStyles = getStylesFromArray(edges.defaultStyle);
defaultStyle = defaultStyles.style;
defaultLabelStyle = defaultStyles.labelStyle;
@@ -210,7 +210,7 @@ export const addEdges = function (edges, g, diagObj) {
// Identify Link
var linkIdBase = 'L-' + edge.start + '-' + edge.end;
// count the links from+to the same node to give unique id
- if (typeof linkIdCnt[linkIdBase] === 'undefined') {
+ if (linkIdCnt[linkIdBase] === undefined) {
linkIdCnt[linkIdBase] = 0;
log.info('abc78 new entry', linkIdBase, linkIdCnt[linkIdBase]);
} else {
@@ -262,10 +262,10 @@ export const addEdges = function (edges, g, diagObj) {
switch (edge.stroke) {
case 'normal':
style = 'fill:none;';
- if (typeof defaultStyle !== 'undefined') {
+ if (defaultStyle !== undefined) {
style = defaultStyle;
}
- if (typeof defaultLabelStyle !== 'undefined') {
+ if (defaultLabelStyle !== undefined) {
labelStyle = defaultLabelStyle;
}
edgeData.thickness = 'normal';
@@ -282,7 +282,7 @@ export const addEdges = function (edges, g, diagObj) {
edgeData.style = 'stroke-width: 3.5px;fill:none;';
break;
}
- if (typeof edge.style !== 'undefined') {
+ if (edge.style !== undefined) {
const styles = getStylesFromArray(edge.style);
style = styles.style;
labelStyle = styles.labelStyle;
@@ -291,16 +291,16 @@ export const addEdges = function (edges, g, diagObj) {
edgeData.style = edgeData.style += style;
edgeData.labelStyle = edgeData.labelStyle += labelStyle;
- if (typeof edge.interpolate !== 'undefined') {
+ if (edge.interpolate !== undefined) {
edgeData.curve = interpolateToCurve(edge.interpolate, curveLinear);
- } else if (typeof edges.defaultInterpolate !== 'undefined') {
+ } else if (edges.defaultInterpolate !== undefined) {
edgeData.curve = interpolateToCurve(edges.defaultInterpolate, curveLinear);
} else {
edgeData.curve = interpolateToCurve(conf.curve, curveLinear);
}
- if (typeof edge.text === 'undefined') {
- if (typeof edge.style !== 'undefined') {
+ if (edge.text === undefined) {
+ if (edge.style !== undefined) {
edgeData.arrowheadStyle = 'fill: #333';
}
} else {
@@ -311,7 +311,7 @@ export const addEdges = function (edges, g, diagObj) {
edgeData.labelType = 'text';
edgeData.label = edge.text.replace(common.lineBreakRegex, '\n');
- if (typeof edge.style === 'undefined') {
+ if (edge.style === undefined) {
edgeData.style = edgeData.style || 'stroke: #333; stroke-width: 1.5px;fill:none;';
}
@@ -360,7 +360,7 @@ export const draw = function (text, id, _version, diagObj) {
// Fetch the default direction, use TD if none was found
let dir = diagObj.db.getDirection();
- if (typeof dir === 'undefined') {
+ if (dir === undefined) {
dir = 'TD';
}
@@ -448,9 +448,7 @@ export const draw = function (text, id, _version, diagObj) {
// Add label rects for non html labels
if (!conf.htmlLabels) {
const labels = doc.querySelectorAll('[id="' + id + '"] .edgeLabel .label');
- for (let k = 0; k < labels.length; k++) {
- const label = labels[k];
-
+ for (const label of labels) {
// Get dimensions of label
const dim = label.getBBox();
diff --git a/packages/mermaid/src/diagrams/flowchart/flowRenderer.js b/packages/mermaid/src/diagrams/flowchart/flowRenderer.js
index 7febc4034..4b3232189 100644
--- a/packages/mermaid/src/diagrams/flowchart/flowRenderer.js
+++ b/packages/mermaid/src/diagrams/flowchart/flowRenderer.js
@@ -14,8 +14,8 @@ import addSVGAccessibilityFields from '../../accessibility';
const conf = {};
export const setConf = function (cnf) {
const keys = Object.keys(cnf);
- for (let i = 0; i < keys.length; i++) {
- conf[keys[i]] = cnf[keys[i]];
+ for (const key of keys) {
+ conf[key] = cnf[key];
}
};
@@ -59,7 +59,7 @@ export const addVertices = function (vert, g, svgId, root, _doc, diagObj) {
// TODO: addHtmlLabel accepts a labelStyle. Do we possibly have that?
const node = {
label: vertexText.replace(
- /fa[lrsb]?:fa-[\w-]+/g,
+ /fa[blrs]?:fa-[\w-]+/g,
(s) => ``
),
};
@@ -71,12 +71,12 @@ export const addVertices = function (vert, g, svgId, root, _doc, diagObj) {
const rows = vertexText.split(common.lineBreakRegex);
- for (let j = 0; j < rows.length; j++) {
+ for (const row of rows) {
const tspan = doc.createElementNS('http://www.w3.org/2000/svg', 'tspan');
tspan.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', 'preserve');
tspan.setAttribute('dy', '1em');
tspan.setAttribute('x', '1');
- tspan.textContent = rows[j];
+ tspan.textContent = row;
svgLabel.appendChild(tspan);
}
vertexNode = svgLabel;
@@ -167,7 +167,7 @@ export const addEdges = function (edges, g, diagObj) {
let defaultStyle;
let defaultLabelStyle;
- if (typeof edges.defaultStyle !== 'undefined') {
+ if (edges.defaultStyle !== undefined) {
const defaultStyles = getStylesFromArray(edges.defaultStyle);
defaultStyle = defaultStyles.style;
defaultLabelStyle = defaultStyles.labelStyle;
@@ -193,7 +193,7 @@ export const addEdges = function (edges, g, diagObj) {
let style = '';
let labelStyle = '';
- if (typeof edge.style !== 'undefined') {
+ if (edge.style !== undefined) {
const styles = getStylesFromArray(edge.style);
style = styles.style;
labelStyle = styles.labelStyle;
@@ -201,10 +201,10 @@ export const addEdges = function (edges, g, diagObj) {
switch (edge.stroke) {
case 'normal':
style = 'fill:none';
- if (typeof defaultStyle !== 'undefined') {
+ if (defaultStyle !== undefined) {
style = defaultStyle;
}
- if (typeof defaultLabelStyle !== 'undefined') {
+ if (defaultLabelStyle !== undefined) {
labelStyle = defaultLabelStyle;
}
break;
@@ -220,16 +220,16 @@ export const addEdges = function (edges, g, diagObj) {
edgeData.style = style;
edgeData.labelStyle = labelStyle;
- if (typeof edge.interpolate !== 'undefined') {
+ if (edge.interpolate !== undefined) {
edgeData.curve = interpolateToCurve(edge.interpolate, curveLinear);
- } else if (typeof edges.defaultInterpolate !== 'undefined') {
+ } else if (edges.defaultInterpolate !== undefined) {
edgeData.curve = interpolateToCurve(edges.defaultInterpolate, curveLinear);
} else {
edgeData.curve = interpolateToCurve(conf.curve, curveLinear);
}
- if (typeof edge.text === 'undefined') {
- if (typeof edge.style !== 'undefined') {
+ if (edge.text === undefined) {
+ if (edge.style !== undefined) {
edgeData.arrowheadStyle = 'fill: #333';
}
} else {
@@ -241,14 +241,14 @@ export const addEdges = function (edges, g, diagObj) {
edgeData.label = `${edge.text.replace(
- /fa[lrsb]?:fa-[\w-]+/g,
+ /fa[blrs]?:fa-[\w-]+/g,
(s) => ``
)}`;
} else {
edgeData.labelType = 'text';
edgeData.label = edge.text.replace(common.lineBreakRegex, '\n');
- if (typeof edge.style === 'undefined') {
+ if (edge.style === undefined) {
edgeData.style = edgeData.style || 'stroke: #333; stroke-width: 1.5px;fill:none';
}
@@ -316,7 +316,7 @@ export const draw = function (text, id, _version, diagObj) {
// Fetch the default direction, use TD if none was found
let dir = diagObj.db.getDirection();
- if (typeof dir === 'undefined') {
+ if (dir === undefined) {
dir = 'TD';
}
const nodeSpacing = conf.nodeSpacing || 50;
@@ -459,9 +459,7 @@ export const draw = function (text, id, _version, diagObj) {
// Add label rects for non html labels
if (!conf.htmlLabels) {
const labels = doc.querySelectorAll('[id="' + id + '"] .edgeLabel .label');
- for (let k = 0; k < labels.length; k++) {
- const label = labels[k];
-
+ for (const label of labels) {
// Get dimensions of label
const dim = label.getBBox();
diff --git a/packages/mermaid/src/diagrams/flowchart/parser/flow-direction.spec.js b/packages/mermaid/src/diagrams/flowchart/parser/flow-direction.spec.js
index 6cba33f88..5c2094737 100644
--- a/packages/mermaid/src/diagrams/flowchart/parser/flow-direction.spec.js
+++ b/packages/mermaid/src/diagrams/flowchart/parser/flow-direction.spec.js
@@ -79,8 +79,8 @@ describe('when parsing directions', function () {
const subgraphs = flow.parser.yy.getSubGraphs();
expect(subgraphs.length).toBe(2);
- const subgraphA = filter(subgraphs, (o) => o.id === 'A')[0];
- const subgraphB = filter(subgraphs, (o) => o.id === 'B')[0];
+ const subgraphA = subgraphs.find((o) => o.id === 'A');
+ const subgraphB = subgraphs.find((o) => o.id === 'B');
expect(subgraphB.nodes[0]).toBe('c');
expect(subgraphB.dir).toBe('LR');
diff --git a/packages/mermaid/src/diagrams/flowchart/parser/subgraph.spec.js b/packages/mermaid/src/diagrams/flowchart/parser/subgraph.spec.js
index 6fec233e7..5ba6a5361 100644
--- a/packages/mermaid/src/diagrams/flowchart/parser/subgraph.spec.js
+++ b/packages/mermaid/src/diagrams/flowchart/parser/subgraph.spec.js
@@ -254,8 +254,8 @@ describe('when parsing subgraphs', function () {
const subgraphs = flow.parser.yy.getSubGraphs();
expect(subgraphs.length).toBe(2);
- const subgraphA = filter(subgraphs, (o) => o.id === 'A')[0];
- const subgraphB = filter(subgraphs, (o) => o.id === 'B')[0];
+ const subgraphA = subgraphs.find((o) => o.id === 'A');
+ const subgraphB = subgraphs.find((o) => o.id === 'B');
expect(subgraphB.nodes[0]).toBe('c');
expect(subgraphA.nodes).toContain('B');
@@ -279,8 +279,8 @@ describe('when parsing subgraphs', function () {
const subgraphs = flow.parser.yy.getSubGraphs();
expect(subgraphs.length).toBe(2);
- const subgraphA = filter(subgraphs, (o) => o.id === 'A')[0];
- const subgraphB = filter(subgraphs, (o) => o.id === 'B')[0];
+ const subgraphA = subgraphs.find((o) => o.id === 'A');
+ const subgraphB = subgraphs.find((o) => o.id === 'B');
expect(subgraphB.nodes[0]).toBe('c');
expect(subgraphA.nodes).toContain('B');
@@ -302,8 +302,8 @@ describe('when parsing subgraphs', function () {
const subgraphs = flow.parser.yy.getSubGraphs();
expect(subgraphs.length).toBe(2);
- const subgraphA = filter(subgraphs, (o) => o.id === 'A')[0];
- const subgraphB = filter(subgraphs, (o) => o.id === 'B')[0];
+ const subgraphA = subgraphs.find((o) => o.id === 'A');
+ const subgraphB = subgraphs.find((o) => o.id === 'B');
expect(subgraphB.nodes[0]).toBe('c');
expect(subgraphA.nodes).toContain('B');
expect(subgraphA.nodes).toContain('b');
diff --git a/packages/mermaid/src/diagrams/gantt/ganttDb.js b/packages/mermaid/src/diagrams/gantt/ganttDb.js
index a0f18c3b8..a1c74dd62 100644
--- a/packages/mermaid/src/diagrams/gantt/ganttDb.js
+++ b/packages/mermaid/src/diagrams/gantt/ganttDb.js
@@ -150,16 +150,16 @@ export const getTasks = function () {
};
export const isInvalidDate = function (date, dateFormat, excludes, includes) {
- if (includes.indexOf(date.format(dateFormat.trim())) >= 0) {
+ if (includes.includes(date.format(dateFormat.trim()))) {
return false;
}
- if (date.isoWeekday() >= 6 && excludes.indexOf('weekends') >= 0) {
+ if (date.isoWeekday() >= 6 && excludes.includes('weekends')) {
return true;
}
- if (excludes.indexOf(date.format('dddd').toLowerCase()) >= 0) {
+ if (excludes.includes(date.format('dddd').toLowerCase())) {
return true;
}
- return excludes.indexOf(date.format(dateFormat.trim())) >= 0;
+ return excludes.includes(date.format(dateFormat.trim()));
};
const checkTaskDates = function (task, dateFormat, excludes, includes) {
@@ -202,7 +202,7 @@ const getStartDate = function (prevTime, dateFormat, str) {
let latestEndingTask = null;
afterStatement[1].split(' ').forEach(function (id) {
let task = findTaskById(id);
- if (typeof task !== 'undefined') {
+ if (task !== undefined) {
if (!latestEndingTask) {
latestEndingTask = task;
} else {
@@ -230,7 +230,7 @@ const getStartDate = function (prevTime, dateFormat, str) {
log.debug('Invalid date:' + str);
log.debug('With date format:' + dateFormat.trim());
const d = new Date(str);
- if (typeof d === 'undefined' || isNaN(d.getTime())) {
+ if (d === undefined || isNaN(d.getTime())) {
throw new Error('Invalid date:' + str);
}
return d;
@@ -258,15 +258,14 @@ const getStartDate = function (prevTime, dateFormat, str) {
* string.
*/
const parseDuration = function (str) {
- const statement = /^(\d+(?:\.\d+)?)([yMwdhms]|ms)$/.exec(str.trim());
+ const statement = /^(\d+(?:\.\d+)?)([Mdhmswy]|ms)$/.exec(str.trim());
if (statement !== null) {
return moment.duration(Number.parseFloat(statement[1]), statement[2]);
}
return moment.duration.invalid();
};
-const getEndDate = function (prevTime, dateFormat, str, inclusive) {
- inclusive = inclusive || false;
+const getEndDate = function (prevTime, dateFormat, str, inclusive = false) {
str = str.trim();
// Check for actual date
@@ -288,7 +287,7 @@ const getEndDate = function (prevTime, dateFormat, str, inclusive) {
let taskCnt = 0;
const parseId = function (idStr) {
- if (typeof idStr === 'undefined') {
+ if (idStr === undefined) {
taskCnt = taskCnt + 1;
return 'task' + taskCnt;
}
@@ -510,10 +509,10 @@ const compileTasks = function () {
};
let allProcessed = true;
- for (let i = 0; i < rawTasks.length; i++) {
+ for (const [i, rawTask] of rawTasks.entries()) {
compileTask(i);
- allProcessed = allProcessed && rawTasks[i].processed;
+ allProcessed = allProcessed && rawTask.processed;
}
return allProcessed;
};
@@ -531,7 +530,7 @@ export const setLink = function (ids, _linkStr) {
}
ids.split(',').forEach(function (id) {
let rawTask = findTaskById(id);
- if (typeof rawTask !== 'undefined') {
+ if (rawTask !== undefined) {
pushFun(id, () => {
window.open(linkStr, '_self');
});
@@ -550,7 +549,7 @@ export const setLink = function (ids, _linkStr) {
export const setClass = function (ids, className) {
ids.split(',').forEach(function (id) {
let rawTask = findTaskById(id);
- if (typeof rawTask !== 'undefined') {
+ if (rawTask !== undefined) {
rawTask.classes.push(className);
}
});
@@ -560,7 +559,7 @@ const setClickFun = function (id, functionName, functionArgs) {
if (configApi.getConfig().securityLevel !== 'loose') {
return;
}
- if (typeof functionName === 'undefined') {
+ if (functionName === undefined) {
return;
}
@@ -585,7 +584,7 @@ const setClickFun = function (id, functionName, functionArgs) {
}
let rawTask = findTaskById(id);
- if (typeof rawTask !== 'undefined') {
+ if (rawTask !== undefined) {
pushFun(id, () => {
utils.runFunc(functionName, ...argList);
});
@@ -600,24 +599,26 @@ const setClickFun = function (id, functionName, functionArgs) {
* @param callbackFunction A function to be executed when clicked on the task or the task's text
*/
const pushFun = function (id, callbackFunction) {
- funs.push(function () {
- // const elem = d3.select(element).select(`[id="${id}"]`)
- const elem = document.querySelector(`[id="${id}"]`);
- if (elem !== null) {
- elem.addEventListener('click', function () {
- callbackFunction();
- });
+ funs.push(
+ function () {
+ // const elem = d3.select(element).select(`[id="${id}"]`)
+ const elem = document.querySelector(`[id="${id}"]`);
+ if (elem !== null) {
+ elem.addEventListener('click', function () {
+ callbackFunction();
+ });
+ }
+ },
+ function () {
+ // const elem = d3.select(element).select(`[id="${id}-text"]`)
+ const elem = document.querySelector(`[id="${id}-text"]`);
+ if (elem !== null) {
+ elem.addEventListener('click', function () {
+ callbackFunction();
+ });
+ }
}
- });
- funs.push(function () {
- // const elem = d3.select(element).select(`[id="${id}-text"]`)
- const elem = document.querySelector(`[id="${id}-text"]`);
- if (elem !== null) {
- elem.addEventListener('click', function () {
- callbackFunction();
- });
- }
- });
+ );
};
/**
diff --git a/packages/mermaid/src/diagrams/gantt/ganttRenderer.js b/packages/mermaid/src/diagrams/gantt/ganttRenderer.js
index 9501dd024..ab2407ecd 100644
--- a/packages/mermaid/src/diagrams/gantt/ganttRenderer.js
+++ b/packages/mermaid/src/diagrams/gantt/ganttRenderer.js
@@ -46,11 +46,11 @@ export const draw = function (text, id, version, diagObj) {
const elem = doc.getElementById(id);
w = elem.parentElement.offsetWidth;
- if (typeof w === 'undefined') {
+ if (w === undefined) {
w = 1200;
}
- if (typeof conf.useWidth !== 'undefined') {
+ if (conf.useWidth !== undefined) {
w = conf.useWidth;
}
@@ -77,8 +77,8 @@ export const draw = function (text, id, version, diagObj) {
let categories = [];
- for (let i = 0; i < taskArray.length; i++) {
- categories.push(taskArray[i].type);
+ for (const element of taskArray) {
+ categories.push(element.type);
}
const catsUnfiltered = categories; // for vert labels
@@ -178,8 +178,8 @@ export const draw = function (text, id, version, diagObj) {
})
.attr('height', theGap)
.attr('class', function (d) {
- for (let i = 0; i < categories.length; i++) {
- if (d.type === categories[i]) {
+ for (const [i, category] of categories.entries()) {
+ if (d.type === category) {
return 'section section' + (i % conf.numberSectionStyles);
}
}
@@ -247,8 +247,8 @@ export const draw = function (text, id, version, diagObj) {
}
let secNum = 0;
- for (let i = 0; i < categories.length; i++) {
- if (d.type === categories[i]) {
+ for (const [i, category] of categories.entries()) {
+ if (d.type === category) {
secNum = i % conf.numberSectionStyles;
}
}
@@ -339,8 +339,8 @@ export const draw = function (text, id, version, diagObj) {
}
let secNum = 0;
- for (let i = 0; i < categories.length; i++) {
- if (d.type === categories[i]) {
+ for (const [i, category] of categories.entries()) {
+ if (d.type === category) {
secNum = i % conf.numberSectionStyles;
}
}
@@ -400,7 +400,7 @@ export const draw = function (text, id, version, diagObj) {
rectangles
.filter(function (d) {
- return typeof links[d.id] !== 'undefined';
+ return links[d.id] !== undefined;
})
.each(function (o) {
var taskRect = doc.querySelector('#' + o.id);
@@ -500,7 +500,7 @@ export const draw = function (text, id, version, diagObj) {
.tickSize(-h + theTopPad + conf.gridLineStartPadding)
.tickFormat(timeFormat(diagObj.db.getAxisFormat() || conf.axisFormat || '%Y-%m-%d'));
- const reTickInterval = /^([1-9][0-9]*)(minute|hour|day|week|month)$/;
+ const reTickInterval = /^([1-9]\d*)(minute|hour|day|week|month)$/;
const resultTickInterval = reTickInterval.exec(
diagObj.db.getTickInterval() || conf.tickInterval
);
@@ -588,8 +588,8 @@ export const draw = function (text, id, version, diagObj) {
const numOccurances = [];
let prevGap = 0;
- for (let i = 0; i < categories.length; i++) {
- numOccurances[i] = [categories[i], getCount(categories[i], catsUnfiltered)];
+ for (const [i, category] of categories.entries()) {
+ numOccurances[i] = [category, getCount(category, catsUnfiltered)];
}
svg
@@ -604,14 +604,14 @@ export const draw = function (text, id, version, diagObj) {
const svgLabel = doc.createElementNS('http://www.w3.org/2000/svg', 'text');
svgLabel.setAttribute('dy', dy + 'em');
- for (let j = 0; j < rows.length; j++) {
+ for (const [j, row] of rows.entries()) {
const tspan = doc.createElementNS('http://www.w3.org/2000/svg', 'tspan');
tspan.setAttribute('alignment-baseline', 'central');
tspan.setAttribute('x', '10');
if (j > 0) {
tspan.setAttribute('dy', '1em');
}
- tspan.textContent = rows[j];
+ tspan.textContent = row;
svgLabel.appendChild(tspan);
}
return svgLabel;
@@ -630,8 +630,8 @@ export const draw = function (text, id, version, diagObj) {
.attr('font-size', conf.sectionFontSize)
.attr('font-size', conf.sectionFontSize)
.attr('class', function (d) {
- for (let i = 0; i < categories.length; i++) {
- if (d[0] === categories[i]) {
+ for (const [i, category] of categories.entries()) {
+ if (d[0] === category) {
return 'sectionTitle sectionTitle' + (i % conf.numberSectionStyles);
}
}
diff --git a/packages/mermaid/src/diagrams/git/gitGraphAst.js b/packages/mermaid/src/diagrams/git/gitGraphAst.js
index 65980933d..dded48efa 100644
--- a/packages/mermaid/src/diagrams/git/gitGraphAst.js
+++ b/packages/mermaid/src/diagrams/git/gitGraphAst.js
@@ -131,7 +131,7 @@ export const commit = function (msg, id, type, tag) {
export const branch = function (name, order) {
name = common.sanitizeText(name, configApi.getConfig());
- if (typeof branches[name] === 'undefined') {
+ if (branches[name] === undefined) {
branches[name] = head != null ? head.id : null;
branchesConfig[name] = { name, order: order ? parseInt(order, 10) : null };
checkout(name);
@@ -169,7 +169,7 @@ export const merge = function (otherBranch, custom_id, override_type, custom_tag
expected: ['branch abc'],
};
throw error;
- } else if (typeof currentCommit === 'undefined' || !currentCommit) {
+ } else if (currentCommit === undefined || !currentCommit) {
let error = new Error(
'Incorrect usage of "merge". Current branch (' + curBranch + ')has no commits'
);
@@ -181,7 +181,7 @@ export const merge = function (otherBranch, custom_id, override_type, custom_tag
expected: ['commit'],
};
throw error;
- } else if (typeof branches[otherBranch] === 'undefined') {
+ } else if (branches[otherBranch] === undefined) {
let error = new Error(
'Incorrect usage of "merge". Branch to be merged (' + otherBranch + ') does not exist'
);
@@ -193,7 +193,7 @@ export const merge = function (otherBranch, custom_id, override_type, custom_tag
expected: ['branch ' + otherBranch],
};
throw error;
- } else if (typeof otherCommit === 'undefined' || !otherCommit) {
+ } else if (otherCommit === undefined || !otherCommit) {
let error = new Error(
'Incorrect usage of "merge". Branch to be merged (' + otherBranch + ') has no commits'
);
@@ -215,7 +215,7 @@ export const merge = function (otherBranch, custom_id, override_type, custom_tag
expected: ['branch abc'],
};
throw error;
- } else if (custom_id && typeof commits[custom_id] !== 'undefined') {
+ } else if (custom_id && commits[custom_id] !== undefined) {
let error = new Error(
'Incorrect usage of "merge". Commit with id:' +
custom_id +
@@ -267,7 +267,7 @@ export const cherryPick = function (sourceId, targetId, tag) {
targetId = common.sanitizeText(targetId, configApi.getConfig());
tag = common.sanitizeText(tag, configApi.getConfig());
- if (!sourceId || typeof commits[sourceId] === 'undefined') {
+ if (!sourceId || commits[sourceId] === undefined) {
let error = new Error(
'Incorrect usage of "cherryPick". Source commit id should exist and provided'
);
@@ -296,7 +296,7 @@ export const cherryPick = function (sourceId, targetId, tag) {
};
throw error;
}
- if (!targetId || typeof commits[targetId] === 'undefined') {
+ if (!targetId || commits[targetId] === undefined) {
// cherry-pick source commit to current branch
if (sourceCommitBranch === curBranch) {
@@ -313,7 +313,7 @@ export const cherryPick = function (sourceId, targetId, tag) {
throw error;
}
const currentCommit = commits[branches[curBranch]];
- if (typeof currentCommit === 'undefined' || !currentCommit) {
+ if (currentCommit === undefined || !currentCommit) {
let error = new Error(
'Incorrect usage of "cherry-pick". Current branch (' + curBranch + ')has no commits'
);
@@ -344,7 +344,7 @@ export const cherryPick = function (sourceId, targetId, tag) {
};
export const checkout = function (branch) {
branch = common.sanitizeText(branch, configApi.getConfig());
- if (typeof branches[branch] === 'undefined') {
+ if (branches[branch] === undefined) {
let error = new Error(
'Trying to checkout branch which is not yet created. (Help try using "branch ' + branch + '")'
);
diff --git a/packages/mermaid/src/diagrams/git/gitGraphRenderer-old.js b/packages/mermaid/src/diagrams/git/gitGraphRenderer-old.js
index bfb0ea71c..ca288bfae 100644
--- a/packages/mermaid/src/diagrams/git/gitGraphRenderer-old.js
+++ b/packages/mermaid/src/diagrams/git/gitGraphRenderer-old.js
@@ -310,8 +310,7 @@ function renderCommitHistory(svg, commitId, branches, direction) {
* @param direction
* @param branchColor
*/
-function renderLines(svg, commit, direction, branchColor) {
- branchColor = branchColor || 0;
+function renderLines(svg, commit, direction, branchColor = 0) {
while (commit.seq > 0 && !commit.lineDrawn) {
if (typeof commit.parent === 'string') {
svgDrawLineForCommits(svg, commit.id, commit.parent, direction, branchColor);
diff --git a/packages/mermaid/src/diagrams/git/gitGraphRenderer.js b/packages/mermaid/src/diagrams/git/gitGraphRenderer.js
index 75e8d445d..6874363ad 100644
--- a/packages/mermaid/src/diagrams/git/gitGraphRenderer.js
+++ b/packages/mermaid/src/diagrams/git/gitGraphRenderer.js
@@ -47,13 +47,13 @@ const drawText = (txt) => {
rows = [];
}
- for (let j = 0; j < rows.length; j++) {
+ for (const row of rows) {
const tspan = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
tspan.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', 'preserve');
tspan.setAttribute('dy', '1em');
tspan.setAttribute('x', '0');
tspan.setAttribute('class', 'row');
- tspan.textContent = rows[j].trim();
+ tspan.textContent = row.trim();
svgLabel.appendChild(tspan);
}
/**
@@ -91,7 +91,7 @@ const drawCommits = (svg, commits, modifyGraph) => {
if (modifyGraph) {
let typeClass;
let commitSymbolType =
- typeof commit.customType !== 'undefined' && commit.customType !== ''
+ commit.customType !== undefined && commit.customType !== ''
? commit.customType
: commit.type;
switch (commitSymbolType) {
@@ -319,23 +319,16 @@ const hasOverlappingCommits = (commit1, commit2, allCommits) => {
*
* @param {any} y1
* @param {any} y2
- * @param {any} _depth
+ * @param {any} depth
* @returns {number} Y value between y1 and y2
*/
-const findLane = (y1, y2, _depth) => {
- const depth = _depth || 0;
-
+const findLane = (y1, y2, depth = 0) => {
const candidate = y1 + Math.abs(y1 - y2) / 2;
if (depth > 5) {
return candidate;
}
- let ok = true;
- for (let i = 0; i < lanes.length; i++) {
- if (Math.abs(lanes[i] - candidate) < 10) {
- ok = false;
- }
- }
+ let ok = lanes.every((lane) => Math.abs(lane - candidate) >= 10);
if (ok) {
lanes.push(candidate);
return candidate;
diff --git a/packages/mermaid/src/diagrams/git/layout.js b/packages/mermaid/src/diagrams/git/layout.js
index dd8f23843..de866a72b 100644
--- a/packages/mermaid/src/diagrams/git/layout.js
+++ b/packages/mermaid/src/diagrams/git/layout.js
@@ -5,8 +5,8 @@ export default (dir, _branches) => {
const branches = [];
const commits = [];
- for (let i = 0; i < _branches.length; i++) {
- const branch = Object.assign({}, _branches[i]);
+ for (const [i, _branch] of _branches.entries()) {
+ const branch = Object.assign({}, _branch);
if (dir === 'TB' || dir === 'BT') {
branch.x = config.branchOffset * i;
branch.y = -1;
diff --git a/packages/mermaid/src/diagrams/pie/pieDb.js b/packages/mermaid/src/diagrams/pie/pieDb.js
index 8ef4d9efc..5ccf6d29e 100644
--- a/packages/mermaid/src/diagrams/pie/pieDb.js
+++ b/packages/mermaid/src/diagrams/pie/pieDb.js
@@ -21,7 +21,7 @@ export const parseDirective = function (statement, context, type) {
const addSection = function (id, value) {
id = common.sanitizeText(id, configApi.getConfig());
- if (typeof sections[id] === 'undefined') {
+ if (sections[id] === undefined) {
sections[id] = value;
log.debug('Added new section :', id);
}
diff --git a/packages/mermaid/src/diagrams/pie/pieRenderer.js b/packages/mermaid/src/diagrams/pie/pieRenderer.js
index 60e9a59c9..c5d86ad65 100644
--- a/packages/mermaid/src/diagrams/pie/pieRenderer.js
+++ b/packages/mermaid/src/diagrams/pie/pieRenderer.js
@@ -39,14 +39,14 @@ export const draw = (txt, id, _version, diagObj) => {
const elem = doc.getElementById(id);
width = elem.parentElement.offsetWidth;
- if (typeof width === 'undefined') {
+ if (width === undefined) {
width = 1200;
}
- if (typeof conf.useWidth !== 'undefined') {
+ if (conf.useWidth !== undefined) {
width = conf.useWidth;
}
- if (typeof conf.pie.useWidth !== 'undefined') {
+ if (conf.pie.useWidth !== undefined) {
width = conf.pie.useWidth;
}
diff --git a/packages/mermaid/src/diagrams/requirement/requirementDb.js b/packages/mermaid/src/diagrams/requirement/requirementDb.js
index 9d48f0b2d..df5eb0ab9 100644
--- a/packages/mermaid/src/diagrams/requirement/requirementDb.js
+++ b/packages/mermaid/src/diagrams/requirement/requirementDb.js
@@ -53,7 +53,7 @@ export const parseDirective = function (statement, context, type) {
};
const addRequirement = (name, type) => {
- if (typeof requirements[name] === 'undefined') {
+ if (requirements[name] === undefined) {
requirements[name] = {
name,
type,
@@ -72,31 +72,31 @@ const addRequirement = (name, type) => {
const getRequirements = () => requirements;
const setNewReqId = (id) => {
- if (typeof latestRequirement != 'undefined') {
+ if (latestRequirement !== undefined) {
latestRequirement.id = id;
}
};
const setNewReqText = (text) => {
- if (typeof latestRequirement != 'undefined') {
+ if (latestRequirement !== undefined) {
latestRequirement.text = text;
}
};
const setNewReqRisk = (risk) => {
- if (typeof latestRequirement != 'undefined') {
+ if (latestRequirement !== undefined) {
latestRequirement.risk = risk;
}
};
const setNewReqVerifyMethod = (verifyMethod) => {
- if (typeof latestRequirement != 'undefined') {
+ if (latestRequirement !== undefined) {
latestRequirement.verifyMethod = verifyMethod;
}
};
const addElement = (name) => {
- if (typeof elements[name] === 'undefined') {
+ if (elements[name] === undefined) {
elements[name] = {
name,
@@ -113,13 +113,13 @@ const addElement = (name) => {
const getElements = () => elements;
const setNewElementType = (type) => {
- if (typeof latestElement != 'undefined') {
+ if (latestElement !== undefined) {
latestElement.type = type;
}
};
const setNewElementDocRef = (docRef) => {
- if (typeof latestElement != 'undefined') {
+ if (latestElement !== undefined) {
latestElement.docRef = docRef;
}
};
diff --git a/packages/mermaid/src/diagrams/requirement/requirementRenderer.js b/packages/mermaid/src/diagrams/requirement/requirementRenderer.js
index 10469d50d..a0019f46b 100644
--- a/packages/mermaid/src/diagrams/requirement/requirementRenderer.js
+++ b/packages/mermaid/src/diagrams/requirement/requirementRenderer.js
@@ -284,7 +284,7 @@ const addRelationships = (relationships, g) => {
const adjustEntities = function (svgNode, graph) {
graph.nodes().forEach(function (v) {
- if (typeof v !== 'undefined' && typeof graph.node(v) !== 'undefined') {
+ if (v !== undefined && graph.node(v) !== undefined) {
svgNode.select('#' + v);
svgNode
.select('#' + v)
diff --git a/packages/mermaid/src/diagrams/sequence/sequenceDb.js b/packages/mermaid/src/diagrams/sequence/sequenceDb.js
index ba9d0549b..e2bc4ecf1 100644
--- a/packages/mermaid/src/diagrams/sequence/sequenceDb.js
+++ b/packages/mermaid/src/diagrams/sequence/sequenceDb.js
@@ -60,15 +60,11 @@ const activationCount = (part) => {
let i;
let count = 0;
for (i = 0; i < messages.length; i++) {
- if (messages[i].type === LINETYPE.ACTIVE_START) {
- if (messages[i].from.actor === part) {
- count++;
- }
+ if (messages[i].type === LINETYPE.ACTIVE_START && messages[i].from.actor === part) {
+ count++;
}
- if (messages[i].type === LINETYPE.ACTIVE_END) {
- if (messages[i].from.actor === part) {
- count--;
- }
+ if (messages[i].type === LINETYPE.ACTIVE_END && messages[i].from.actor === part) {
+ count--;
}
}
return count;
@@ -143,7 +139,7 @@ export const setWrap = function (wrapSetting) {
export const autoWrap = () => {
// if setWrap has been called, use that value, otherwise use the value from the config
// TODO: refactor, always use the config value let setWrap update the config value
- if (typeof wrapEnabled !== 'undefined') {
+ if (wrapEnabled !== undefined) {
return wrapEnabled;
}
return configApi.getConfig().sequence.wrap;
@@ -159,11 +155,11 @@ export const clear = function () {
export const parseMessage = function (str) {
const _str = str.trim();
const message = {
- text: _str.replace(/^[:]?(?:no)?wrap:/, '').trim(),
+ text: _str.replace(/^:?(?:no)?wrap:/, '').trim(),
wrap:
- _str.match(/^[:]?wrap:/) !== null
+ _str.match(/^:?wrap:/) !== null
? true
- : _str.match(/^[:]?nowrap:/) !== null
+ : _str.match(/^:?nowrap:/) !== null
? false
: undefined,
};
@@ -223,7 +219,7 @@ export const addNote = function (actor, placement, message) {
};
// Coerce actor into a [to, from, ...] array
- const actors = [].concat(actor, actor);
+ const actors = [actor, actor];
notes.push(note);
messages.push({
@@ -337,7 +333,7 @@ export const addDetails = function (actorId, text) {
};
export const getActorProperty = function (actor, key) {
- if (typeof actor !== 'undefined' && typeof actor.properties !== 'undefined') {
+ if (actor !== undefined && actor.properties !== undefined) {
return actor.properties[key];
}
@@ -345,7 +341,7 @@ export const getActorProperty = function (actor, key) {
};
export const apply = function (param) {
- if (param instanceof Array) {
+ if (Array.isArray(param)) {
param.forEach(function (item) {
apply(item);
});
diff --git a/packages/mermaid/src/diagrams/sequence/sequenceRenderer.ts b/packages/mermaid/src/diagrams/sequence/sequenceRenderer.ts
index fa943d658..738b86540 100644
--- a/packages/mermaid/src/diagrams/sequence/sequenceRenderer.ts
+++ b/packages/mermaid/src/diagrams/sequence/sequenceRenderer.ts
@@ -91,7 +91,7 @@ export const bounds = {
setConf(configApi.getConfig());
},
updateVal: function (obj, key, val, fun) {
- if (typeof obj[key] === 'undefined') {
+ if (obj[key] === undefined) {
obj[key] = val;
} else {
obj[key] = fun(val, obj[key]);
@@ -481,8 +481,8 @@ export const drawActors = function (
let prevWidth = 0;
let prevMargin = 0;
let maxHeight = 0;
- for (let i = 0; i < actorKeys.length; i++) {
- const actor = actors[actorKeys[i]];
+ for (const actorKey of actorKeys) {
+ const actor = actors[actorKey];
// Add some rendering data to the object
actor.width = actor.width || conf.width;
@@ -509,8 +509,8 @@ export const drawActors = function (
export const drawActorsPopup = function (diagram, actors, actorKeys, doc) {
let maxHeight = 0;
let maxWidth = 0;
- for (let i = 0; i < actorKeys.length; i++) {
- const actor = actors[actorKeys[i]];
+ for (const actorKey of actorKeys) {
+ const actor = actors[actorKey];
const minMenuWidth = getRequiredPopupWidth(actor);
const menuDimensions = svgDraw.drawPopup(
diagram,
@@ -1180,7 +1180,7 @@ const buildMessageModel = function (msg, actors, diagObj) {
const toBounds = activationBounds(msg.to, actors);
const fromIdx = fromBounds[0] <= toBounds[0] ? 1 : 0;
const toIdx = fromBounds[0] < toBounds[0] ? 0 : 1;
- const allBounds = fromBounds.concat(toBounds);
+ const allBounds = [...fromBounds, ...toBounds];
const boundedWidth = Math.abs(toBounds[toIdx] - fromBounds[fromIdx]);
if (msg.wrap && msg.message) {
msg.message = utils.wrapLabel(
diff --git a/packages/mermaid/src/diagrams/sequence/svgDraw.js b/packages/mermaid/src/diagrams/sequence/svgDraw.js
index ed4373514..ce1caea69 100644
--- a/packages/mermaid/src/diagrams/sequence/svgDraw.js
+++ b/packages/mermaid/src/diagrams/sequence/svgDraw.js
@@ -13,7 +13,7 @@ export const drawRect = function (elem, rectData) {
rectElem.attr('rx', rectData.rx);
rectElem.attr('ry', rectData.ry);
- if (typeof rectData.class !== 'undefined') {
+ if (rectData.class !== undefined) {
rectElem.attr('class', rectData.class);
}
@@ -62,7 +62,7 @@ export const drawPopup = function (elem, actor, minMenuWidth, textAttrs, forceMe
g.attr('display', displayValue);
addPopupInteraction('#actor' + actorCnt + '_popup', actorCnt);
var actorClass = '';
- if (typeof rectData.class !== 'undefined') {
+ if (rectData.class !== undefined) {
actorClass = ' ' + rectData.class;
}
@@ -160,8 +160,8 @@ export const drawText = function (elem, textData) {
let dy = 0;
let yfunc = () => textData.y;
if (
- typeof textData.valign !== 'undefined' &&
- typeof textData.textMargin !== 'undefined' &&
+ textData.valign !== undefined &&
+ textData.textMargin !== undefined &&
textData.textMargin > 0
) {
switch (textData.valign) {
@@ -186,9 +186,9 @@ export const drawText = function (elem, textData) {
}
}
if (
- typeof textData.anchor !== 'undefined' &&
- typeof textData.textMargin !== 'undefined' &&
- typeof textData.width !== 'undefined'
+ textData.anchor !== undefined &&
+ textData.textMargin !== undefined &&
+ textData.width !== undefined
) {
switch (textData.anchor) {
case 'left':
@@ -214,12 +214,11 @@ export const drawText = function (elem, textData) {
break;
}
}
- for (let i = 0; i < lines.length; i++) {
- let line = lines[i];
+ for (let [i, line] of lines.entries()) {
if (
- typeof textData.textMargin !== 'undefined' &&
+ textData.textMargin !== undefined &&
textData.textMargin === 0 &&
- typeof textData.fontSize !== 'undefined'
+ textData.fontSize !== undefined
) {
dy = i * textData.fontSize;
}
@@ -227,28 +226,28 @@ export const drawText = function (elem, textData) {
const textElem = elem.append('text');
textElem.attr('x', textData.x);
textElem.attr('y', yfunc());
- if (typeof textData.anchor !== 'undefined') {
+ if (textData.anchor !== undefined) {
textElem
.attr('text-anchor', textData.anchor)
.attr('dominant-baseline', textData.dominantBaseline)
.attr('alignment-baseline', textData.alignmentBaseline);
}
- if (typeof textData.fontFamily !== 'undefined') {
+ if (textData.fontFamily !== undefined) {
textElem.style('font-family', textData.fontFamily);
}
- if (typeof textData.fontSize !== 'undefined') {
+ if (textData.fontSize !== undefined) {
textElem.style('font-size', textData.fontSize);
}
- if (typeof textData.fontWeight !== 'undefined') {
+ if (textData.fontWeight !== undefined) {
textElem.style('font-weight', textData.fontWeight);
}
- if (typeof textData.fill !== 'undefined') {
+ if (textData.fill !== undefined) {
textElem.attr('fill', textData.fill);
}
- if (typeof textData.class !== 'undefined') {
+ if (textData.class !== undefined) {
textElem.attr('class', textData.class);
}
- if (typeof textData.dy !== 'undefined') {
+ if (textData.dy !== undefined) {
textElem.attr('dy', textData.dy);
} else if (dy !== 0) {
textElem.attr('dy', dy);
@@ -257,7 +256,7 @@ export const drawText = function (elem, textData) {
if (textData.tspan) {
const span = textElem.append('tspan');
span.attr('x', textData.x);
- if (typeof textData.fill !== 'undefined') {
+ if (textData.fill !== undefined) {
span.attr('fill', textData.fill);
}
span.text(line);
@@ -265,8 +264,8 @@ export const drawText = function (elem, textData) {
textElem.text(line);
}
if (
- typeof textData.valign !== 'undefined' &&
- typeof textData.textMargin !== 'undefined' &&
+ textData.valign !== undefined &&
+ textData.textMargin !== undefined &&
textData.textMargin > 0
) {
textHeight += (textElem._groups || textElem)[0][0].getBBox().height;
@@ -561,7 +560,7 @@ export const drawLoop = function (elem, loopModel, labelText, conf) {
drawLoopLine(loopModel.stopx, loopModel.starty, loopModel.stopx, loopModel.stopy);
drawLoopLine(loopModel.startx, loopModel.stopy, loopModel.stopx, loopModel.stopy);
drawLoopLine(loopModel.startx, loopModel.starty, loopModel.startx, loopModel.stopy);
- if (typeof loopModel.sections !== 'undefined') {
+ if (loopModel.sections !== undefined) {
loopModel.sections.forEach(function (item) {
drawLoopLine(loopModel.startx, item.y, loopModel.stopx, item.y).style(
'stroke-dasharray',
@@ -601,7 +600,7 @@ export const drawLoop = function (elem, loopModel, labelText, conf) {
let textElem = drawText(g, txt);
- if (typeof loopModel.sectionTitles !== 'undefined') {
+ if (loopModel.sectionTitles !== undefined) {
loopModel.sectionTitles.forEach(function (item, idx) {
if (item.message) {
txt.text = item.message;
diff --git a/packages/mermaid/src/diagrams/state/shapes.js b/packages/mermaid/src/diagrams/state/shapes.js
index aa99ff862..0a495e56c 100644
--- a/packages/mermaid/src/diagrams/state/shapes.js
+++ b/packages/mermaid/src/diagrams/state/shapes.js
@@ -197,10 +197,8 @@ export const addTitleAndBox = (g, stateDef, altBkg) => {
if (titleWidth > orgWidth) {
startX = (orgWidth - width) / 2 + pad;
}
- if (Math.abs(orgX - graphBox.x) < pad) {
- if (titleWidth > orgWidth) {
- startX = orgX - (titleWidth - orgWidth) / 2;
- }
+ if (Math.abs(orgX - graphBox.x) < pad && titleWidth > orgWidth) {
+ startX = orgX - (titleWidth - orgWidth) / 2;
}
const lineY = 1 - getConfig().state.textHeight;
@@ -301,7 +299,7 @@ export const drawText = function (elem, textData) {
textElem.attr('y', textData.y);
textElem.style('text-anchor', textData.anchor);
textElem.attr('fill', textData.fill);
- if (typeof textData.class !== 'undefined') {
+ if (textData.class !== undefined) {
textElem.attr('class', textData.class);
}
@@ -464,7 +462,7 @@ export const drawEdge = function (elem, path, relation) {
'url(' + url + '#' + getRelationType(stateDb.relationType.DEPENDENCY) + 'End' + ')'
);
- if (typeof relation.title !== 'undefined') {
+ if (relation.title !== undefined) {
const label = elem.append('g').attr('class', 'stateLabel');
const { x, y } = utils.calcLabelPosition(path.points);
diff --git a/packages/mermaid/src/diagrams/state/stateDb.js b/packages/mermaid/src/diagrams/state/stateDb.js
index 19ecbe65f..991aba078 100644
--- a/packages/mermaid/src/diagrams/state/stateDb.js
+++ b/packages/mermaid/src/diagrams/state/stateDb.js
@@ -94,11 +94,9 @@ const docTranslator = (parent, node, first) => {
docTranslator(parent, node.state1, true);
docTranslator(parent, node.state2, false);
} else {
- if (node.stmt === STMT_STATE) {
- if (node.id === '[*]') {
- node.id = first ? parent.id + '_start' : parent.id + '_end';
- node.start = first;
- }
+ if (node.stmt === STMT_STATE && node.id === '[*]') {
+ node.id = first ? parent.id + '_start' : parent.id + '_end';
+ node.start = first;
}
if (node.doc) {
@@ -218,7 +216,7 @@ export const addState = function (
textStyles = null
) {
// add the state if needed
- if (typeof currentDocument.states[id] === 'undefined') {
+ if (currentDocument.states[id] === undefined) {
log.info('Adding state ', id, descr);
currentDocument.states[id] = {
id: id,
@@ -457,25 +455,23 @@ const getDividerId = () => {
*/
export const addStyleClass = function (id, styleAttributes = '') {
// create a new style class object with this id
- if (typeof classes[id] === 'undefined') {
+ if (classes[id] === undefined) {
classes[id] = { id: id, styles: [], textStyles: [] }; // This is a classDef
}
const foundClass = classes[id];
- if (typeof styleAttributes !== 'undefined') {
- if (styleAttributes !== null) {
- styleAttributes.split(STYLECLASS_SEP).forEach((attrib) => {
- // remove any trailing ;
- const fixedAttrib = attrib.replace(/([^;]*);/, '$1').trim();
+ if (styleAttributes !== undefined && styleAttributes !== null) {
+ styleAttributes.split(STYLECLASS_SEP).forEach((attrib) => {
+ // remove any trailing ;
+ const fixedAttrib = attrib.replace(/([^;]*);/, '$1').trim();
- // replace some style keywords
- if (attrib.match(COLOR_KEYWORD)) {
- const newStyle1 = fixedAttrib.replace(FILL_KEYWORD, BG_FILL);
- const newStyle2 = newStyle1.replace(COLOR_KEYWORD, FILL_KEYWORD);
- foundClass.textStyles.push(newStyle2);
- }
- foundClass.styles.push(fixedAttrib);
- });
- }
+ // replace some style keywords
+ if (attrib.match(COLOR_KEYWORD)) {
+ const newStyle1 = fixedAttrib.replace(FILL_KEYWORD, BG_FILL);
+ const newStyle2 = newStyle1.replace(COLOR_KEYWORD, FILL_KEYWORD);
+ foundClass.textStyles.push(newStyle2);
+ }
+ foundClass.styles.push(fixedAttrib);
+ });
}
};
@@ -498,7 +494,7 @@ export const getClasses = function () {
export const setCssClass = function (itemIds, cssClassName) {
itemIds.split(',').forEach(function (id) {
let foundState = getState(id);
- if (typeof foundState === 'undefined') {
+ if (foundState === undefined) {
const trimmedId = id.trim();
addState(trimmedId);
foundState = getState(trimmedId);
@@ -519,7 +515,7 @@ export const setCssClass = function (itemIds, cssClassName) {
*/
export const setStyle = function (itemId, styleText) {
const item = getState(itemId);
- if (typeof item !== 'undefined') {
+ if (item !== undefined) {
item.textStyles.push(styleText);
}
};
@@ -532,7 +528,7 @@ export const setStyle = function (itemId, styleText) {
*/
export const setTextStyle = function (itemId, cssClassName) {
const item = getState(itemId);
- if (typeof item !== 'undefined') {
+ if (item !== undefined) {
item.textStyles.push(cssClassName);
}
};
diff --git a/packages/mermaid/src/diagrams/state/stateRenderer-v2.js b/packages/mermaid/src/diagrams/state/stateRenderer-v2.js
index 6fdeb723e..78e38726e 100644
--- a/packages/mermaid/src/diagrams/state/stateRenderer-v2.js
+++ b/packages/mermaid/src/diagrams/state/stateRenderer-v2.js
@@ -71,8 +71,8 @@ const conf = {};
export const setConf = function (cnf) {
const keys = Object.keys(cnf);
- for (let i = 0; i < keys.length; i++) {
- conf[keys[i]] = cnf[keys[i]];
+ for (const key of keys) {
+ conf[key] = cnf[key];
}
};
@@ -106,7 +106,7 @@ export const getClasses = function (text, diagramObj) {
* @returns {string}
*/
function getClassesFromDbInfo(dbInfoItem) {
- if (typeof dbInfoItem === 'undefined' || dbInfoItem === null) {
+ if (dbInfoItem === undefined || dbInfoItem === null) {
return '';
} else {
if (dbInfoItem.classes) {
@@ -291,11 +291,9 @@ const setupNode = (g, parent, parsedItem, diagramStates, diagramDb, altFlag) =>
}
}
- if (parent) {
- if (parent.id !== 'root') {
- log.trace('Setting node ', itemId, ' to be child of its parent ', parent.id);
- g.setParent(itemId, parent.id);
- }
+ if (parent && parent.id !== 'root') {
+ log.trace('Setting node ', itemId, ' to be child of its parent ', parent.id);
+ g.setParent(itemId, parent.id);
}
if (parsedItem.doc) {
log.trace('Adding nodes children ');
@@ -386,7 +384,7 @@ export const draw = function (text, id, _version, diag) {
nodeDb = {};
// Fetch the default direction, use TD if none was found
let dir = diag.db.getDirection();
- if (typeof dir === 'undefined') {
+ if (dir === undefined) {
dir = DEFAULT_DIAGRAM_DIRECTION;
}
@@ -459,9 +457,7 @@ export const draw = function (text, id, _version, diag) {
// Add label rects for non html labels
// if (!evaluate(conf.htmlLabels) || true) {
const labels = document.querySelectorAll('[id="' + id + '"] .edgeLabel .label');
- for (let k = 0; k < labels.length; k++) {
- const label = labels[k];
-
+ for (const label of labels) {
// Get dimensions of label
const dim = label.getBBox();
diff --git a/packages/mermaid/src/diagrams/state/stateRenderer.js b/packages/mermaid/src/diagrams/state/stateRenderer.js
index 57b1d1665..4eeede12e 100644
--- a/packages/mermaid/src/diagrams/state/stateRenderer.js
+++ b/packages/mermaid/src/diagrams/state/stateRenderer.js
@@ -162,8 +162,8 @@ const renderDoc = (doc, diagram, parentId, altBkg, root, domDocument, diagObj) =
let first = true;
- for (let i = 0; i < keys.length; i++) {
- const stateDef = states[keys[i]];
+ for (const key of keys) {
+ const stateDef = states[key];
if (parentId) {
stateDef.parentId = parentId;
@@ -245,7 +245,7 @@ const renderDoc = (doc, diagram, parentId, altBkg, root, domDocument, diagObj) =
const svgElem = diagram.node();
graph.nodes().forEach(function (v) {
- if (typeof v !== 'undefined' && typeof graph.node(v) !== 'undefined') {
+ if (v !== undefined && graph.node(v) !== undefined) {
log.warn('Node ' + v + ': ' + JSON.stringify(graph.node(v)));
root
.select('#' + svgElem.id + ' #' + v)
@@ -287,7 +287,7 @@ const renderDoc = (doc, diagram, parentId, altBkg, root, domDocument, diagObj) =
let stateBox = svgElem.getBBox();
graph.edges().forEach(function (e) {
- if (typeof e !== 'undefined' && typeof graph.edge(e) !== 'undefined') {
+ if (e !== undefined && graph.edge(e) !== undefined) {
log.debug('Edge ' + e.v + ' -> ' + e.w + ': ' + JSON.stringify(graph.edge(e)));
drawEdge(diagram, graph.edge(e), graph.edge(e).relation);
}
diff --git a/packages/mermaid/src/diagrams/user-journey/journeyDb.js b/packages/mermaid/src/diagrams/user-journey/journeyDb.js
index 0707636f5..ce8705094 100644
--- a/packages/mermaid/src/diagrams/user-journey/journeyDb.js
+++ b/packages/mermaid/src/diagrams/user-journey/journeyDb.js
@@ -105,10 +105,10 @@ const compileTasks = function () {
};
let allProcessed = true;
- for (let i = 0; i < rawTasks.length; i++) {
+ for (const [i, rawTask] of rawTasks.entries()) {
compileTask(i);
- allProcessed = allProcessed && rawTasks[i].processed;
+ allProcessed = allProcessed && rawTask.processed;
}
return allProcessed;
};
diff --git a/packages/mermaid/src/diagrams/user-journey/journeyRenderer.ts b/packages/mermaid/src/diagrams/user-journey/journeyRenderer.ts
index 3880a243a..b22192101 100644
--- a/packages/mermaid/src/diagrams/user-journey/journeyRenderer.ts
+++ b/packages/mermaid/src/diagrams/user-journey/journeyRenderer.ts
@@ -146,7 +146,7 @@ export const bounds = {
this.verticalPos = 0;
},
updateVal: function (obj, key, val, fun) {
- if (typeof obj[key] === 'undefined') {
+ if (obj[key] === undefined) {
obj[key] = val;
} else {
obj[key] = fun(val, obj[key]);
@@ -221,8 +221,7 @@ export const drawTasks = function (diagram, tasks, verticalPos) {
let num = 0;
// Draw the tasks
- for (let i = 0; i < tasks.length; i++) {
- const task = tasks[i];
+ for (const [i, task] of tasks.entries()) {
if (lastSection !== task.section) {
fill = fills[sectionNumber % fills.length];
num = sectionNumber % fills.length;
diff --git a/packages/mermaid/src/diagrams/user-journey/svgDraw.js b/packages/mermaid/src/diagrams/user-journey/svgDraw.js
index a8c59a939..74d5d2a02 100644
--- a/packages/mermaid/src/diagrams/user-journey/svgDraw.js
+++ b/packages/mermaid/src/diagrams/user-journey/svgDraw.js
@@ -11,7 +11,7 @@ export const drawRect = function (elem, rectData) {
rectElem.attr('rx', rectData.rx);
rectElem.attr('ry', rectData.ry);
- if (typeof rectData.class !== 'undefined') {
+ if (rectData.class !== undefined) {
rectElem.attr('class', rectData.class);
}
@@ -116,11 +116,11 @@ export const drawCircle = function (element, circleData) {
circleElement.attr('stroke', circleData.stroke);
circleElement.attr('r', circleData.r);
- if (typeof circleElement.class !== 'undefined') {
+ if (circleElement.class !== undefined) {
circleElement.attr('class', circleElement.class);
}
- if (typeof circleData.title !== 'undefined') {
+ if (circleData.title !== undefined) {
circleElement.append('title').text(circleData.title);
}
@@ -138,7 +138,7 @@ export const drawText = function (elem, textData) {
textElem.style('text-anchor', textData.anchor);
- if (typeof textData.class !== 'undefined') {
+ if (textData.class !== undefined) {
textElem.attr('class', textData.class);
}
diff --git a/packages/mermaid/src/mermaid.ts b/packages/mermaid/src/mermaid.ts
index 993f2f944..7a4d744e4 100644
--- a/packages/mermaid/src/mermaid.ts
+++ b/packages/mermaid/src/mermaid.ts
@@ -108,7 +108,7 @@ const initThrowsErrors = function (
// if last argument is a function this is the callback function
log.debug(`${!callback ? 'No ' : ''}Callback function found`);
let nodesToProcess: ArrayLike;
- if (typeof nodes === 'undefined') {
+ if (nodes === undefined) {
nodesToProcess = document.querySelectorAll('.mermaid');
} else if (typeof nodes === 'string') {
nodesToProcess = document.querySelectorAll(nodes);
@@ -121,7 +121,7 @@ const initThrowsErrors = function (
}
log.debug(`Found ${nodesToProcess.length} diagrams`);
- if (typeof config?.startOnLoad !== 'undefined') {
+ if (config?.startOnLoad !== undefined) {
log.debug('Start On Load: ' + config?.startOnLoad);
mermaidAPI.updateSiteConfig({ startOnLoad: config?.startOnLoad });
}
@@ -133,6 +133,7 @@ const initThrowsErrors = function (
const errors: DetailedError[] = [];
// element is the current div with mermaid class
+ // eslint-disable-next-line unicorn/prefer-spread
for (const element of Array.from(nodesToProcess)) {
log.info('Rendering diagram: ' + element.id);
/*! Check if previously processed */
@@ -162,7 +163,7 @@ const initThrowsErrors = function (
txt,
(svgCode: string, bindFunctions?: (el: Element) => void) => {
element.innerHTML = svgCode;
- if (typeof callback !== 'undefined') {
+ if (callback !== undefined) {
callback(id);
}
if (bindFunctions) {
@@ -249,7 +250,7 @@ const initThrowsErrorsAsync = async function (
// if last argument is a function this is the callback function
log.debug(`${!callback ? 'No ' : ''}Callback function found`);
let nodesToProcess: ArrayLike;
- if (typeof nodes === 'undefined') {
+ if (nodes === undefined) {
nodesToProcess = document.querySelectorAll('.mermaid');
} else if (typeof nodes === 'string') {
nodesToProcess = document.querySelectorAll(nodes);
@@ -262,7 +263,7 @@ const initThrowsErrorsAsync = async function (
}
log.debug(`Found ${nodesToProcess.length} diagrams`);
- if (typeof config?.startOnLoad !== 'undefined') {
+ if (config?.startOnLoad !== undefined) {
log.debug('Start On Load: ' + config?.startOnLoad);
mermaidAPI.updateSiteConfig({ startOnLoad: config?.startOnLoad });
}
@@ -274,6 +275,7 @@ const initThrowsErrorsAsync = async function (
const errors: DetailedError[] = [];
// element is the current div with mermaid class
+ // eslint-disable-next-line unicorn/prefer-spread
for (const element of Array.from(nodesToProcess)) {
log.info('Rendering diagram: ' + element.id);
/*! Check if previously processed */
@@ -303,7 +305,7 @@ const initThrowsErrorsAsync = async function (
txt,
(svgCode: string, bindFunctions?: (el: Element) => void) => {
element.innerHTML = svgCode;
- if (typeof callback !== 'undefined') {
+ if (callback !== undefined) {
callback(id);
}
if (bindFunctions) {
diff --git a/packages/mermaid/src/mermaidAPI.spec.ts b/packages/mermaid/src/mermaidAPI.spec.ts
index 786b163c4..55d46ae7c 100644
--- a/packages/mermaid/src/mermaidAPI.spec.ts
+++ b/packages/mermaid/src/mermaidAPI.spec.ts
@@ -257,11 +257,11 @@ describe('mermaidAPI', function () {
});
it('gets the fontFamily from the config', () => {
const styles = createCssStyles(mocked_config_with_htmlLabels, 'graphType', {});
- expect(styles).toMatch(/(.*)\n:root \{ --mermaid-font-family: serif(.*)/);
+ expect(styles).toMatch(/(.*)\n:root { --mermaid-font-family: serif(.*)/);
});
it('gets the alt fontFamily from the config', () => {
const styles = createCssStyles(mocked_config_with_htmlLabels, 'graphType', undefined);
- expect(styles).toMatch(/(.*)\n:root \{ --mermaid-alt-font-family: sans-serif(.*)/);
+ expect(styles).toMatch(/(.*)\n:root { --mermaid-alt-font-family: sans-serif(.*)/);
});
describe('there are some classDefs', () => {
@@ -277,7 +277,7 @@ describe('mermaidAPI', function () {
// prefix any special RegExp characters in the given string with a \ so we can use the literal character in a RegExp
function escapeForRegexp(str: string) {
- const strChars = str.split(''); // split into array of every char
+ const strChars = [...str]; // split into array of every char
const strEscaped = strChars.map((char) => {
if (REGEXP_SPECIALS.includes(char)) {
return `\\${char}`;
diff --git a/packages/mermaid/src/mermaidAPI.ts b/packages/mermaid/src/mermaidAPI.ts
index 0b2e85cd6..f9b5b259d 100644
--- a/packages/mermaid/src/mermaidAPI.ts
+++ b/packages/mermaid/src/mermaidAPI.ts
@@ -128,15 +128,9 @@ export const encodeEntities = function (text: string): string {
export const decodeEntities = function (text: string): string {
let txt = text;
- txt = txt.replace(/fl°°/g, function () {
- return '';
- });
- txt = txt.replace(/fl°/g, function () {
- return '&';
- });
- txt = txt.replace(/¶ß/g, function () {
- return ';';
- });
+ txt = txt.replace(/fl°°/g, '');
+ txt = txt.replace(/fl°/g, '&');
+ txt = txt.replace(/¶ß/g, ';');
return txt;
};
@@ -189,28 +183,26 @@ export const createCssStyles = (
}
// classDefs defined in the diagram text
- if (!isEmpty(classDefs)) {
- if (CLASSDEF_DIAGRAMS.includes(graphType)) {
- const htmlLabels = config.htmlLabels || config.flowchart?.htmlLabels; // TODO why specifically check the Flowchart diagram config?
+ if (!isEmpty(classDefs) && CLASSDEF_DIAGRAMS.includes(graphType)) {
+ const htmlLabels = config.htmlLabels || config.flowchart?.htmlLabels; // TODO why specifically check the Flowchart diagram config?
- const cssHtmlElements = ['> *', 'span']; // TODO make a constant
- const cssShapeElements = ['rect', 'polygon', 'ellipse', 'circle', 'path']; // TODO make a constant
+ const cssHtmlElements = ['> *', 'span']; // TODO make a constant
+ const cssShapeElements = ['rect', 'polygon', 'ellipse', 'circle', 'path']; // TODO make a constant
- const cssElements = htmlLabels ? cssHtmlElements : cssShapeElements;
+ const cssElements = htmlLabels ? cssHtmlElements : cssShapeElements;
- // create the CSS styles needed for each styleClass definition and css element
- for (const classId in classDefs) {
- const styleClassDef = classDefs[classId];
- // create the css styles for each cssElement and the styles (only if there are styles)
- if (!isEmpty(styleClassDef.styles)) {
- cssElements.forEach((cssElement) => {
- cssStyles += cssImportantStyles(styleClassDef.id, cssElement, styleClassDef.styles);
- });
- }
- // create the css styles for the tspan element and the text styles (only if there are textStyles)
- if (!isEmpty(styleClassDef.textStyles)) {
- cssStyles += cssImportantStyles(styleClassDef.id, 'tspan', styleClassDef.textStyles);
- }
+ // create the CSS styles needed for each styleClass definition and css element
+ for (const classId in classDefs) {
+ const styleClassDef = classDefs[classId];
+ // create the css styles for each cssElement and the styles (only if there are styles)
+ if (!isEmpty(styleClassDef.styles)) {
+ cssElements.forEach((cssElement) => {
+ cssStyles += cssImportantStyles(styleClassDef.id, cssElement, styleClassDef.styles);
+ });
+ }
+ // create the css styles for the tspan element and the text styles (only if there are textStyles)
+ if (!isEmpty(styleClassDef.textStyles)) {
+ cssStyles += cssImportantStyles(styleClassDef.id, 'tspan', styleClassDef.textStyles);
}
}
}
@@ -432,7 +424,7 @@ const render = function (
// Define the root d3 node
// In regular execution the svgContainingElement will be the element with a mermaid class
- if (typeof svgContainingElement !== 'undefined') {
+ if (svgContainingElement !== undefined) {
if (svgContainingElement) {
svgContainingElement.innerHTML = '';
}
@@ -545,7 +537,7 @@ const render = function (
// -------------------------------------------------------------------------------
// Do any callbacks (cb = callback)
- if (typeof cb !== 'undefined') {
+ if (cb !== undefined) {
switch (graphType) {
case 'flowchart':
case 'flowchart-v2':
@@ -631,7 +623,7 @@ const renderAsync = async function (
// Define the root d3 node
// In regular execution the svgContainingElement will be the element with a mermaid class
- if (typeof svgContainingElement !== 'undefined') {
+ if (svgContainingElement !== undefined) {
if (svgContainingElement) {
svgContainingElement.innerHTML = '';
}
@@ -741,7 +733,7 @@ const renderAsync = async function (
// -------------------------------------------------------------------------------
// Do any callbacks (cb = callback)
- if (typeof cb !== 'undefined') {
+ if (cb !== undefined) {
switch (graphType) {
case 'flowchart':
case 'flowchart-v2':
@@ -820,7 +812,7 @@ const handleDirective = function (p: any, directive: any, type: string): void {
case 'init':
case 'initialize': {
['config'].forEach((prop) => {
- if (typeof directive.args[prop] !== 'undefined') {
+ if (directive.args[prop] !== undefined) {
if (type === 'flowchart-v2') {
type = 'flowchart';
}
@@ -859,10 +851,8 @@ const handleDirective = function (p: any, directive: any, type: string): void {
*/
function initialize(options: MermaidConfig = {}) {
// Handle legacy location of font-family configuration
- if (options?.fontFamily) {
- if (!options.themeVariables?.fontFamily) {
- options.themeVariables = { fontFamily: options.fontFamily };
- }
+ if (options?.fontFamily && !options.themeVariables?.fontFamily) {
+ options.themeVariables = { fontFamily: options.fontFamily };
}
// Set default options
diff --git a/packages/mermaid/src/tests/MockedD3.ts b/packages/mermaid/src/tests/MockedD3.ts
index d7c16b3a8..9cf01ddad 100644
--- a/packages/mermaid/src/tests/MockedD3.ts
+++ b/packages/mermaid/src/tests/MockedD3.ts
@@ -23,7 +23,7 @@ export class MockedD3 {
select = vi.fn().mockImplementation(({ select_str = '' }): MockedD3 => {
// Get the id from an argument string. if it is of the form [id='some-id'], strip off the
// surrounding id[..]
- const stripSurroundRegexp = /\[id='(.*)'\]/;
+ const stripSurroundRegexp = /\[id='(.*)']/;
const matchedSurrounds = select_str.match(stripSurroundRegexp);
const cleanId = matchedSurrounds ? matchedSurrounds[1] : select_str;
return new MockedD3(cleanId);
diff --git a/packages/mermaid/src/utils.ts b/packages/mermaid/src/utils.ts
index 3689a01a1..16566c3b1 100644
--- a/packages/mermaid/src/utils.ts
+++ b/packages/mermaid/src/utils.ts
@@ -37,10 +37,9 @@ const d3CurveTypes = {
curveStepAfter: curveStepAfter,
curveStepBefore: curveStepBefore,
};
-const directive =
- /[%]{2}[{]\s*(?:(?:(\w+)\s*:|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi;
+const directive = /%{2}{\s*(?:(\w+)\s*:|(\w+))\s*(?:(\w+)|((?:(?!}%{2}).|\r?\n)*))?\s*(?:}%{2})?/gi;
const directiveWithoutOpen =
- /\s*(?:(?:(\w+)(?=:):|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi;
+ /\s*(?:(\w+)(?=:):|(\w+))\s*(?:(\w+)|((?:(?!}%{2}).|\r?\n)*))?\s*(?:}%{2})?/gi;
/**
* Detects the init config object from the text
@@ -91,7 +90,7 @@ export const detectInit = function (text: string, config?: MermaidConfig): Merma
if (results) {
let type = detectType(text, config);
['config'].forEach((prop) => {
- if (typeof results[prop] !== 'undefined') {
+ if (results[prop] !== undefined) {
if (type === 'flowchart-v2') {
type = 'flowchart';
}
@@ -180,8 +179,8 @@ export const detectDirective = function (
* @returns The array index containing the substring or -1 if not present
*/
export const isSubstringInArray = function (str: string, arr: string[]): number {
- for (let i = 0; i < arr.length; i++) {
- if (arr[i].match(str)) {
+ for (const [i, element] of arr.entries()) {
+ if (element.match(str)) {
return i;
}
}
@@ -460,13 +459,13 @@ export function getStylesFromArray(arr: string[]): { style: string; labelStyle:
let style = '';
let labelStyle = '';
- for (let i = 0; i < arr.length; i++) {
- if (typeof arr[i] !== 'undefined') {
+ for (const element of arr) {
+ if (element !== undefined) {
// add text properties to label style definition
- if (arr[i].startsWith('color:') || arr[i].startsWith('text-align:')) {
- labelStyle = labelStyle + arr[i] + ';';
+ if (element.startsWith('color:') || element.startsWith('text-align:')) {
+ labelStyle = labelStyle + element + ';';
} else {
- style = style + arr[i] + ';';
+ style = style + element + ';';
}
}
}
@@ -549,7 +548,7 @@ export const drawSimpleText = function (
textElem.style('font-size', textData.fontSize);
textElem.style('font-weight', textData.fontWeight);
textElem.attr('fill', textData.fill);
- if (typeof textData.class !== 'undefined') {
+ if (textData.class !== undefined) {
textElem.attr('class', textData.class);
}
@@ -630,7 +629,7 @@ const breakString: (
{ fontSize: 12, fontWeight: 400, fontFamily: 'Arial', margin: 0 },
config
);
- const characters = word.split('');
+ const characters = [...word];
const lines: string[] = [];
let currentLine = '';
characters.forEach((character, index) => {
@@ -822,34 +821,34 @@ export const directiveSanitizer = (args: any) => {
// This is an object
Object.keys(args).forEach((key) => {
log.debug('Checking key', key);
- if (key.indexOf('__') === 0) {
+ if (key.startsWith('__')) {
log.debug('sanitize deleting __ option', key);
delete args[key];
}
- if (key.indexOf('proto') >= 0) {
+ if (key.includes('proto')) {
log.debug('sanitize deleting proto option', key);
delete args[key];
}
- if (key.indexOf('constr') >= 0) {
+ if (key.includes('constr')) {
log.debug('sanitize deleting constr option', key);
delete args[key];
}
- if (key.indexOf('themeCSS') >= 0) {
+ if (key.includes('themeCSS')) {
log.debug('sanitizing themeCss option');
args[key] = sanitizeCss(args[key]);
}
- if (key.indexOf('fontFamily') >= 0) {
+ if (key.includes('fontFamily')) {
log.debug('sanitizing fontFamily option');
args[key] = sanitizeCss(args[key]);
}
- if (key.indexOf('altFontFamily') >= 0) {
+ if (key.includes('altFontFamily')) {
log.debug('sanitizing altFontFamily option');
args[key] = sanitizeCss(args[key]);
}
- if (configKeys.indexOf(key) < 0) {
+ if (!configKeys.includes(key)) {
log.debug('sanitize deleting option', key);
delete args[key];
} else {
@@ -863,10 +862,9 @@ export const directiveSanitizer = (args: any) => {
}
if (args.themeVariables) {
const kArr = Object.keys(args.themeVariables);
- for (let i = 0; i < kArr.length; i++) {
- const k = kArr[i];
+ for (const k of kArr) {
const val = args.themeVariables[k];
- if (val && val.match && !val.match(/^[a-zA-Z0-9#,";()%. ]+$/)) {
+ if (val && val.match && !val.match(/^[\d "#%(),.;A-Za-z]+$/)) {
args.themeVariables[k] = '';
}
}
@@ -877,13 +875,13 @@ export const sanitizeCss = (str) => {
let startCnt = 0;
let endCnt = 0;
- for (let i = 0; i < str.length; i++) {
+ for (const element of str) {
if (startCnt < endCnt) {
return '{ /* ERROR: Unbalanced CSS */ }';
}
- if (str[i] === '{') {
+ if (element === '{') {
startCnt++;
- } else if (str[i] === '}') {
+ } else if (element === '}') {
endCnt++;
}
}
diff --git a/scripts/jison/lint.mts b/scripts/jison/lint.mts
index e834a8e4f..c410d5999 100644
--- a/scripts/jison/lint.mts
+++ b/scripts/jison/lint.mts
@@ -28,7 +28,7 @@ const lint = async (file: string): Promise => {
dot: true,
});
const lintResults = await Promise.all(jisonFiles.map(lint));
- if (lintResults.some((result) => result === false)) {
+ if (lintResults.includes(false)) {
process.exit(1);
}
})();