Adding new flowchart renderer using cytoscape

This commit is contained in:
Knut Sveidqvist
2022-12-02 08:06:16 +01:00
parent 650ee31cd1
commit 4f1b26fd76
12 changed files with 1026 additions and 27 deletions

View File

@@ -41,6 +41,11 @@ const packageOptions = {
packageName: 'mermaid-mindmap',
file: 'detector.ts',
},
'mermaid-flowchart-v3': {
name: 'mermaid-flowchart-v3',
packageName: 'mermaid-flowchart-v3',
file: 'detector.ts',
},
// 'mermaid-example-diagram-detector': {
// name: 'mermaid-example-diagram-detector',
// packageName: 'mermaid-example-diagram',
@@ -120,6 +125,7 @@ export const getBuildConfig = ({ minify, core, watch, entryName }: BuildOptions)
if (watch && config.build) {
config.build.watch = {
include: [
'packages/mermaid-flowchart-v3/src/**',
'packages/mermaid-mindmap/src/**',
'packages/mermaid/src/**',
// 'packages/mermaid-example-diagram/src/**',
@@ -148,6 +154,7 @@ const main = async () => {
if (watch) {
build(getBuildConfig({ minify: false, watch, core: true, entryName: 'mermaid' }));
if (!mermaidOnly) {
build(getBuildConfig({ minify: false, watch, entryName: 'mermaid-flowchart-v3' }));
build(getBuildConfig({ minify: false, watch, entryName: 'mermaid-mindmap' }));
// build(getBuildConfig({ minify: false, watch, entryName: 'mermaid-example-diagram' }));
}

View File

@@ -56,14 +56,20 @@
<body>
<div>Security check</div>
<pre id="diagram" class="mermaid">
graph LR
subgraph external
inside
end
outside --> external
</pre>
<pre id="diagram" class="mermaid">
mindmap
cyto LR
subgraph test
inside1 --> inside2
end
subgraph test2
inside3 --> inside4
end
out
</pre
>
a(letter a<br />a) ---> b(letter b)--> c(letter c) --> d -->e(letter e<br />e) --> a b <-->
d(letter b<br />d)
<pre id="diagram" class="mermaid2">
mindmap
root
child1((Circle))
grandchild 1
@@ -78,7 +84,7 @@ mindmap
::icon(mdi mdi-fire)
gc7((grand<br/>grand<br/>child 8))
</pre>
<pre id="diagram" class="mermaid">
<pre id="diagram" class="mermaid2">
gantt
title Style today marker (vertical line should be 5px wide and half-transparent blue)
dateFormat YYYY-MM-DD
@@ -96,9 +102,10 @@ mindmap
<script type="module">
import mindmap from '../../packages/mermaid-mindmap/src/detector';
import flowV3 from '../../packages/mermaid-flowchart-v3/src/detector';
// import example from '../../packages/mermaid-example-diagram/src/detector';
import mermaid from '../../packages/mermaid/src/mermaid';
await mermaid.registerExternalDiagrams([mindmap]);
await mermaid.registerExternalDiagrams([mindmap, flowV3]);
mermaid.parseError = function (err, hash) {
// console.error('Mermaid error: ', err);
};

View File

@@ -0,0 +1,66 @@
{
"name": "@mermaid-js/mermaid-mindmap",
"version": "9.2.2",
"description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.",
"module": "dist/mermaid-mindmap.core.mjs",
"types": "dist/detector.d.ts",
"type": "module",
"exports": {
".": {
"import": "./dist/mermaid-mindmap.core.mjs",
"types": "./dist/detector.d.ts"
},
"./*": "./*"
},
"keywords": [
"diagram",
"markdown",
"mindmap",
"mermaid"
],
"scripts": {
"prepublishOnly": "pnpm -w run build"
},
"repository": {
"type": "git",
"url": "https://github.com/mermaid-js/mermaid"
},
"author": "Knut Sveidqvist",
"license": "MIT",
"standard": {
"ignore": [
"**/parser/*.js",
"dist/**/*.js",
"cypress/**/*.js"
],
"globals": [
"page"
]
},
"dependencies": {
"@braintree/sanitize-url": "^6.0.0",
"cytoscape": "^3.23.0",
"cytoscape-cose-bilkent": "^4.1.0",
"cytoscape-fcose": "^2.1.0",
"graphlib": "^2.1.0",
"dagre-d3-es": "7.0.4",
"d3": "^7.0.0",
"khroma": "^2.0.0",
"non-layered-tidy-tree-layout": "^2.0.2"
},
"devDependencies": {
"concurrently": "^7.5.0",
"mermaid": "workspace:*",
"rimraf": "^3.0.2"
},
"resolutions": {
"d3": "^7.0.0"
},
"files": [
"dist"
],
"sideEffects": [
"**/*.css",
"**/*.scss"
]
}

View File

@@ -0,0 +1,24 @@
import type { ExternalDiagramDefinition } from 'mermaid';
const id = 'flowchart-v3';
const detector = (txt: string, config) => {
// If we have configured to use dagre-wrapper then we should return true in this function for graph code thus making it use the new flowchart diagram
if (config?.flowchart?.defaultRenderer === 'cytoscape' && txt.match(/^\s*graph/) !== null) {
return true;
}
return txt.match(/^\s*cyto/) !== null;
};
const loader = async () => {
const { diagram } = await import('./diagram-definition');
return { id, diagram };
};
const plugin: ExternalDiagramDefinition = {
id,
detector,
loader,
};
export default plugin;

View File

@@ -0,0 +1,14 @@
// @ts-ignore: TODO Fix ts errors
import parser from '../../mermaid/src/diagrams/flowchart/parser/flow';
import * as db from '../../mermaid/src/diagrams/flowchart/flowDb';
import renderer from './flowRenderer-v3';
import styles from './styles';
import { injectUtils } from './mermaidUtils';
export const diagram = {
db,
renderer,
parser,
styles,
injectUtils,
};

View File

@@ -0,0 +1,674 @@
import graphlib from 'graphlib';
import { select, line, curveLinear, curveCardinal, curveBasis, selectAll } from 'd3';
import { log, getConfig, setupGraphViewbox } from './mermaidUtils';
import { insertNode } from '../../mermaid/src/dagre-wrapper/nodes.js';
import insertMarkers from '../../mermaid/src/dagre-wrapper/markers.js';
// Replace with other function to avoid dependency to dagre-d3
import { addHtmlLabel } from 'dagre-d3-es/src/dagre-js/label/add-html-label.js';
import common, { evaluate } from '../../mermaid/src/diagrams/common/common';
import { interpolateToCurve, getStylesFromArray } from '../../mermaid/src/utils';
import cytoscape from 'cytoscape';
const conf = {};
export const setConf = function (cnf) {
const keys = Object.keys(cnf);
for (const key of keys) {
conf[key] = cnf[key];
}
};
// /**
// * Function that adds the vertices found during parsing to the graph to be rendered.
// *
// * @param vert Object containing the vertices.
// * @param g The graph that is to be drawn.
// * @param svgId
// * @param root
// * @param doc
// * @param diagObj
// */
export const addVertices = function (vert, cy, svgId, root, doc, diagObj, parentLookUpDb) {
const svg = root.select(`[id="${svgId}"]`);
const nodes = svg.insert('g').attr('class', 'nodes');
const keys = Object.keys(vert);
// Iterate through each item in the vertex object (containing all the vertices found) in the graph definition
keys.forEach(function (id) {
const vertex = vert[id];
/**
* Variable for storing the classes for the vertex
*
* @type {string}
*/
let classStr = 'default';
if (vertex.classes.length > 0) {
classStr = vertex.classes.join(' ');
}
const styles = getStylesFromArray(vertex.styles);
// Use vertex id as text in the box if no text is provided by the graph definition
let vertexText = vertex.text !== undefined ? vertex.text : vertex.id;
// We create a SVG label, either by delegating to addHtmlLabel or manually
let vertexNode;
if (evaluate(getConfig().flowchart.htmlLabels)) {
// TODO: addHtmlLabel accepts a labelStyle. Do we possibly have that?
const node = {
label: vertexText.replace(
/fa[blrs]?:fa-[\w-]+/g,
(s) => `<i class='${s.replace(':', ' ')}'></i>`
),
};
vertexNode = addHtmlLabel(svg, node).node();
vertexNode.parentNode.removeChild(vertexNode);
} else {
const svgLabel = doc.createElementNS('http://www.w3.org/2000/svg', 'text');
svgLabel.setAttribute('style', styles.labelStyle.replace('color:', 'fill:'));
const rows = vertexText.split(common.lineBreakRegex);
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 = row;
svgLabel.appendChild(tspan);
}
vertexNode = svgLabel;
}
let radious = 0;
let _shape = '';
// Set the shape based parameters
switch (vertex.type) {
case 'round':
radious = 5;
_shape = 'rect';
break;
case 'square':
_shape = 'rect';
break;
case 'diamond':
_shape = 'question';
break;
case 'hexagon':
_shape = 'hexagon';
break;
case 'odd':
_shape = 'rect_left_inv_arrow';
break;
case 'lean_right':
_shape = 'lean_right';
break;
case 'lean_left':
_shape = 'lean_left';
break;
case 'trapezoid':
_shape = 'trapezoid';
break;
case 'inv_trapezoid':
_shape = 'inv_trapezoid';
break;
case 'odd_right':
_shape = 'rect_left_inv_arrow';
break;
case 'circle':
_shape = 'circle';
break;
case 'ellipse':
_shape = 'ellipse';
break;
case 'stadium':
_shape = 'stadium';
break;
case 'subroutine':
_shape = 'subroutine';
break;
case 'cylinder':
_shape = 'cylinder';
break;
case 'group':
_shape = 'rect';
break;
case 'doublecircle':
_shape = 'doublecircle';
break;
default:
_shape = 'rect';
}
// // Add the node
const node = {
labelStyle: styles.labelStyle,
shape: _shape,
labelText: vertexText,
rx: radious,
ry: radious,
class: classStr,
style: styles.style,
id: vertex.id,
link: vertex.link,
linkTarget: vertex.linkTarget,
tooltip: diagObj.db.getTooltip(vertex.id) || '',
domId: diagObj.db.lookUpDomId(vertex.id),
haveCallback: vertex.haveCallback,
width: vertex.type === 'group' ? 500 : undefined,
dir: vertex.dir,
type: vertex.type,
props: vertex.props,
padding: getConfig().flowchart.padding,
};
const nodeEl = insertNode(nodes, node, vertex.dir);
const boundingBox = nodeEl.node().getBBox();
cy.add({
group: 'nodes',
data: {
id: vertex.id,
labelStyle: styles.labelStyle,
shape: _shape,
labelText: vertexText,
rx: radious,
ry: radious,
class: classStr,
style: styles.style,
link: vertex.link,
linkTarget: vertex.linkTarget,
tooltip: diagObj.db.getTooltip(vertex.id) || '',
domId: diagObj.db.lookUpDomId(vertex.id),
haveCallback: vertex.haveCallback,
width: vertex.type === 'group' ? 500 : undefined,
dir: vertex.dir,
type: vertex.type,
props: vertex.props,
padding: getConfig().flowchart.padding,
boundingBox,
el: nodeEl,
parent: parentLookUpDb[vertex.id],
},
});
log.trace('setNode', {
labelStyle: styles.labelStyle,
shape: _shape,
labelText: vertexText,
rx: radious,
ry: radious,
class: classStr,
style: styles.style,
id: vertex.id,
domId: diagObj.db.lookUpDomId(vertex.id),
width: vertex.type === 'group' ? 500 : undefined,
type: vertex.type,
dir: vertex.dir,
props: vertex.props,
padding: getConfig().flowchart.padding,
parent: parentLookUpDb[vertex.id],
});
});
};
/**
* Add edges to graph based on parsed graph definition
*
* @param {object} edges The edges to add to the graph
* @param {object} g The graph object
* @param cy
* @param diagObj
*/
export const addEdges = function (edges, cy, diagObj) {
// log.info('abc78 edges = ', edges);
let cnt = 0;
let linkIdCnt = {};
let defaultStyle;
let defaultLabelStyle;
if (edges.defaultStyle !== undefined) {
const defaultStyles = getStylesFromArray(edges.defaultStyle);
defaultStyle = defaultStyles.style;
defaultLabelStyle = defaultStyles.labelStyle;
}
edges.forEach(function (edge) {
cnt++;
// Identify Link
var linkIdBase = 'L-' + edge.start + '-' + edge.end;
// count the links from+to the same node to give unique id
if (linkIdCnt[linkIdBase] === undefined) {
linkIdCnt[linkIdBase] = 0;
log.info('abc78 new entry', linkIdBase, linkIdCnt[linkIdBase]);
} else {
linkIdCnt[linkIdBase]++;
log.info('abc78 new entry', linkIdBase, linkIdCnt[linkIdBase]);
}
let linkId = linkIdBase + '-' + linkIdCnt[linkIdBase];
log.info('abc78 new link id to be used is', linkIdBase, linkId, linkIdCnt[linkIdBase]);
var linkNameStart = 'LS-' + edge.start;
var linkNameEnd = 'LE-' + edge.end;
const edgeData = { style: '', labelStyle: '' };
edgeData.minlen = edge.length || 1;
//edgeData.id = 'id' + cnt;
// Set link type for rendering
if (edge.type === 'arrow_open') {
edgeData.arrowhead = 'none';
} else {
edgeData.arrowhead = 'normal';
}
// Check of arrow types, placed here in order not to break old rendering
edgeData.arrowTypeStart = 'arrow_open';
edgeData.arrowTypeEnd = 'arrow_open';
/* eslint-disable no-fallthrough */
switch (edge.type) {
case 'double_arrow_cross':
edgeData.arrowTypeStart = 'arrow_cross';
case 'arrow_cross':
edgeData.arrowTypeEnd = 'arrow_cross';
break;
case 'double_arrow_point':
edgeData.arrowTypeStart = 'arrow_point';
case 'arrow_point':
edgeData.arrowTypeEnd = 'arrow_point';
break;
case 'double_arrow_circle':
edgeData.arrowTypeStart = 'arrow_circle';
case 'arrow_circle':
edgeData.arrowTypeEnd = 'arrow_circle';
break;
}
let style = '';
let labelStyle = '';
switch (edge.stroke) {
case 'normal':
style = 'fill:none;';
if (defaultStyle !== undefined) {
style = defaultStyle;
}
if (defaultLabelStyle !== undefined) {
labelStyle = defaultLabelStyle;
}
edgeData.thickness = 'normal';
edgeData.pattern = 'solid';
break;
case 'dotted':
edgeData.thickness = 'normal';
edgeData.pattern = 'dotted';
edgeData.style = 'fill:none;stroke-width:2px;stroke-dasharray:3;';
break;
case 'thick':
edgeData.thickness = 'thick';
edgeData.pattern = 'solid';
edgeData.style = 'stroke-width: 3.5px;fill:none;';
break;
}
if (edge.style !== undefined) {
const styles = getStylesFromArray(edge.style);
style = styles.style;
labelStyle = styles.labelStyle;
}
edgeData.style = edgeData.style += style;
edgeData.labelStyle = edgeData.labelStyle += labelStyle;
if (edge.interpolate !== undefined) {
edgeData.curve = interpolateToCurve(edge.interpolate, curveLinear);
} else if (edges.defaultInterpolate !== undefined) {
edgeData.curve = interpolateToCurve(edges.defaultInterpolate, curveLinear);
} else {
edgeData.curve = interpolateToCurve(conf.curve, curveLinear);
}
if (edge.text === undefined) {
if (edge.style !== undefined) {
edgeData.arrowheadStyle = 'fill: #333';
}
} else {
edgeData.arrowheadStyle = 'fill: #333';
edgeData.labelpos = 'c';
}
edgeData.labelType = 'text';
edgeData.label = edge.text.replace(common.lineBreakRegex, '\n');
if (edge.style === undefined) {
edgeData.style = edgeData.style || 'stroke: #333; stroke-width: 1.5px;fill:none;';
}
edgeData.labelStyle = edgeData.labelStyle.replace('color:', 'fill:');
edgeData.id = linkId;
edgeData.classes = 'flowchart-link ' + linkNameStart + ' ' + linkNameEnd;
// Add the edge to the graph
cy.add({ group: 'edges', data: { source: edge.start, target: edge.end, edgeData, id: cnt } });
});
};
const addmarkers = function (svgPath, edgeData, diagramType, arrowMarkerAbsolute) {
// // TODO: Can we load this config only from the rendered graph type?
let url;
if (arrowMarkerAbsolute) {
url =
window.location.protocol +
'//' +
window.location.host +
window.location.pathname +
window.location.search;
url = url.replace(/\(/g, '\\(');
url = url.replace(/\)/g, '\\)');
}
switch (edgeData.arrowTypeStart) {
case 'arrow_cross':
svgPath.attr('marker-start', 'url(' + url + '#' + diagramType + '-crossStart' + ')');
break;
case 'arrow_point':
svgPath.attr('marker-start', 'url(' + url + '#' + diagramType + '-pointStart' + ')');
break;
case 'arrow_barb':
svgPath.attr('marker-start', 'url(' + url + '#' + diagramType + '-barbStart' + ')');
break;
case 'arrow_circle':
svgPath.attr('marker-start', 'url(' + url + '#' + diagramType + '-circleStart' + ')');
break;
case 'aggregation':
svgPath.attr('marker-start', 'url(' + url + '#' + diagramType + '-aggregationStart' + ')');
break;
case 'extension':
svgPath.attr('marker-start', 'url(' + url + '#' + diagramType + '-extensionStart' + ')');
break;
case 'composition':
svgPath.attr('marker-start', 'url(' + url + '#' + diagramType + '-compositionStart' + ')');
break;
case 'dependency':
svgPath.attr('marker-start', 'url(' + url + '#' + diagramType + '-dependencyStart' + ')');
break;
case 'lollipop':
svgPath.attr('marker-start', 'url(' + url + '#' + diagramType + '-lollipopStart' + ')');
break;
default:
}
switch (edgeData.arrowTypeEnd) {
case 'arrow_cross':
svgPath.attr('marker-end', 'url(' + url + '#' + diagramType + '-crossEnd' + ')');
break;
case 'arrow_point':
svgPath.attr('marker-end', 'url(' + url + '#' + diagramType + '-pointEnd' + ')');
break;
case 'arrow_barb':
svgPath.attr('marker-end', 'url(' + url + '#' + diagramType + '-barbEnd' + ')');
break;
case 'arrow_circle':
svgPath.attr('marker-end', 'url(' + url + '#' + diagramType + '-circleEnd' + ')');
break;
case 'aggregation':
svgPath.attr('marker-end', 'url(' + url + '#' + diagramType + '-aggregationEnd' + ')');
break;
case 'extension':
svgPath.attr('marker-end', 'url(' + url + '#' + diagramType + '-extensionEnd' + ')');
break;
case 'composition':
svgPath.attr('marker-end', 'url(' + url + '#' + diagramType + '-compositionEnd' + ')');
break;
case 'dependency':
svgPath.attr('marker-end', 'url(' + url + '#' + diagramType + '-dependencyEnd' + ')');
break;
case 'lollipop':
svgPath.attr('marker-end', 'url(' + url + '#' + diagramType + '-lollipopEnd' + ')');
break;
default:
}
};
/**
* Returns the all the styles from classDef statements in the graph definition.
*
* @param text
* @param diagObj
* @returns {object} ClassDef styles
*/
export const getClasses = function (text, diagObj) {
log.info('Extracting classes');
diagObj.db.clear();
try {
// Parse the graph definition
diagObj.parse(text);
return diagObj.db.getClasses();
} catch (e) {
return;
}
};
const addSubGraphs = function (cy, db) {
const parentLookUpDb = {};
const subgraphs = db.getSubGraphs();
subgraphs.forEach(function (subgraph) {
parentLookUpDb[subgraph.id] = subgraph.parent;
});
subgraphs.forEach(function (subgraph) {
cy.add({
group: 'nodes',
data: { id: subgraph.id, parent: parentLookUpDb[subgraph.id], classes: 'flowchart-subgraph' },
});
});
return parentLookUpDb;
};
const insertEdge = function (edgesEl, edge, edgeData, bounds, diagObj) {
const src = edge.sourceEndpoint();
const segments = edge.segmentPoints();
// const dest = edge.target().position();
const dest = edge.targetEndpoint();
const segPoints = segments.map((segment) => [segment.x, segment.y]);
const points = [
[src.x, src.y],
[segments[0].x, segments[0].y],
[dest.x, dest.y],
];
// console.log('Edge ctrl points:', edge.segmentPoints(), 'Bounds:', bounds, edge.source(), points);
// console.log('Edge ctrl points:', points);
const curve = line().curve(curveCardinal);
const edge2 = edgesEl
.insert('path')
.attr('d', curve(points))
.attr('class', 'path')
.attr('fill', 'none');
addmarkers(edge2, edgeData, diagObj.type, diagObj.arrowMarkerAbsolute);
// edgesEl
// .append('circle')
// .style('stroke', 'red')
// .style('fill', 'red')
// .attr('r', 1)
// .attr('cx', src.x)
// .attr('cy', src.y);
// edgesEl
// .append('circle')
// .style('stroke', 'white')
// .style('fill', 'white')
// .attr('r', 1)
// .attr('cx', segments[0].x)
// .attr('cy', segments[0].y);
// edgesEl
// .append('circle')
// .style('stroke', 'pink')
// .style('fill', 'pink')
// .attr('r', 1)
// .attr('cx', dest.x)
// .attr('cy', dest.y);
};
/**
* Draws a flowchart in the tag with id: id based on the graph definition in text.
*
* @param text
* @param id
*/
export const draw = function (text, id, _version, diagObj) {
// Add temporary render element
return new Promise(function (resolve, reject) {
const renderEl = select('body').append('div').attr('style', 'height:400px').attr('id', 'cy');
// .attr('style', 'display:none')
const cy = cytoscape({
styleEnabled: true,
// animate: false,
// ready: function () {
// log.info('Ready', this);
// },
container: document.getElementById('cy'), // container to render in
elements: [],
style: [
{
selector: 'edge',
style: {
'curve-style': 'segments',
// 'curve-style': 'bezier',
// 'segment-weights': '0.5',
// 'segment-distances': '0',
'edge-distances': 'node-position',
// 'source-endpoint': '180deg',
// 'target-endpoint': '0deg',
},
// 'edge-distance': 'intersection',
},
// {
// selector: 'node',
// style: {
// width: 70,
// height: 100,
// },
// },
],
});
log.info('Drawing flowchart using v3 renderer');
// Fetch the default direction, use TD if none was found
let dir = diagObj.db.getDirection();
if (dir === undefined) {
dir = 'TD';
}
const { securityLevel, flowchart: conf } = getConfig();
// Handle root and document for when rendering in sandbox mode
let sandboxElement;
if (securityLevel === 'sandbox') {
sandboxElement = select('#i' + id);
}
const root =
securityLevel === 'sandbox'
? select(sandboxElement.nodes()[0].contentDocument.body)
: select('body');
const doc = securityLevel === 'sandbox' ? sandboxElement.nodes()[0].contentDocument : document;
const svg = root.select(`[id="${id}"]`);
const markers = ['point', 'circle', 'cross'];
insertMarkers(svg, markers, diagObj.type, diagObj.arrowMarkerAbsolute);
// Fetch the vertices/nodes and edges/links from the parsed graph definition
const vert = diagObj.db.getVertices();
const parentLookUpDb = addSubGraphs(cy, diagObj.db);
addVertices(vert, cy, id, root, doc, diagObj, parentLookUpDb);
const edgesEl = svg.insert('g').attr('class', 'edges edgePath');
const edges = diagObj.db.getEdges();
addEdges(edges, cy, diagObj);
// c.style();
// Make cytoscape care about the dimensions of the nodes
cy.nodes().forEach(function (n) {
const boundingBox = n.data().boundingBox;
if (boundingBox) {
n.style('width', boundingBox.width);
n.style('height', boundingBox.height);
}
n.style('shape', 'square');
n.layoutDimensions = () => {
// console.log('Node dimensions', boundingBox.width, boundingBox.height);
if (boundingBox) {
return { w: boundingBox.width, h: boundingBox.height };
}
// return { w: boundingBox.width, h: boundingBox.height };
// const data = n.data();
// return { w: data.width, h: data.height };
return { w: 206, h: 160 };
};
});
cy.layout({
// name: 'grid',
name: 'preset',
// name: 'cose',
// name: 'circle',
// name: 'concentric',
headless: true,
styleEnabled: false,
animate: false,
}).run();
// log.info('Positions', cy.nodes().positions());
window.cy = cy;
cy.ready((e) => {
log.info('Ready', e);
// setTimeout(() => {
cy.nodes().map((node, id) => {
const data = node.data();
log.info(
'Position: (',
node.position().x,
', ',
node.position().y,
')',
data,
cy.elements()[0].renderedBoundingBox()
);
if (data.el) {
data.el.attr('transform', `translate(${node.position().x}, ${node.position().y})`);
// document
// .querySelector(`[id="${data.domId}"]`)
// .setAttribute('transform', `translate(${node.position().x}, ${node.position().y})`);
log.info('Id = ', data.domId, svg.select(`[id="${data.domId}"]`), data.el.node());
}
// else {
// // console.log('No element found for node', data, node.position(), node.size());
// }
});
cy.edges().map((edge, id) => {
const data = edge.data();
if (edge[0]._private.bodyBounds) {
const bounds = edge[0]._private.rscratch;
insertEdge(edgesEl, edge, data.edgeData, bounds, diagObj);
}
});
log.info(cy.json());
setupGraphViewbox({}, svg, conf.diagramPadding, conf.useMaxWidth);
// Remove element after layout
// renderEl.remove();
resolve();
// }, 500);
});
});
};
export default {
// setConf,
// addVertices,
// addEdges,
getClasses,
draw,
};

View File

@@ -0,0 +1,56 @@
const warning = (s: string) => {
// Todo remove debug code
// eslint-disable-next-line no-console
console.error('Log function was called before initialization', s);
};
export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
export const LEVELS: Record<LogLevel, number> = {
trace: 0,
debug: 1,
info: 2,
warn: 3,
error: 4,
fatal: 5,
};
export const log: Record<keyof typeof LEVELS, typeof console.log> = {
trace: warning,
debug: warning,
info: warning,
warn: warning,
error: warning,
fatal: warning,
};
export let setLogLevel: (level: keyof typeof LEVELS | number | string) => void;
export let getConfig: () => object;
export let sanitizeText: (str: string) => string;
// eslint-disable @typescript-eslint/no-explicit-any
export let setupGraphViewbox: (
graph: any,
svgElem: any,
padding: any,
useMaxWidth: boolean
) => void;
export const injectUtils = (
_log: Record<keyof typeof LEVELS, typeof console.log>,
_setLogLevel: any,
_getConfig: any,
_sanitizeText: any,
_setupGraphViewbox: any
) => {
_log.info('Mermaid utils injected');
log.trace = _log.trace;
log.debug = _log.debug;
log.info = _log.info;
log.warn = _log.warn;
log.error = _log.error;
log.fatal = _log.fatal;
setLogLevel = _setLogLevel;
getConfig = _getConfig;
sanitizeText = _sanitizeText;
setupGraphViewbox = _setupGraphViewbox;
};

View File

@@ -0,0 +1,114 @@
/** Returns the styles given options */
export interface FlowChartStyleOptions {
arrowheadColor: string;
border2: string;
clusterBkg: string;
clusterBorder: string;
edgeLabelBackground: string;
fontFamily: string;
lineColor: string;
mainBkg: string;
nodeBorder: string;
nodeTextColor: string;
tertiaryColor: string;
textColor: string;
titleColor: string;
}
const getStyles = (options: FlowChartStyleOptions) =>
`.label {
font-family: ${options.fontFamily};
color: ${options.nodeTextColor || options.textColor};
}
.cluster-label text {
fill: ${options.titleColor};
}
.cluster-label span {
color: ${options.titleColor};
}
.label text,span {
fill: ${options.nodeTextColor || options.textColor};
color: ${options.nodeTextColor || options.textColor};
}
.node rect,
.node circle,
.node ellipse,
.node polygon,
.node path {
fill: ${options.mainBkg};
stroke: ${options.nodeBorder};
stroke-width: 1px;
}
.node .label {
text-align: center;
}
.node.clickable {
cursor: pointer;
}
.arrowheadPath {
fill: ${options.arrowheadColor};
}
.edgePath .path {
stroke: ${options.lineColor};
stroke-width: 2.0px;
}
.flowchart-link {
stroke: ${options.lineColor};
fill: none;
}
.edgeLabel {
background-color: ${options.edgeLabelBackground};
rect {
opacity: 0.5;
background-color: ${options.edgeLabelBackground};
fill: ${options.edgeLabelBackground};
}
text-align: center;
}
.cluster rect {
fill: ${options.clusterBkg};
stroke: ${options.clusterBorder};
stroke-width: 1px;
}
.cluster text {
fill: ${options.titleColor};
}
.cluster span {
color: ${options.titleColor};
}
/* .cluster div {
color: ${options.titleColor};
} */
div.mermaidTooltip {
position: absolute;
text-align: center;
max-width: 200px;
padding: 2px;
font-family: ${options.fontFamily};
font-size: 12px;
background: ${options.tertiaryColor};
border: 1px solid ${options.border2};
border-radius: 2px;
pointer-events: none;
z-index: 100;
}
.flowchartTitleText {
text-anchor: middle;
font-size: 18px;
fill: ${options.textColor};
}
`;
export default getStyles;

View File

@@ -1064,6 +1064,7 @@ export const insertNode = (elem, node, dir) => {
if (node.haveCallback) {
nodeElems[node.id].attr('class', nodeElems[node.id].attr('class') + ' clickable');
}
return newEl;
};
export const setNodeElem = (elem, node) => {
nodeElems[node.id] = elem;

View File

@@ -684,7 +684,7 @@ const destructEndLink = (_str) => {
return { type, stroke, length };
};
const destructLink = (_str, _startStr) => {
export const destructLink = (_str, _startStr) => {
const info = destructEndLink(_str);
let startInfo;
if (_startStr) {
@@ -744,6 +744,9 @@ const makeUniq = (sg, allSubgraphs) => {
return { nodes: res };
};
export const lex = {
firstGraph,
};
export default {
parseDirective,
defaultConfig: () => configApi.defaultConfig.flowchart,
@@ -776,9 +779,7 @@ export default {
indexNodes,
getSubGraphs,
destructLink,
lex: {
firstGraph,
},
lex,
exists,
makeUniq,
setDiagramTitle,

View File

@@ -82,6 +82,7 @@ that id.
<click>[\s\n] this.popState();
<click>[^\s\n]* return 'CLICK';
"cyto" {if(yy.lex.firstGraph()){this.begin("dir");} return 'GRAPH';}
"graph" {if(yy.lex.firstGraph()){this.begin("dir");} return 'GRAPH';}
"flowchart" {if(yy.lex.firstGraph()){this.begin("dir");} return 'GRAPH';}
"subgraph" return 'subgraph';

60
pnpm-lock.yaml generated
View File

@@ -300,6 +300,46 @@ importers:
specifier: ^3.0.2
version: 3.0.2
packages/mermaid-flowchart-v3:
dependencies:
'@braintree/sanitize-url':
specifier: ^6.0.0
version: 6.0.0
cytoscape:
specifier: ^3.23.0
version: 3.23.0
cytoscape-cose-bilkent:
specifier: ^4.1.0
version: 4.1.0_cytoscape@3.23.0
cytoscape-fcose:
specifier: ^2.1.0
version: 2.1.0_cytoscape@3.23.0
d3:
specifier: ^7.0.0
version: 7.6.1
dagre-d3-es:
specifier: 7.0.4
version: 7.0.4
graphlib:
specifier: ^2.1.0
version: 2.1.8
khroma:
specifier: ^2.0.0
version: 2.0.0
non-layered-tidy-tree-layout:
specifier: ^2.0.2
version: 2.0.2
devDependencies:
concurrently:
specifier: ^7.5.0
version: 7.5.0
mermaid:
specifier: workspace:*
version: link:../mermaid
rimraf:
specifier: ^3.0.2
version: 3.0.2
packages/mermaid-mindmap:
dependencies:
'@braintree/sanitize-url':
@@ -3538,7 +3578,7 @@ packages:
/axios/0.21.4_debug@4.3.2:
resolution: {integrity: sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==}
dependencies:
follow-redirects: 1.15.2_debug@4.3.2
follow-redirects: 1.15.2
transitivePeerDependencies:
- debug
dev: true
@@ -6171,18 +6211,6 @@ packages:
optional: true
dev: true
/follow-redirects/1.15.2_debug@4.3.2:
resolution: {integrity: sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==}
engines: {node: '>=4.0'}
peerDependencies:
debug: '*'
peerDependenciesMeta:
debug:
optional: true
dependencies:
debug: 4.3.2
dev: true
/foreground-child/2.0.0:
resolution: {integrity: sha512-dCIq9FpEcyQyXKCkyzmlPTFNgrCzPudOe+mhvJU5zAtlBnGVy2yKxtfsxK2tQBThwq225jcvBjpw1Gr40uzZCA==}
engines: {node: '>=8.0.0'}
@@ -6518,6 +6546,12 @@ packages:
resolution: {integrity: sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==}
dev: true
/graphlib/2.1.8:
resolution: {integrity: sha512-jcLLfkpoVGmH7/InMC/1hIvOPSUh38oJtGhvrOFGzioE1DZ+0YW16RgmOJhHiuWTvGiJQ9Z1Ik43JvkRPRvE+A==}
dependencies:
lodash: 4.17.21
dev: false
/handle-thing/2.0.1:
resolution: {integrity: sha512-9Qn4yBxelxoh2Ow62nP+Ka/kMnOXRi8BXnRaUwezLNhqelnN49xKz4F/dPP8OYLxLxq6JDtZb2i9XznUQbNPTg==}
dev: true