mirror of
https://github.com/mermaid-js/mermaid.git
synced 2025-09-25 02:09:50 +02:00
Adding new flowchart renderer using elk
This commit is contained in:
@@ -3,14 +3,19 @@ import { select, line, curveLinear, curveCardinal, curveBasis, selectAll } from
|
||||
import { log, getConfig, setupGraphViewbox } from './mermaidUtils';
|
||||
import { insertNode } from '../../mermaid/src/dagre-wrapper/nodes.js';
|
||||
import insertMarkers from '../../mermaid/src/dagre-wrapper/markers.js';
|
||||
|
||||
import dagre from 'cytoscape-dagre';
|
||||
// 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';
|
||||
// import ELK from 'elkjs/lib/elk-api';
|
||||
// const elk = new ELK({
|
||||
// workerUrl: './elk-worker.min.js',
|
||||
// });
|
||||
import ELK from 'elkjs/lib/elk.bundled.js';
|
||||
const elk = new ELK();
|
||||
|
||||
const conf = {};
|
||||
export const setConf = function (cnf) {
|
||||
@@ -20,6 +25,8 @@ export const setConf = function (cnf) {
|
||||
}
|
||||
};
|
||||
|
||||
const nodeDb = {};
|
||||
|
||||
// /**
|
||||
// * Function that adds the vertices found during parsing to the graph to be rendered.
|
||||
// *
|
||||
@@ -30,7 +37,7 @@ export const setConf = function (cnf) {
|
||||
// * @param doc
|
||||
// * @param diagObj
|
||||
// */
|
||||
export const addVertices = function (vert, cy, svgId, root, doc, diagObj, parentLookUpDb) {
|
||||
export const addVertices = function (vert, svgId, root, doc, diagObj, parentLookUpDb, graph) {
|
||||
const svg = root.select(`[id="${svgId}"]`);
|
||||
const nodes = svg.insert('g').attr('class', 'nodes');
|
||||
const keys = Object.keys(vert);
|
||||
@@ -165,33 +172,36 @@ export const addVertices = function (vert, cy, svgId, root, doc, diagObj, parent
|
||||
};
|
||||
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],
|
||||
},
|
||||
const 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: boundingBox.width,
|
||||
height: boundingBox.height,
|
||||
dir: vertex.dir,
|
||||
type: vertex.type,
|
||||
props: vertex.props,
|
||||
padding: getConfig().flowchart.padding,
|
||||
boundingBox,
|
||||
el: nodeEl,
|
||||
parent: parentLookUpDb.parentById[vertex.id],
|
||||
};
|
||||
// if (!Object.keys(parentLookUpDb.childrenById).includes(vertex.id)) {
|
||||
graph.children.push({
|
||||
...data,
|
||||
});
|
||||
|
||||
// }
|
||||
nodeDb[node.id] = data;
|
||||
log.trace('setNode', {
|
||||
labelStyle: styles.labelStyle,
|
||||
shape: _shape,
|
||||
@@ -207,9 +217,10 @@ export const addVertices = function (vert, cy, svgId, root, doc, diagObj, parent
|
||||
dir: vertex.dir,
|
||||
props: vertex.props,
|
||||
padding: getConfig().flowchart.padding,
|
||||
parent: parentLookUpDb[vertex.id],
|
||||
parent: parentLookUpDb.parentById[vertex.id],
|
||||
});
|
||||
});
|
||||
return graph;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -219,8 +230,9 @@ export const addVertices = function (vert, cy, svgId, root, doc, diagObj, parent
|
||||
* @param {object} g The graph object
|
||||
* @param cy
|
||||
* @param diagObj
|
||||
* @param graph
|
||||
*/
|
||||
export const addEdges = function (edges, cy, diagObj) {
|
||||
export const addEdges = function (edges, diagObj, graph) {
|
||||
// log.info('abc78 edges = ', edges);
|
||||
let cnt = 0;
|
||||
let linkIdCnt = {};
|
||||
@@ -351,8 +363,16 @@ export const addEdges = function (edges, cy, diagObj) {
|
||||
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 } });
|
||||
graph.edges.push({
|
||||
id: 'e' + edge.start + edge.end,
|
||||
sources: [edge.start],
|
||||
targets: [edge.end],
|
||||
edgeData,
|
||||
targetPort: 'PortSide.NORTH',
|
||||
// id: cnt,
|
||||
});
|
||||
});
|
||||
return graph;
|
||||
};
|
||||
|
||||
const addmarkers = function (svgPath, edgeData, diagramType, arrowMarkerAbsolute) {
|
||||
@@ -439,7 +459,7 @@ const addmarkers = function (svgPath, edgeData, diagramType, arrowMarkerAbsolute
|
||||
*/
|
||||
export const getClasses = function (text, diagObj) {
|
||||
log.info('Extracting classes');
|
||||
diagObj.db.clear();
|
||||
diagObj.db.clear('ver-2');
|
||||
try {
|
||||
// Parse the graph definition
|
||||
diagObj.parse(text);
|
||||
@@ -449,40 +469,49 @@ export const getClasses = function (text, diagObj) {
|
||||
}
|
||||
};
|
||||
|
||||
const addSubGraphs = function (cy, db) {
|
||||
const parentLookUpDb = {};
|
||||
const addSubGraphs = function (db) {
|
||||
const parentLookUpDb = { parentById: {}, childrenById: {} };
|
||||
const subgraphs = db.getSubGraphs();
|
||||
|
||||
log.info('Subgraphs - ', subgraphs);
|
||||
subgraphs.forEach(function (subgraph) {
|
||||
parentLookUpDb[subgraph.id] = subgraph.parent;
|
||||
subgraph.nodes.forEach(function (node) {
|
||||
parentLookUpDb.parentById[node] = subgraph.id;
|
||||
if (parentLookUpDb.childrenById[subgraph.id] === undefined) {
|
||||
parentLookUpDb.childrenById[subgraph.id] = [];
|
||||
}
|
||||
parentLookUpDb.childrenById[subgraph.id].push(node);
|
||||
});
|
||||
});
|
||||
|
||||
subgraphs.forEach(function (subgraph) {
|
||||
cy.add({
|
||||
group: 'nodes',
|
||||
data: { id: subgraph.id, parent: parentLookUpDb[subgraph.id], classes: 'flowchart-subgraph' },
|
||||
});
|
||||
const data = { id: subgraph.id };
|
||||
if (parentLookUpDb.parentById[subgraph.id] !== undefined) {
|
||||
data.parent = parentLookUpDb.parentById[subgraph.id];
|
||||
}
|
||||
// cy.add({
|
||||
// group: 'nodes',
|
||||
// data,
|
||||
// });
|
||||
});
|
||||
return parentLookUpDb;
|
||||
};
|
||||
|
||||
const insertEdge = function (edgesEl, edge, edgeData, bounds, diagObj) {
|
||||
const src = edge.sourceEndpoint();
|
||||
const segments = edge.segmentPoints();
|
||||
const insertEdge = function (edgesEl, edge, edgeData, diagObj) {
|
||||
const src = edge.sections[0].startPoint;
|
||||
const dest = edge.sections[0].endPoint;
|
||||
const segments = edge.sections[0].bendPoints ? edge.sections[0].bendPoints : [];
|
||||
// const dest = edge.target().position();
|
||||
const dest = edge.targetEndpoint();
|
||||
// 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],
|
||||
];
|
||||
const points = [[src.x, src.y], ...segPoints, [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 curve = line().curve(curveCardinal);
|
||||
const curve = line().curve(curveLinear);
|
||||
const edge2 = edgesEl
|
||||
.insert('path')
|
||||
.attr('d', curve(points))
|
||||
// .attr('d', points))
|
||||
.attr('class', 'path')
|
||||
.attr('fill', 'none');
|
||||
addmarkers(edge2, edgeData, diagObj.type, diagObj.arrowMarkerAbsolute);
|
||||
@@ -518,42 +547,31 @@ const insertEdge = function (edgesEl, edge, edgeData, bounds, diagObj) {
|
||||
|
||||
export const draw = function (text, id, _version, diagObj) {
|
||||
// Add temporary render element
|
||||
diagObj.db.clear();
|
||||
diagObj.db.setGen('gen-2');
|
||||
// Parse the graph definition
|
||||
diagObj.parser.parse(text);
|
||||
|
||||
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,
|
||||
// },
|
||||
// },
|
||||
],
|
||||
});
|
||||
let graph = {
|
||||
id: 'root',
|
||||
layoutOptions: {
|
||||
'elk.algorithm': 'layered',
|
||||
'elk.direction': 'DOWN',
|
||||
'elk.port.side': 'SOUTH',
|
||||
// 'nodePlacement.strategy': 'SIMPLE',
|
||||
'org.eclipse.elk.graphviz.concentrate': true,
|
||||
// 'org.eclipse.elk.spacing.nodeNode': 120,
|
||||
// 'org.eclipse.elk.spacing.edgeEdge': 120,
|
||||
// 'org.eclipse.elk.spacing.edgeNode': 120,
|
||||
// 'org.eclipse.elk.spacing.nodeEdge': 120,
|
||||
'org.eclipse.elk.spacing.componentComponent': 120,
|
||||
},
|
||||
children: [],
|
||||
edges: [],
|
||||
};
|
||||
log.info('Drawing flowchart using v3 renderer');
|
||||
// Fetch the default direction, use TD if none was found
|
||||
let dir = diagObj.db.getDirection();
|
||||
@@ -579,89 +597,45 @@ export const draw = function (text, id, _version, diagObj) {
|
||||
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);
|
||||
|
||||
let subG;
|
||||
const subGraphs = diagObj.db.getSubGraphs();
|
||||
log.info('Subgraphs - ', subGraphs);
|
||||
for (let i = subGraphs.length - 1; i >= 0; i--) {
|
||||
subG = subGraphs[i];
|
||||
log.info('Subgraph - ', subG);
|
||||
diagObj.db.addVertex(subG.id, subG.title, 'group', undefined, subG.classes, subG.dir);
|
||||
}
|
||||
|
||||
const parentLookUpDb = addSubGraphs(diagObj.db);
|
||||
graph = addVertices(vert, id, root, doc, diagObj, parentLookUpDb, graph);
|
||||
const edgesEl = svg.insert('g').attr('class', 'edges edgePath');
|
||||
const edges = diagObj.db.getEdges();
|
||||
addEdges(edges, cy, diagObj);
|
||||
graph = addEdges(edges, diagObj, graph);
|
||||
|
||||
// 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})`);
|
||||
elk.layout(graph).then(function (g) {
|
||||
g.children.forEach(function (node) {
|
||||
const data = nodeDb[node.id];
|
||||
if (data) {
|
||||
data.el.attr(
|
||||
'transform',
|
||||
`translate(${node.x + node.width / 2}, ${node.y + node.height / 2})`
|
||||
);
|
||||
// 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);
|
||||
}
|
||||
g.edges.map((edge, id) => {
|
||||
insertEdge(edgesEl, edge, edge.edgeData, diagObj);
|
||||
});
|
||||
|
||||
log.info(cy.json());
|
||||
setupGraphViewbox({}, svg, conf.diagramPadding, conf.useMaxWidth);
|
||||
// Remove element after layout
|
||||
// renderEl.remove();
|
||||
resolve();
|
||||
// }, 500);
|
||||
});
|
||||
// Remove element after layout
|
||||
// renderEl.remove();
|
||||
});
|
||||
};
|
||||
|
||||
|
Reference in New Issue
Block a user