Skip to content

Instantly share code, notes, and snippets.

@xc8tlik
Created May 6, 2014 14:50
Show Gist options
  • Save xc8tlik/ce7d9cdf601622b810d6 to your computer and use it in GitHub Desktop.
Save xc8tlik/ce7d9cdf601622b810d6 to your computer and use it in GitHub Desktop.
GraphViz/Sugiyama layout for Cytoscape.js using dagre
;(function($$){ 'use strict';
// default layout options
var defaults = {
ready: function(){}, // on layoutready
stop: function(){} // on layoutstop
};
// constructor
// options : object containing layout options
function DagreLayout( options ){
this.options = $$.util.extend(true, {}, defaults, options);
}
// runs the layout
DagreLayout.prototype.run = function(){
var options = this.options;
var cy = options.cy; // cy is automatically populated for us in the constructor
// Create a new directed graph
var g = new dagre.Digraph();
cy.nodes().each(function(j, node) {
g.addNode(node.id(), {
label: node.data('name'),
width: node.renderedOuterWidth(),
height: node.renderedOuterHeight()
});
console.log("Got node with id: " + node.id());
});
cy.edges().each(function(k, edge) {
g.addEdge(null, edge.source().id(), edge.target().id());
console.log("Got edge with source/target: " + edge.source().id() + "/" + edge.target().id());
});
// Next we can ask dagre to do the layout for these nodes and edges. This is done with the following code:
var layout = dagre.layout().run(g);
layout.eachNode(function(u, value) {
console.log("Node " + u + ": " + JSON.stringify(value));
cy.$("#" + u).position({
x: value.x,
y: value.y
});
});
// trigger layoutready when each node has had its position set at least once
cy.one('layoutready', options.ready);
cy.trigger('layoutready');
// trigger layoutstop when the layout stops (e.g. finishes)
cy.one('layoutstop', options.stop);
cy.trigger('layoutstop');
};
// called on continuous layouts to stop them before they finish
DagreLayout.prototype.stop = function(){
var options = this.options;
cy.one('layoutstop', options.stop);
cy.trigger('layoutstop');
};
// register the layout
$$('layout', 'dagre', DagreLayout);
})(cytoscape);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment