graphHelper.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import * as dagre from "dagre";
  2. import { DiagramModel } from 'storm-react-diagrams/dist/@types/src/models/DiagramModel';
  3. export class GraphHelper {
  4. public static DistributeGraph(model: DiagramModel) {
  5. let nodes = this._MapElements(model);
  6. let edges = this._MapEdges(model);
  7. let graph = new dagre.graphlib.Graph();
  8. graph.setGraph({});
  9. graph.setDefaultEdgeLabel(() => ({}));
  10. graph.graph().rankdir = "LR";
  11. //add elements to dagre graph
  12. nodes.forEach(node => {
  13. graph.setNode(node.id, node.metadata);
  14. });
  15. edges.forEach(edge => {
  16. if (edge.from && edge.to) {
  17. graph.setEdge(edge.from.id, edge.to.id);
  18. }
  19. });
  20. //auto-distribute
  21. dagre.layout(graph);
  22. return graph.nodes().map(node => graph.node(node));
  23. }
  24. private static _MapElements(model: DiagramModel) {
  25. let output = [];
  26. // dagre compatible format
  27. for (var nodeName in model.nodes) {
  28. let node = model.nodes[nodeName];
  29. let size = {
  30. width: node.width | 200,
  31. height: node.height | 100
  32. };
  33. output.push({ id: node.id, metadata: { ...size, id: node.id } });
  34. }
  35. return output;
  36. }
  37. private static _MapEdges(model: DiagramModel) {
  38. // returns links which connects nodes
  39. // we check are there both from and to nodes in the model. Sometimes links can be detached
  40. let output = [];
  41. for (var linkName in model.links) {
  42. let link = model.links[linkName];
  43. output.push({
  44. from: link.sourcePort!.parent,
  45. to: link.targetPort!.parent
  46. });
  47. }
  48. return output;
  49. }
  50. }