diff --git a/README.md b/README.md index 8ca6937c..64579c52 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,10 @@ var defaults = { boundingBox: undefined, // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h } transform: function( node, pos ){ return pos; }, // a function that applies a transform to the final node position ready: function(){}, // on layoutready + sort: undefined, // a sorting function to order the nodes and edges; e.g. function(a, b){ return a.data('weight') - b.data('weight') } + // because cytoscape dagre creates a directed graph, and directed graphs use the node order as a tie breaker when + // defining the topology of a graph, this sort function can help ensure the correct order of the nodes/edges. + // this feature is most useful when adding and removing the same nodes and edges multiple times in a graph. stop: function(){} // on layoutstop }; ``` diff --git a/src/defaults.js b/src/defaults.js index 106137d1..19af45c2 100644 --- a/src/defaults.js +++ b/src/defaults.js @@ -24,6 +24,10 @@ let defaults = { boundingBox: undefined, // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h } transform: function( node, pos ){ return pos; }, // a function that applies a transform to the final node position ready: function(){}, // on layoutready + sort: undefined, // a sorting function to order the nodes and edges; e.g. function(a, b){ return a.data('weight') - b.data('weight') } + // because cytoscape dagre creates a directed graph, and directed graphs use the node order as a tie breaker when + // defining the topology of a graph, this sort function can help ensure the correct order of the nodes/edges. + // this feature is most useful when adding and removing the same nodes and edges multiple times in a graph. stop: function(){} // on layoutstop }; diff --git a/src/layout.js b/src/layout.js index 79ed913a..7bf82561 100644 --- a/src/layout.js +++ b/src/layout.js @@ -54,6 +54,11 @@ DagreLayout.prototype.run = function(){ // add nodes to dagre let nodes = eles.nodes(); + + if ( isFunction(options.sort) ) { + nodes = nodes.sort( options.sort ); + } + for( let i = 0; i < nodes.length; i++ ){ let node = nodes[i]; let nbb = node.layoutDimensions( options ); @@ -80,6 +85,11 @@ DagreLayout.prototype.run = function(){ let edges = eles.edges().stdFilter(function( edge ){ return !edge.source().isParent() && !edge.target().isParent(); // dagre can't handle edges on compound nodes }); + + if ( isFunction(options.sort) ) { + edges = edges.sort( options.sort ); + } + for( let i = 0; i < edges.length; i++ ){ let edge = edges[i];