diff --git a/HISTORY.md b/HISTORY.md
index a6821ac5..4452c90e 100644
--- a/HISTORY.md
+++ b/HISTORY.md
@@ -9,7 +9,7 @@ http://visjs.org
- Renamed storePosition to storePositions. Added deprication message and old name still works.
- Worked around hammer.js bug with multiple release listeners.
- Improved cleaning up after manipulation toolbar.
-- Added getPositions() method to get the position of all nodes.
+- Added getPositions() method to get the position of all nodes or some of them if specific Ids are supplied.
- Added getCenterCoordinates() method to get the x and y position in canvas space of the center of the view.
- Fixed node label becoming undefined.
- Fixed cluster fontsize scaling.
diff --git a/dist/vis.js b/dist/vis.js
index 21c4b8d5..c5e66beb 100644
--- a/dist/vis.js
+++ b/dist/vis.js
@@ -5,7 +5,7 @@
* A dynamic, browser-based visualization library.
*
* @version 3.5.0
- * @date 2014-10-07
+ * @date 2014-10-08
*
* @license
* Copyright (C) 2011-2014 Almende B.V, http://almende.com
@@ -133,13 +133,13 @@ return /******/ (function(modules) { // webpackBootstrap
// Network
exports.Network = __webpack_require__(46);
exports.network = {
- Edge: __webpack_require__(52),
+ Edge: __webpack_require__(47),
Groups: __webpack_require__(49),
Images: __webpack_require__(50),
- Node: __webpack_require__(51),
- Popup: __webpack_require__(53),
- dotparser: __webpack_require__(47),
- gephiParser: __webpack_require__(48)
+ Node: __webpack_require__(48),
+ Popup: __webpack_require__(51),
+ dotparser: __webpack_require__(52),
+ gephiParser: __webpack_require__(53)
};
// Deprecated since v3.0.0
@@ -12361,17 +12361,6 @@ return /******/ (function(modules) { // webpackBootstrap
}
};
- function printObject(obj) {
- var str = ""
- for (var idx in obj) {
- if (obj.hasOwnProperty(idx)) {
- str += idx + ":" + obj[idx] + "
";
- }
-
- }
- return str;
- }
-
/**
* Helper function to calculate the center date for zooming
* @param {{x: Number, y: Number}} pointer
@@ -12434,7 +12423,6 @@ return /******/ (function(modules) { // webpackBootstrap
// calculate new start and end
var newStart = center + (this.start - center) * scale;
var newEnd = (center+hiddenDuration) + (this.end - (center+hiddenDuration)) * scale;
-
// snapping times away from hidden zones
this.startToFront = delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
this.endToFront = -delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
@@ -21934,13 +21922,13 @@ return /******/ (function(modules) { // webpackBootstrap
var hammerUtil = __webpack_require__(21);
var DataSet = __webpack_require__(7);
var DataView = __webpack_require__(8);
- var dotparser = __webpack_require__(47);
- var gephiParser = __webpack_require__(48);
+ var dotparser = __webpack_require__(52);
+ var gephiParser = __webpack_require__(53);
var Groups = __webpack_require__(49);
var Images = __webpack_require__(50);
- var Node = __webpack_require__(51);
- var Edge = __webpack_require__(52);
- var Popup = __webpack_require__(53);
+ var Node = __webpack_require__(48);
+ var Edge = __webpack_require__(47);
+ var Popup = __webpack_require__(51);
var MixinLoader = __webpack_require__(54);
var Activator = __webpack_require__(38);
var locales = __webpack_require__(65);
@@ -24213,14 +24201,32 @@ return /******/ (function(modules) { // webpackBootstrap
};
/**
- * Load the XY positions of the nodes into the dataset.
+ * Return the positions of the nodes.
*/
- Network.prototype.getPositions = function() {
+ Network.prototype.getPositions = function(ids) {
var dataArray = {};
- for (var nodeId in this.nodes) {
- if (this.nodes.hasOwnProperty(nodeId)) {
- var node = this.nodes[nodeId];
- dataArray[nodeId] = {x:Math.round(node.x),y:Math.round(node.y)};
+ if (ids !== undefined) {
+ if (Array.isArray(ids) == true) {
+ for (var i = 0; i < ids.length; i++) {
+ if (this.nodes[ids[i]] !== undefined) {
+ var node = this.nodes[ids[i]];
+ dataArray[ids[i]] = {x: Math.round(node.x), y: Math.round(node.y)};
+ }
+ }
+ }
+ else {
+ if (this.nodes[ids] !== undefined) {
+ var node = this.nodes[ids];
+ dataArray[ids] = {x: Math.round(node.x), y: Math.round(node.y)};
+ }
+ }
+ }
+ else {
+ for (var nodeId in this.nodes) {
+ if (this.nodes.hasOwnProperty(nodeId)) {
+ var node = this.nodes[nodeId];
+ dataArray[nodeId] = {x: Math.round(node.x), y: Math.round(node.y)};
+ }
}
}
return dataArray;
@@ -24443,7 +24449,6 @@ return /******/ (function(modules) { // webpackBootstrap
return this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight});
};
-
module.exports = Network;
@@ -24451,1048 +24456,1203 @@ return /******/ (function(modules) { // webpackBootstrap
/* 47 */
/***/ function(module, exports, __webpack_require__) {
+ var util = __webpack_require__(1);
+ var Node = __webpack_require__(48);
+
/**
- * Parse a text source containing data in DOT language into a JSON object.
- * The object contains two lists: one with nodes and one with edges.
- *
- * DOT language reference: http://www.graphviz.org/doc/info/lang.html
+ * @class Edge
*
- * @param {String} data Text containing a graph in DOT-notation
- * @return {Object} graph An object containing two parameters:
- * {Object[]} nodes
- * {Object[]} edges
+ * A edge connects two nodes
+ * @param {Object} properties Object with properties. Must contain
+ * At least properties from and to.
+ * Available properties: from (number),
+ * to (number), label (string, color (string),
+ * width (number), style (string),
+ * length (number), title (string)
+ * @param {Network} network A Network object, used to find and edge to
+ * nodes.
+ * @param {Object} constants An object with default values for
+ * example for the color
*/
- function parseDOT (data) {
- dot = data;
- return parseGraph();
- }
+ function Edge (properties, network, networkConstants) {
+ if (!network) {
+ throw "No network provided";
+ }
+ var fields = ['edges','physics'];
+ var constants = util.selectiveBridgeObject(fields,networkConstants);
+ this.options = constants.edges;
+ this.physics = constants.physics;
+ this.options['smoothCurves'] = networkConstants['smoothCurves'];
- // token types enumeration
- var TOKENTYPE = {
- NULL : 0,
- DELIMITER : 1,
- IDENTIFIER: 2,
- UNKNOWN : 3
- };
- // map with all delimiters
- var DELIMITERS = {
- '{': true,
- '}': true,
- '[': true,
- ']': true,
- ';': true,
- '=': true,
- ',': true,
+ this.network = network;
- '->': true,
- '--': true
- };
+ // initialize variables
+ this.id = undefined;
+ this.fromId = undefined;
+ this.toId = undefined;
+ this.title = undefined;
+ this.widthSelected = this.options.width * this.options.widthSelectionMultiplier;
+ this.value = undefined;
+ this.selected = false;
+ this.hover = false;
+ this.labelDimensions = {top:0,left:0,width:0,height:0,yLine:0}; // could be cached
+ this.dirtyLabel = true;
- var dot = ''; // current dot file
- var index = 0; // current index in dot file
- var c = ''; // current token character in expr
- var token = ''; // current token
- var tokenType = TOKENTYPE.NULL; // type of the token
+ this.from = null; // a node
+ this.to = null; // a node
+ this.via = null; // a temp node
- /**
- * Get the first character from the dot file.
- * The character is stored into the char c. If the end of the dot file is
- * reached, the function puts an empty string in c.
- */
- function first() {
- index = 0;
- c = dot.charAt(0);
- }
+ // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
+ // by storing the original information we can revert to the original connection when the cluser is opened.
+ this.originalFromId = [];
+ this.originalToId = [];
- /**
- * Get the next character from the dot file.
- * The character is stored into the char c. If the end of the dot file is
- * reached, the function puts an empty string in c.
- */
- function next() {
- index++;
- c = dot.charAt(index);
- }
+ this.connected = false;
- /**
- * Preview the next character from the dot file.
- * @return {String} cNext
- */
- function nextPreview() {
- return dot.charAt(index + 1);
- }
+ this.widthFixed = false;
+ this.lengthFixed = false;
- /**
- * Test whether given character is alphabetic or numeric
- * @param {String} c
- * @return {Boolean} isAlphaNumeric
- */
- var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
- function isAlphaNumeric(c) {
- return regexAlphaNumeric.test(c);
+ this.setProperties(properties);
+
+ this.controlNodesEnabled = false;
+ this.controlNodes = {from:null, to:null, positions:{}};
+ this.connectedNode = null;
}
/**
- * Merge all properties of object b into object b
- * @param {Object} a
- * @param {Object} b
- * @return {Object} a
+ * Set or overwrite properties for the edge
+ * @param {Object} properties an object with properties
+ * @param {Object} constants and object with default, global properties
*/
- function merge (a, b) {
- if (!a) {
- a = {};
+ Edge.prototype.setProperties = function(properties) {
+ if (!properties) {
+ return;
}
- if (b) {
- for (var name in b) {
- if (b.hasOwnProperty(name)) {
- a[name] = b[name];
- }
+ var fields = ['style','fontSize','fontFace','fontColor','fontFill','width',
+ 'widthSelectionMultiplier','hoverWidth','arrowScaleFactor','dash','inheritColor'
+ ];
+ util.selectiveDeepExtend(fields, this.options, properties);
+
+ if (properties.from !== undefined) {this.fromId = properties.from;}
+ if (properties.to !== undefined) {this.toId = properties.to;}
+
+ if (properties.id !== undefined) {this.id = properties.id;}
+ if (properties.label !== undefined) {this.label = properties.label; this.dirtyLabel = true;}
+
+ if (properties.title !== undefined) {this.title = properties.title;}
+ if (properties.value !== undefined) {this.value = properties.value;}
+ if (properties.length !== undefined) {this.physics.springLength = properties.length;}
+
+ if (properties.color !== undefined) {
+ this.options.inheritColor = false;
+ if (util.isString(properties.color)) {
+ this.options.color.color = properties.color;
+ this.options.color.highlight = properties.color;
+ }
+ else {
+ if (properties.color.color !== undefined) {this.options.color.color = properties.color.color;}
+ if (properties.color.highlight !== undefined) {this.options.color.highlight = properties.color.highlight;}
+ if (properties.color.hover !== undefined) {this.options.color.hover = properties.color.hover;}
}
}
- return a;
- }
+
+ // A node is connected when it has a from and to node.
+ this.connect();
+
+ this.widthFixed = this.widthFixed || (properties.width !== undefined);
+ this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
+
+ this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
+
+ // set draw method based on style
+ switch (this.options.style) {
+ case 'line': this.draw = this._drawLine; break;
+ case 'arrow': this.draw = this._drawArrow; break;
+ case 'arrow-center': this.draw = this._drawArrowCenter; break;
+ case 'dash-line': this.draw = this._drawDashLine; break;
+ default: this.draw = this._drawLine; break;
+ }
+ };
/**
- * Set a value in an object, where the provided parameter name can be a
- * path with nested parameters. For example:
- *
- * var obj = {a: 2};
- * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
- *
- * @param {Object} obj
- * @param {String} path A parameter name or dot-separated parameter path,
- * like "color.highlight.border".
- * @param {*} value
+ * Connect an edge to its nodes
*/
- function setValue(obj, path, value) {
- var keys = path.split('.');
- var o = obj;
- while (keys.length) {
- var key = keys.shift();
- if (keys.length) {
- // this isn't the end point
- if (!o[key]) {
- o[key] = {};
- }
- o = o[key];
+ Edge.prototype.connect = function () {
+ this.disconnect();
+
+ this.from = this.network.nodes[this.fromId] || null;
+ this.to = this.network.nodes[this.toId] || null;
+ this.connected = (this.from && this.to);
+
+ if (this.connected) {
+ this.from.attachEdge(this);
+ this.to.attachEdge(this);
+ }
+ else {
+ if (this.from) {
+ this.from.detachEdge(this);
}
- else {
- // this is the end point
- o[key] = value;
+ if (this.to) {
+ this.to.detachEdge(this);
}
}
- }
+ };
/**
- * Add a node to a graph object. If there is already a node with
- * the same id, their attributes will be merged.
- * @param {Object} graph
- * @param {Object} node
+ * Disconnect an edge from its nodes
*/
- function addNode(graph, node) {
- var i, len;
- var current = null;
-
- // find root graph (in case of subgraph)
- var graphs = [graph]; // list with all graphs from current graph to root graph
- var root = graph;
- while (root.parent) {
- graphs.push(root.parent);
- root = root.parent;
+ Edge.prototype.disconnect = function () {
+ if (this.from) {
+ this.from.detachEdge(this);
+ this.from = null;
}
-
- // find existing node (at root level) by its id
- if (root.nodes) {
- for (i = 0, len = root.nodes.length; i < len; i++) {
- if (node.id === root.nodes[i].id) {
- current = root.nodes[i];
- break;
- }
- }
+ if (this.to) {
+ this.to.detachEdge(this);
+ this.to = null;
}
- if (!current) {
- // this is a new node
- current = {
- id: node.id
- };
- if (graph.node) {
- // clone default attributes
- current.attr = merge(current.attr, graph.node);
- }
- }
+ this.connected = false;
+ };
- // add node to this (sub)graph and all its parent graphs
- for (i = graphs.length - 1; i >= 0; i--) {
- var g = graphs[i];
+ /**
+ * get the title of this edge.
+ * @return {string} title The title of the edge, or undefined when no title
+ * has been set.
+ */
+ Edge.prototype.getTitle = function() {
+ return typeof this.title === "function" ? this.title() : this.title;
+ };
- if (!g.nodes) {
- g.nodes = [];
- }
- if (g.nodes.indexOf(current) == -1) {
- g.nodes.push(current);
- }
- }
- // merge attributes
- if (node.attr) {
- current.attr = merge(current.attr, node.attr);
- }
- }
+ /**
+ * Retrieve the value of the edge. Can be undefined
+ * @return {Number} value
+ */
+ Edge.prototype.getValue = function() {
+ return this.value;
+ };
/**
- * Add an edge to a graph object
- * @param {Object} graph
- * @param {Object} edge
+ * Adjust the value range of the edge. The edge will adjust it's width
+ * based on its value.
+ * @param {Number} min
+ * @param {Number} max
*/
- function addEdge(graph, edge) {
- if (!graph.edges) {
- graph.edges = [];
- }
- graph.edges.push(edge);
- if (graph.edge) {
- var attr = merge({}, graph.edge); // clone default attributes
- edge.attr = merge(attr, edge.attr); // merge attributes
+ Edge.prototype.setValueRange = function(min, max) {
+ if (!this.widthFixed && this.value !== undefined) {
+ var scale = (this.options.widthMax - this.options.widthMin) / (max - min);
+ this.options.width= (this.value - min) * scale + this.options.widthMin;
+ this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
}
- }
+ };
/**
- * Create an edge to a graph object
- * @param {Object} graph
- * @param {String | Number | Object} from
- * @param {String | Number | Object} to
- * @param {String} type
- * @param {Object | null} attr
- * @return {Object} edge
+ * Redraw a edge
+ * Draw this edge in the given canvas
+ * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
+ * @param {CanvasRenderingContext2D} ctx
*/
- function createEdge(graph, from, to, type, attr) {
- var edge = {
- from: from,
- to: to,
- type: type
- };
+ Edge.prototype.draw = function(ctx) {
+ throw "Method draw not initialized in edge";
+ };
- if (graph.edge) {
- edge.attr = merge({}, graph.edge); // clone default attributes
+ /**
+ * Check if this object is overlapping with the provided object
+ * @param {Object} obj an object with parameters left, top
+ * @return {boolean} True if location is located on the edge
+ */
+ Edge.prototype.isOverlappingWith = function(obj) {
+ if (this.connected) {
+ var distMax = 10;
+ var xFrom = this.from.x;
+ var yFrom = this.from.y;
+ var xTo = this.to.x;
+ var yTo = this.to.y;
+ var xObj = obj.left;
+ var yObj = obj.top;
+
+ var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
+
+ return (dist < distMax);
}
- edge.attr = merge(edge.attr || {}, attr); // merge attributes
+ else {
+ return false
+ }
+ };
- return edge;
+ Edge.prototype._getColor = function() {
+ var colorObj = this.options.color;
+ if (this.options.inheritColor == "to") {
+ colorObj = {
+ highlight: this.to.options.color.highlight.border,
+ hover: this.to.options.color.hover.border,
+ color: this.to.options.color.border
+ };
+ }
+ else if (this.options.inheritColor == "from" || this.options.inheritColor == true) {
+ colorObj = {
+ highlight: this.from.options.color.highlight.border,
+ hover: this.from.options.color.hover.border,
+ color: this.from.options.color.border
+ };
+ }
+
+ if (this.selected == true) {return colorObj.highlight;}
+ else if (this.hover == true) {return colorObj.hover;}
+ else {return colorObj.color;}
}
+
/**
- * Get next token in the current dot file.
- * The token and token type are available as token and tokenType
+ * Redraw a edge as a line
+ * Draw this edge in the given canvas
+ * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
+ * @param {CanvasRenderingContext2D} ctx
+ * @private
*/
- function getToken() {
- tokenType = TOKENTYPE.NULL;
- token = '';
-
- // skip over whitespaces
- while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
- next();
- }
+ Edge.prototype._drawLine = function(ctx) {
+ // set style
+ ctx.strokeStyle = this._getColor();
+ ctx.lineWidth = this._getLineWidth();
- do {
- var isComment = false;
+ if (this.from != this.to) {
+ // draw line
+ var via = this._line(ctx);
- // skip comment
- if (c == '#') {
- // find the previous non-space character
- var i = index - 1;
- while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
- i--;
+ // draw label
+ var point;
+ if (this.label) {
+ if (this.options.smoothCurves.enabled == true && via != null) {
+ var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
+ var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
+ point = {x:midpointX, y:midpointY};
}
- if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
- // the # is at the start of a line, this is indeed a line comment
- while (c != '' && c != '\n') {
- next();
- }
- isComment = true;
+ else {
+ point = this._pointOnLine(0.5);
}
+ this._label(ctx, this.label, point.x, point.y);
}
- if (c == '/' && nextPreview() == '/') {
- // skip line comment
- while (c != '' && c != '\n') {
- next();
- }
- isComment = true;
+ }
+ else {
+ var x, y;
+ var radius = this.physics.springLength / 4;
+ var node = this.from;
+ if (!node.width) {
+ node.resize(ctx);
}
- if (c == '/' && nextPreview() == '*') {
- // skip block comment
- while (c != '') {
- if (c == '*' && nextPreview() == '/') {
- // end of block comment found. skip these last two characters
- next();
- next();
- break;
- }
- else {
- next();
- }
- }
- isComment = true;
+ if (node.width > node.height) {
+ x = node.x + node.width / 2;
+ y = node.y - radius;
}
-
- // skip over whitespaces
- while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
- next();
+ else {
+ x = node.x + radius;
+ y = node.y - node.height / 2;
}
+ this._circle(ctx, x, y, radius);
+ point = this._pointOnCircle(x, y, radius, 0.5);
+ this._label(ctx, this.label, point.x, point.y);
}
- while (isComment);
+ };
- // check for end of dot file
- if (c == '') {
- // token is still empty
- tokenType = TOKENTYPE.DELIMITER;
- return;
+ /**
+ * Get the line width of the edge. Depends on width and whether one of the
+ * connected nodes is selected.
+ * @return {Number} width
+ * @private
+ */
+ Edge.prototype._getLineWidth = function() {
+ if (this.selected == true) {
+ return Math.max(Math.min(this.widthSelected, this.options.widthMax), 0.3*this.networkScaleInv);
}
-
- // check for delimiters consisting of 2 characters
- var c2 = c + nextPreview();
- if (DELIMITERS[c2]) {
- tokenType = TOKENTYPE.DELIMITER;
- token = c2;
- next();
- next();
- return;
- }
-
- // check for delimiters consisting of 1 character
- if (DELIMITERS[c]) {
- tokenType = TOKENTYPE.DELIMITER;
- token = c;
- next();
- return;
+ else {
+ if (this.hover == true) {
+ return Math.max(Math.min(this.options.hoverWidth, this.options.widthMax), 0.3*this.networkScaleInv);
+ }
+ else {
+ return Math.max(this.options.width, 0.3*this.networkScaleInv);
+ }
}
+ };
- // check for an identifier (number or string)
- // TODO: more precise parsing of numbers/strings (and the port separator ':')
- if (isAlphaNumeric(c) || c == '-') {
- token += c;
- next();
+ Edge.prototype._getViaCoordinates = function () {
+ var xVia = null;
+ var yVia = null;
+ var factor = this.options.smoothCurves.roundness;
+ var type = this.options.smoothCurves.type;
- while (isAlphaNumeric(c)) {
- token += c;
- next();
+ var dx = Math.abs(this.from.x - this.to.x);
+ var dy = Math.abs(this.from.y - this.to.y);
+ if (type == 'discrete' || type == 'diagonalCross') {
+ if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
+ if (this.from.y > this.to.y) {
+ if (this.from.x < this.to.x) {
+ xVia = this.from.x + factor * dy;
+ yVia = this.from.y - factor * dy;
+ }
+ else if (this.from.x > this.to.x) {
+ xVia = this.from.x - factor * dy;
+ yVia = this.from.y - factor * dy;
+ }
+ }
+ else if (this.from.y < this.to.y) {
+ if (this.from.x < this.to.x) {
+ xVia = this.from.x + factor * dy;
+ yVia = this.from.y + factor * dy;
+ }
+ else if (this.from.x > this.to.x) {
+ xVia = this.from.x - factor * dy;
+ yVia = this.from.y + factor * dy;
+ }
+ }
+ if (type == "discrete") {
+ xVia = dx < factor * dy ? this.from.x : xVia;
+ }
}
- if (token == 'false') {
- token = false; // convert to boolean
+ else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
+ if (this.from.y > this.to.y) {
+ if (this.from.x < this.to.x) {
+ xVia = this.from.x + factor * dx;
+ yVia = this.from.y - factor * dx;
+ }
+ else if (this.from.x > this.to.x) {
+ xVia = this.from.x - factor * dx;
+ yVia = this.from.y - factor * dx;
+ }
+ }
+ else if (this.from.y < this.to.y) {
+ if (this.from.x < this.to.x) {
+ xVia = this.from.x + factor * dx;
+ yVia = this.from.y + factor * dx;
+ }
+ else if (this.from.x > this.to.x) {
+ xVia = this.from.x - factor * dx;
+ yVia = this.from.y + factor * dx;
+ }
+ }
+ if (type == "discrete") {
+ yVia = dy < factor * dx ? this.from.y : yVia;
+ }
}
- else if (token == 'true') {
- token = true; // convert to boolean
+ }
+ else if (type == "straightCross") {
+ if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { // up - down
+ xVia = this.from.x;
+ if (this.from.y < this.to.y) {
+ yVia = this.to.y - (1-factor) * dy;
+ }
+ else {
+ yVia = this.to.y + (1-factor) * dy;
+ }
}
- else if (!isNaN(Number(token))) {
- token = Number(token); // convert to number
+ else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { // left - right
+ if (this.from.x < this.to.x) {
+ xVia = this.to.x - (1-factor) * dx;
+ }
+ else {
+ xVia = this.to.x + (1-factor) * dx;
+ }
+ yVia = this.from.y;
}
- tokenType = TOKENTYPE.IDENTIFIER;
- return;
}
-
- // check for a string enclosed by double quotes
- if (c == '"') {
- next();
- while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
- token += c;
- if (c == '"') { // skip the escape character
- next();
+ else if (type == 'horizontal') {
+ if (this.from.x < this.to.x) {
+ xVia = this.to.x - (1-factor) * dx;
+ }
+ else {
+ xVia = this.to.x + (1-factor) * dx;
+ }
+ yVia = this.from.y;
+ }
+ else if (type == 'vertical') {
+ xVia = this.from.x;
+ if (this.from.y < this.to.y) {
+ yVia = this.to.y - (1-factor) * dy;
+ }
+ else {
+ yVia = this.to.y + (1-factor) * dy;
+ }
+ }
+ else { // continuous
+ if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
+ if (this.from.y > this.to.y) {
+ if (this.from.x < this.to.x) {
+ // console.log(1)
+ xVia = this.from.x + factor * dy;
+ yVia = this.from.y - factor * dy;
+ xVia = this.to.x < xVia ? this.to.x : xVia;
+ }
+ else if (this.from.x > this.to.x) {
+ // console.log(2)
+ xVia = this.from.x - factor * dy;
+ yVia = this.from.y - factor * dy;
+ xVia = this.to.x > xVia ? this.to.x :xVia;
+ }
+ }
+ else if (this.from.y < this.to.y) {
+ if (this.from.x < this.to.x) {
+ // console.log(3)
+ xVia = this.from.x + factor * dy;
+ yVia = this.from.y + factor * dy;
+ xVia = this.to.x < xVia ? this.to.x : xVia;
+ }
+ else if (this.from.x > this.to.x) {
+ // console.log(4, this.from.x, this.to.x)
+ xVia = this.from.x - factor * dy;
+ yVia = this.from.y + factor * dy;
+ xVia = this.to.x > xVia ? this.to.x : xVia;
+ }
}
- next();
}
- if (c != '"') {
- throw newSyntaxError('End of string " expected');
+ else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
+ if (this.from.y > this.to.y) {
+ if (this.from.x < this.to.x) {
+ // console.log(5)
+ xVia = this.from.x + factor * dx;
+ yVia = this.from.y - factor * dx;
+ yVia = this.to.y > yVia ? this.to.y : yVia;
+ }
+ else if (this.from.x > this.to.x) {
+ // console.log(6)
+ xVia = this.from.x - factor * dx;
+ yVia = this.from.y - factor * dx;
+ yVia = this.to.y > yVia ? this.to.y : yVia;
+ }
+ }
+ else if (this.from.y < this.to.y) {
+ if (this.from.x < this.to.x) {
+ // console.log(7)
+ xVia = this.from.x + factor * dx;
+ yVia = this.from.y + factor * dx;
+ yVia = this.to.y < yVia ? this.to.y : yVia;
+ }
+ else if (this.from.x > this.to.x) {
+ // console.log(8)
+ xVia = this.from.x - factor * dx;
+ yVia = this.from.y + factor * dx;
+ yVia = this.to.y < yVia ? this.to.y : yVia;
+ }
+ }
}
- next();
- tokenType = TOKENTYPE.IDENTIFIER;
- return;
}
- // something unknown is found, wrong characters, a syntax error
- tokenType = TOKENTYPE.UNKNOWN;
- while (c != '') {
- token += c;
- next();
- }
- throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
+
+ return {x:xVia, y:yVia};
}
/**
- * Parse a graph.
- * @returns {Object} graph
+ * Draw a line between two nodes
+ * @param {CanvasRenderingContext2D} ctx
+ * @private
*/
- function parseGraph() {
- var graph = {};
-
- first();
- getToken();
-
- // optional strict keyword
- if (token == 'strict') {
- graph.strict = true;
- getToken();
+ Edge.prototype._line = function (ctx) {
+ // draw a straight line
+ ctx.beginPath();
+ ctx.moveTo(this.from.x, this.from.y);
+ if (this.options.smoothCurves.enabled == true) {
+ if (this.options.smoothCurves.dynamic == false) {
+ var via = this._getViaCoordinates();
+ if (via.x == null) {
+ ctx.lineTo(this.to.x, this.to.y);
+ ctx.stroke();
+ return null;
+ }
+ else {
+ // this.via.x = via.x;
+ // this.via.y = via.y;
+ ctx.quadraticCurveTo(via.x,via.y,this.to.x, this.to.y);
+ ctx.stroke();
+ return via;
+ }
+ }
+ else {
+ ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
+ ctx.stroke();
+ return this.via;
+ }
}
-
- // graph or digraph keyword
- if (token == 'graph' || token == 'digraph') {
- graph.type = token;
- getToken();
+ else {
+ ctx.lineTo(this.to.x, this.to.y);
+ ctx.stroke();
+ return null;
}
+ };
- // optional graph id
- if (tokenType == TOKENTYPE.IDENTIFIER) {
- graph.id = token;
- getToken();
- }
+ /**
+ * Draw a line from a node to itself, a circle
+ * @param {CanvasRenderingContext2D} ctx
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} radius
+ * @private
+ */
+ Edge.prototype._circle = function (ctx, x, y, radius) {
+ // draw a circle
+ ctx.beginPath();
+ ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
+ ctx.stroke();
+ };
- // open angle bracket
- if (token != '{') {
- throw newSyntaxError('Angle bracket { expected');
- }
- getToken();
+ /**
+ * Draw label with white background and with the middle at (x, y)
+ * @param {CanvasRenderingContext2D} ctx
+ * @param {String} text
+ * @param {Number} x
+ * @param {Number} y
+ * @private
+ */
+ Edge.prototype._label = function (ctx, text, x, y) {
+ if (text) {
+ ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
+ this.options.fontSize + "px " + this.options.fontFace;
+ var yLine;
- // statements
- parseStatements(graph);
+ if (this.dirtyLabel == true) {
+ var lines = String(text).split('\n');
+ var lineCount = lines.length;
+ var fontSize = (Number(this.options.fontSize) + 4);
+ yLine = y + (1 - lineCount) / 2 * fontSize;
- // close angle bracket
- if (token != '}') {
- throw newSyntaxError('Angle bracket } expected');
- }
- getToken();
+ var width = ctx.measureText(lines[0]).width;
+ for (var i = 1; i < lineCount; i++) {
+ var lineWidth = ctx.measureText(lines[i]).width;
+ width = lineWidth > width ? lineWidth : width;
+ }
+ var height = this.options.fontSize * lineCount;
+ var left = x - width / 2;
+ var top = y - height / 2;
- // end of file
- if (token !== '') {
- throw newSyntaxError('End of file expected');
- }
- getToken();
+ // cache
+ this.labelDimensions = {top:top,left:left,width:width,height:height,yLine:yLine};
+ }
- // remove temporary default properties
- delete graph.node;
- delete graph.edge;
- delete graph.graph;
- return graph;
- }
+ if (this.options.fontFill !== undefined && this.options.fontFill !== null && this.options.fontFill !== "none") {
+ ctx.fillStyle = this.options.fontFill;
+ ctx.fillRect(this.labelDimensions.left,
+ this.labelDimensions.top,
+ this.labelDimensions.width,
+ this.labelDimensions.height);
+ }
- /**
- * Parse a list with statements.
- * @param {Object} graph
- */
- function parseStatements (graph) {
- while (token !== '' && token != '}') {
- parseStatement(graph);
- if (token == ';') {
- getToken();
+ // draw text
+ ctx.fillStyle = this.options.fontColor || "black";
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+ yLine = this.labelDimensions.yLine;
+ for (var i = 0; i < lineCount; i++) {
+ ctx.fillText(lines[i], x, yLine);
+ yLine += fontSize;
}
}
- }
+ };
/**
- * Parse a single statement. Can be a an attribute statement, node
- * statement, a series of node statements and edge statements, or a
- * parameter.
- * @param {Object} graph
+ * Redraw a edge as a dashed line
+ * Draw this edge in the given canvas
+ * @author David Jordan
+ * @date 2012-08-08
+ * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
+ * @param {CanvasRenderingContext2D} ctx
+ * @private
*/
- function parseStatement(graph) {
- // parse subgraph
- var subgraph = parseSubgraph(graph);
- if (subgraph) {
- // edge statements
- parseEdge(graph, subgraph);
+ Edge.prototype._drawDashLine = function(ctx) {
+ // set style
+ if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight;}
+ else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover;}
+ else {ctx.strokeStyle = this.options.color.color;}
- return;
- }
+ ctx.lineWidth = this._getLineWidth();
- // parse an attribute statement
- var attr = parseAttributeStatement(graph);
- if (attr) {
- return;
- }
+ var via = null;
+ // only firefox and chrome support this method, else we use the legacy one.
+ if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
+ // configure the dash pattern
+ var pattern = [0];
+ if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) {
+ pattern = [this.options.dash.length,this.options.dash.gap];
+ }
+ else {
+ pattern = [5,5];
+ }
- // parse node
- if (tokenType != TOKENTYPE.IDENTIFIER) {
- throw newSyntaxError('Identifier expected');
- }
- var id = token; // id can be a string or a number
- getToken();
+ // set dash settings for chrome or firefox
+ if (typeof ctx.setLineDash !== 'undefined') { //Chrome
+ ctx.setLineDash(pattern);
+ ctx.lineDashOffset = 0;
- if (token == '=') {
- // id statement
- getToken();
- if (tokenType != TOKENTYPE.IDENTIFIER) {
- throw newSyntaxError('Identifier expected');
+ } else { //Firefox
+ ctx.mozDash = pattern;
+ ctx.mozDashOffset = 0;
}
- graph[id] = token;
- getToken();
- // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
- }
- else {
- parseNodeStatement(graph, id);
- }
- }
- /**
- * Parse a subgraph
- * @param {Object} graph parent graph object
- * @return {Object | null} subgraph
- */
- function parseSubgraph (graph) {
- var subgraph = null;
+ // draw the line
+ via = this._line(ctx);
- // optional subgraph keyword
- if (token == 'subgraph') {
- subgraph = {};
- subgraph.type = 'subgraph';
- getToken();
+ // restore the dash settings.
+ if (typeof ctx.setLineDash !== 'undefined') { //Chrome
+ ctx.setLineDash([0]);
+ ctx.lineDashOffset = 0;
- // optional graph id
- if (tokenType == TOKENTYPE.IDENTIFIER) {
- subgraph.id = token;
- getToken();
+ } else { //Firefox
+ ctx.mozDash = [0];
+ ctx.mozDashOffset = 0;
}
}
-
- // open angle bracket
- if (token == '{') {
- getToken();
-
- if (!subgraph) {
- subgraph = {};
+ else { // unsupporting smooth lines
+ // draw dashed line
+ ctx.beginPath();
+ ctx.lineCap = 'round';
+ if (this.options.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
+ {
+ ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
+ [this.options.dash.length,this.options.dash.gap,this.options.dash.altLength,this.options.dash.gap]);
}
- subgraph.parent = graph;
- subgraph.node = graph.node;
- subgraph.edge = graph.edge;
- subgraph.graph = graph.graph;
-
- // statements
- parseStatements(subgraph);
-
- // close angle bracket
- if (token != '}') {
- throw newSyntaxError('Angle bracket } expected');
+ else if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) //If a dash and gap value has been set add to the array this value
+ {
+ ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
+ [this.options.dash.length,this.options.dash.gap]);
}
- getToken();
-
- // remove temporary default properties
- delete subgraph.node;
- delete subgraph.edge;
- delete subgraph.graph;
- delete subgraph.parent;
+ else //If all else fails draw a line
+ {
+ ctx.moveTo(this.from.x, this.from.y);
+ ctx.lineTo(this.to.x, this.to.y);
+ }
+ ctx.stroke();
+ }
- // register at the parent graph
- if (!graph.subgraphs) {
- graph.subgraphs = [];
+ // draw label
+ if (this.label) {
+ var point;
+ if (this.options.smoothCurves.enabled == true && via != null) {
+ var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
+ var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
+ point = {x:midpointX, y:midpointY};
}
- graph.subgraphs.push(subgraph);
+ else {
+ point = this._pointOnLine(0.5);
+ }
+ this._label(ctx, this.label, point.x, point.y);
}
-
- return subgraph;
- }
+ };
/**
- * parse an attribute statement like "node [shape=circle fontSize=16]".
- * Available keywords are 'node', 'edge', 'graph'.
- * The previous list with default attributes will be replaced
- * @param {Object} graph
- * @returns {String | null} keyword Returns the name of the parsed attribute
- * (node, edge, graph), or null if nothing
- * is parsed.
+ * Get a point on a line
+ * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
+ * @return {Object} point
+ * @private
*/
- function parseAttributeStatement (graph) {
- // attribute statements
- if (token == 'node') {
- getToken();
-
- // node attributes
- graph.node = parseAttributeList();
- return 'node';
- }
- else if (token == 'edge') {
- getToken();
-
- // edge attributes
- graph.edge = parseAttributeList();
- return 'edge';
- }
- else if (token == 'graph') {
- getToken();
-
- // graph attributes
- graph.graph = parseAttributeList();
- return 'graph';
+ Edge.prototype._pointOnLine = function (percentage) {
+ return {
+ x: (1 - percentage) * this.from.x + percentage * this.to.x,
+ y: (1 - percentage) * this.from.y + percentage * this.to.y
}
-
- return null;
- }
+ };
/**
- * parse a node statement
- * @param {Object} graph
- * @param {String | Number} id
+ * Get a point on a circle
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} radius
+ * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
+ * @return {Object} point
+ * @private
*/
- function parseNodeStatement(graph, id) {
- // node statement
- var node = {
- id: id
- };
- var attr = parseAttributeList();
- if (attr) {
- node.attr = attr;
+ Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
+ var angle = (percentage - 3/8) * 2 * Math.PI;
+ return {
+ x: x + radius * Math.cos(angle),
+ y: y - radius * Math.sin(angle)
}
- addNode(graph, node);
-
- // edge statements
- parseEdge(graph, id);
- }
+ };
/**
- * Parse an edge or a series of edges
- * @param {Object} graph
- * @param {String | Number} from Id of the from node
+ * Redraw a edge as a line with an arrow halfway the line
+ * Draw this edge in the given canvas
+ * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
+ * @param {CanvasRenderingContext2D} ctx
+ * @private
*/
- function parseEdge(graph, from) {
- while (token == '->' || token == '--') {
- var to;
- var type = token;
- getToken();
+ Edge.prototype._drawArrowCenter = function(ctx) {
+ var point;
+ // set style
+ if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight; ctx.fillStyle = this.options.color.highlight;}
+ else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover; ctx.fillStyle = this.options.color.hover;}
+ else {ctx.strokeStyle = this.options.color.color; ctx.fillStyle = this.options.color.color;}
+ ctx.lineWidth = this._getLineWidth();
- var subgraph = parseSubgraph(graph);
- if (subgraph) {
- to = subgraph;
+ if (this.from != this.to) {
+ // draw line
+ var via = this._line(ctx);
+
+ var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
+ var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
+ // draw an arrow halfway the line
+ if (this.options.smoothCurves.enabled == true && via != null) {
+ var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
+ var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
+ point = {x:midpointX, y:midpointY};
}
else {
- if (tokenType != TOKENTYPE.IDENTIFIER) {
- throw newSyntaxError('Identifier or subgraph expected');
- }
- to = token;
- addNode(graph, {
- id: to
- });
- getToken();
+ point = this._pointOnLine(0.5);
}
- // parse edge attributes
- var attr = parseAttributeList();
+ ctx.arrow(point.x, point.y, angle, length);
+ ctx.fill();
+ ctx.stroke();
- // create edge
- var edge = createEdge(graph, from, to, type, attr);
- addEdge(graph, edge);
+ // draw label
+ if (this.label) {
+ this._label(ctx, this.label, point.x, point.y);
+ }
+ }
+ else {
+ // draw circle
+ var x, y;
+ var radius = 0.25 * Math.max(100,this.physics.springLength);
+ var node = this.from;
+ if (!node.width) {
+ node.resize(ctx);
+ }
+ if (node.width > node.height) {
+ x = node.x + node.width * 0.5;
+ y = node.y - radius;
+ }
+ else {
+ x = node.x + radius;
+ y = node.y - node.height * 0.5;
+ }
+ this._circle(ctx, x, y, radius);
- from = to;
+ // draw all arrows
+ var angle = 0.2 * Math.PI;
+ var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
+ point = this._pointOnCircle(x, y, radius, 0.5);
+ ctx.arrow(point.x, point.y, angle, length);
+ ctx.fill();
+ ctx.stroke();
+
+ // draw label
+ if (this.label) {
+ point = this._pointOnCircle(x, y, radius, 0.5);
+ this._label(ctx, this.label, point.x, point.y);
+ }
}
- }
+ };
+
+
/**
- * Parse a set with attributes,
- * for example [label="1.000", shape=solid]
- * @return {Object | null} attr
+ * Redraw a edge as a line with an arrow
+ * Draw this edge in the given canvas
+ * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
+ * @param {CanvasRenderingContext2D} ctx
+ * @private
*/
- function parseAttributeList() {
- var attr = null;
+ Edge.prototype._drawArrow = function(ctx) {
+ // set style
+ if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight; ctx.fillStyle = this.options.color.highlight;}
+ else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover; ctx.fillStyle = this.options.color.hover;}
+ else {ctx.strokeStyle = this.options.color.color; ctx.fillStyle = this.options.color.color;}
- while (token == '[') {
- getToken();
- attr = {};
- while (token !== '' && token != ']') {
- if (tokenType != TOKENTYPE.IDENTIFIER) {
- throw newSyntaxError('Attribute name expected');
- }
- var name = token;
+ ctx.lineWidth = this._getLineWidth();
- getToken();
- if (token != '=') {
- throw newSyntaxError('Equal sign = expected');
- }
- getToken();
+ var angle, length;
+ //draw a line
+ if (this.from != this.to) {
+ angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
+ var dx = (this.to.x - this.from.x);
+ var dy = (this.to.y - this.from.y);
+ var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
- if (tokenType != TOKENTYPE.IDENTIFIER) {
- throw newSyntaxError('Attribute value expected');
- }
- var value = token;
- setValue(attr, name, value); // name can be a path
+ var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
+ var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
+ var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
+ var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
- getToken();
- if (token ==',') {
- getToken();
- }
+ var via;
+ if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true ) {
+ via = this.via;
}
-
- if (token != ']') {
- throw newSyntaxError('Bracket ] expected');
+ else if (this.options.smoothCurves.enabled == true) {
+ via = this._getViaCoordinates();
}
- getToken();
- }
- return attr;
- }
+ if (this.options.smoothCurves.enabled == true && via.x != null) {
+ angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x));
+ dx = (this.to.x - via.x);
+ dy = (this.to.y - via.y);
+ edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
+ }
+ var toBorderDist = this.to.distanceToBorder(ctx, angle);
+ var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
- /**
- * Create a syntax error with extra information on current token and index.
- * @param {String} message
- * @returns {SyntaxError} err
- */
- function newSyntaxError(message) {
- return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
- }
+ var xTo,yTo;
+ if (this.options.smoothCurves.enabled == true && via.x != null) {
+ xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x;
+ yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y;
+ }
+ else {
+ xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
+ yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
+ }
- /**
- * Chop off text after a maximum length
- * @param {String} text
- * @param {Number} maxLength
- * @returns {String}
- */
- function chop (text, maxLength) {
- return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
- }
+ ctx.beginPath();
+ ctx.moveTo(xFrom,yFrom);
+ if (this.options.smoothCurves.enabled == true && via.x != null) {
+ ctx.quadraticCurveTo(via.x,via.y,xTo, yTo);
+ }
+ else {
+ ctx.lineTo(xTo, yTo);
+ }
+ ctx.stroke();
- /**
- * Execute a function fn for each pair of elements in two arrays
- * @param {Array | *} array1
- * @param {Array | *} array2
- * @param {function} fn
- */
- function forEach2(array1, array2, fn) {
- if (Array.isArray(array1)) {
- array1.forEach(function (elem1) {
- if (Array.isArray(array2)) {
- array2.forEach(function (elem2) {
- fn(elem1, elem2);
- });
+ // draw arrow at the end of the line
+ length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
+ ctx.arrow(xTo, yTo, angle, length);
+ ctx.fill();
+ ctx.stroke();
+
+ // draw label
+ if (this.label) {
+ var point;
+ if (this.options.smoothCurves.enabled == true && via != null) {
+ var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
+ var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
+ point = {x:midpointX, y:midpointY};
}
else {
- fn(elem1, array2);
+ point = this._pointOnLine(0.5);
}
- });
+ this._label(ctx, this.label, point.x, point.y);
+ }
}
else {
- if (Array.isArray(array2)) {
- array2.forEach(function (elem2) {
- fn(array1, elem2);
- });
+ // draw circle
+ var node = this.from;
+ var x, y, arrow;
+ var radius = 0.25 * Math.max(100,this.physics.springLength);
+ if (!node.width) {
+ node.resize(ctx);
+ }
+ if (node.width > node.height) {
+ x = node.x + node.width * 0.5;
+ y = node.y - radius;
+ arrow = {
+ x: x,
+ y: node.y,
+ angle: 0.9 * Math.PI
+ };
}
else {
- fn(array1, array2);
+ x = node.x + radius;
+ y = node.y - node.height * 0.5;
+ arrow = {
+ x: node.x,
+ y: y,
+ angle: 0.6 * Math.PI
+ };
}
- }
- }
+ ctx.beginPath();
+ // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
+ ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
+ ctx.stroke();
- /**
- * Convert a string containing a graph in DOT language into a map containing
- * with nodes and edges in the format of graph.
- * @param {String} data Text containing a graph in DOT-notation
- * @return {Object} graphData
- */
- function DOTToGraph (data) {
- // parse the DOT file
- var dotData = parseDOT(data);
- var graphData = {
- nodes: [],
- edges: [],
- options: {}
- };
+ // draw all arrows
+ var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
+ ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
+ ctx.fill();
+ ctx.stroke();
- // copy the nodes
- if (dotData.nodes) {
- dotData.nodes.forEach(function (dotNode) {
- var graphNode = {
- id: dotNode.id,
- label: String(dotNode.label || dotNode.id)
- };
- merge(graphNode, dotNode.attr);
- if (graphNode.image) {
- graphNode.shape = 'image';
- }
- graphData.nodes.push(graphNode);
- });
+ // draw label
+ if (this.label) {
+ point = this._pointOnCircle(x, y, radius, 0.5);
+ this._label(ctx, this.label, point.x, point.y);
+ }
}
+ };
- // copy the edges
- if (dotData.edges) {
- /**
- * Convert an edge in DOT format to an edge with VisGraph format
- * @param {Object} dotEdge
- * @returns {Object} graphEdge
- */
- function convertEdge(dotEdge) {
- var graphEdge = {
- from: dotEdge.from,
- to: dotEdge.to
- };
- merge(graphEdge, dotEdge.attr);
- graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
- return graphEdge;
- }
- dotData.edges.forEach(function (dotEdge) {
- var from, to;
- if (dotEdge.from instanceof Object) {
- from = dotEdge.from.nodes;
- }
- else {
- from = {
- id: dotEdge.from
- }
- }
- if (dotEdge.to instanceof Object) {
- to = dotEdge.to.nodes;
+ /**
+ * Calculate the distance between a point (x3,y3) and a line segment from
+ * (x1,y1) to (x2,y2).
+ * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
+ * @param {number} x1
+ * @param {number} y1
+ * @param {number} x2
+ * @param {number} y2
+ * @param {number} x3
+ * @param {number} y3
+ * @private
+ */
+ Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
+ var returnValue = 0;
+ if (this.from != this.to) {
+ if (this.options.smoothCurves.enabled == true) {
+ var xVia, yVia;
+ if (this.options.smoothCurves.enabled == true && this.options.smoothCurves.dynamic == true) {
+ xVia = this.via.x;
+ yVia = this.via.y;
}
else {
- to = {
- id: dotEdge.to
+ var via = this._getViaCoordinates();
+ xVia = via.x;
+ yVia = via.y;
+ }
+ var minDistance = 1e9;
+ var distance;
+ var i,t,x,y, lastX, lastY;
+ for (i = 0; i < 10; i++) {
+ t = 0.1*i;
+ x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*xVia + Math.pow(t,2)*x2;
+ y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*yVia + Math.pow(t,2)*y2;
+ if (i > 0) {
+ distance = this._getDistanceToLine(lastX,lastY,x,y, x3,y3);
+ minDistance = distance < minDistance ? distance : minDistance;
}
+ lastX = x; lastY = y;
}
+ returnValue = minDistance;
+ }
+ else {
+ returnValue = this._getDistanceToLine(x1,y1,x2,y2,x3,y3);
+ }
+ }
+ else {
+ var x, y, dx, dy;
+ var radius = 0.25 * this.physics.springLength;
+ var node = this.from;
+ if (node.width > node.height) {
+ x = node.x + 0.5 * node.width;
+ y = node.y - radius;
+ }
+ else {
+ x = node.x + radius;
+ y = node.y - 0.5 * node.height;
+ }
+ dx = x - x3;
+ dy = y - y3;
+ returnValue = Math.abs(Math.sqrt(dx*dx + dy*dy) - radius);
+ }
- if (dotEdge.from instanceof Object && dotEdge.from.edges) {
- dotEdge.from.edges.forEach(function (subEdge) {
- var graphEdge = convertEdge(subEdge);
- graphData.edges.push(graphEdge);
- });
- }
+ if (this.labelDimensions.left < x3 &&
+ this.labelDimensions.left + this.labelDimensions.width > x3 &&
+ this.labelDimensions.top < y3 &&
+ this.labelDimensions.top + this.labelDimensions.height > y3) {
+ return 0;
+ }
+ else {
+ return returnValue;
+ }
+ };
- forEach2(from, to, function (from, to) {
- var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
- var graphEdge = convertEdge(subEdge);
- graphData.edges.push(graphEdge);
- });
+ Edge.prototype._getDistanceToLine = function(x1,y1,x2,y2,x3,y3) {
+ var px = x2-x1,
+ py = y2-y1,
+ something = px*px + py*py,
+ u = ((x3 - x1) * px + (y3 - y1) * py) / something;
- if (dotEdge.to instanceof Object && dotEdge.to.edges) {
- dotEdge.to.edges.forEach(function (subEdge) {
- var graphEdge = convertEdge(subEdge);
- graphData.edges.push(graphEdge);
- });
- }
- });
+ if (u > 1) {
+ u = 1;
}
-
- // copy the options
- if (dotData.attr) {
- graphData.options = dotData.attr;
+ else if (u < 0) {
+ u = 0;
}
- return graphData;
- }
+ var x = x1 + u * px,
+ y = y1 + u * py,
+ dx = x - x3,
+ dy = y - y3;
- // exports
- exports.parseDOT = parseDOT;
- exports.DOTToGraph = DOTToGraph;
+ //# Note: If the actual distance does not matter,
+ //# if you only want to compare what this function
+ //# returns to other results of this function, you
+ //# can just return the squared distance instead
+ //# (i.e. remove the sqrt) to gain a little performance
-
-/***/ },
-/* 48 */
-/***/ function(module, exports, __webpack_require__) {
-
-
- function parseGephi(gephiJSON, options) {
- var edges = [];
- var nodes = [];
- this.options = {
- edges: {
- inheritColor: true
- },
- nodes: {
- allowedToMove: false,
- parseColor: false
- }
- };
-
- if (options !== undefined) {
- this.options.nodes['allowedToMove'] = options.allowedToMove | false;
- this.options.nodes['parseColor'] = options.parseColor | false;
- this.options.edges['inheritColor'] = options.inheritColor | true;
- }
-
- var gEdges = gephiJSON.edges;
- var gNodes = gephiJSON.nodes;
- for (var i = 0; i < gEdges.length; i++) {
- var edge = {};
- var gEdge = gEdges[i];
- edge['id'] = gEdge.id;
- edge['from'] = gEdge.source;
- edge['to'] = gEdge.target;
- edge['attributes'] = gEdge.attributes;
- // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined;
- // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size;
- edge['color'] = gEdge.color;
- edge['inheritColor'] = edge['color'] !== undefined ? false : this.options.inheritColor;
- edges.push(edge);
- }
-
- for (var i = 0; i < gNodes.length; i++) {
- var node = {};
- var gNode = gNodes[i];
- node['id'] = gNode.id;
- node['attributes'] = gNode.attributes;
- node['x'] = gNode.x;
- node['y'] = gNode.y;
- node['label'] = gNode.label;
- if (this.options.nodes.parseColor == true) {
- node['color'] = gNode.color;
- }
- else {
- node['color'] = gNode.color !== undefined ? {background:gNode.color, border:gNode.color} : undefined;
- }
- node['radius'] = gNode.size;
- node['allowedToMoveX'] = this.options.nodes.allowedToMove;
- node['allowedToMoveY'] = this.options.nodes.allowedToMove;
- nodes.push(node);
- }
-
- return {nodes:nodes, edges:edges};
+ return Math.sqrt(dx*dx + dy*dy);
}
- exports.parseGephi = parseGephi;
-
-/***/ },
-/* 49 */
-/***/ function(module, exports, __webpack_require__) {
-
- var util = __webpack_require__(1);
-
/**
- * @class Groups
- * This class can store groups and properties specific for groups.
+ * This allows the zoom level of the network to influence the rendering
+ *
+ * @param scale
*/
- function Groups() {
- this.clear();
- this.defaultIndex = 0;
- }
+ Edge.prototype.setScale = function(scale) {
+ this.networkScaleInv = 1.0/scale;
+ };
- /**
- * default constants for group colors
- */
- Groups.DEFAULT = [
- {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}, hover: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
- {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}, hover: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
- {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}, hover: {border: "#FA0A10", background: "#FFAFB1"}}, // red
- {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}, hover: {border: "#41A906", background: "#A1EC76"}}, // green
- {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}, hover: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
- {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}, hover: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
- {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}, hover: {border: "#C37F00", background: "#FFCA66"}}, // orange
- {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}, hover: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
- {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}, hover: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
- {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}, hover: {border: "#4AD63A", background: "#E6FFE3"}} // mint
- ];
+ Edge.prototype.select = function() {
+ this.selected = true;
+ };
+
+ Edge.prototype.unselect = function() {
+ this.selected = false;
+ };
+ Edge.prototype.positionBezierNode = function() {
+ if (this.via !== null && this.from !== null && this.to !== null) {
+ this.via.x = 0.5 * (this.from.x + this.to.x);
+ this.via.y = 0.5 * (this.from.y + this.to.y);
+ }
+ };
/**
- * Clear all groups
+ * This function draws the control nodes for the manipulator. In order to enable this, only set the this.controlNodesEnabled to true.
+ * @param ctx
*/
- Groups.prototype.clear = function () {
- this.groups = {};
- this.groups.length = function()
- {
- var i = 0;
- for ( var p in this ) {
- if (this.hasOwnProperty(p)) {
- i++;
- }
+ Edge.prototype._drawControlNodes = function(ctx) {
+ if (this.controlNodesEnabled == true) {
+ if (this.controlNodes.from === null && this.controlNodes.to === null) {
+ var nodeIdFrom = "edgeIdFrom:".concat(this.id);
+ var nodeIdTo = "edgeIdTo:".concat(this.id);
+ var constants = {
+ nodes:{group:'', radius:8},
+ physics:{damping:0},
+ clustering: {maxNodeSizeIncrements: 0 ,nodeScaling: {width:0, height: 0, radius:0}}
+ };
+ this.controlNodes.from = new Node(
+ {id:nodeIdFrom,
+ shape:'dot',
+ color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}}
+ },{},{},constants);
+ this.controlNodes.to = new Node(
+ {id:nodeIdTo,
+ shape:'dot',
+ color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}}
+ },{},{},constants);
}
- return i;
+
+ if (this.controlNodes.from.selected == false && this.controlNodes.to.selected == false) {
+ this.controlNodes.positions = this.getControlNodePositions(ctx);
+ this.controlNodes.from.x = this.controlNodes.positions.from.x;
+ this.controlNodes.from.y = this.controlNodes.positions.from.y;
+ this.controlNodes.to.x = this.controlNodes.positions.to.x;
+ this.controlNodes.to.y = this.controlNodes.positions.to.y;
+ }
+
+ this.controlNodes.from.draw(ctx);
+ this.controlNodes.to.draw(ctx);
+ }
+ else {
+ this.controlNodes = {from:null, to:null, positions:{}};
}
};
-
/**
- * get group properties of a groupname. If groupname is not found, a new group
- * is added.
- * @param {*} groupname Can be a number, string, Date, etc.
- * @return {Object} group The created group, containing all group properties
+ * Enable control nodes.
+ * @private
*/
- Groups.prototype.get = function (groupname) {
- var group = this.groups[groupname];
- if (group == undefined) {
- // create new group
- var index = this.defaultIndex % Groups.DEFAULT.length;
- this.defaultIndex++;
- group = {};
- group.color = Groups.DEFAULT[index];
- this.groups[groupname] = group;
- }
-
- return group;
+ Edge.prototype._enableControlNodes = function() {
+ this.controlNodesEnabled = true;
};
/**
- * Add a custom group style
- * @param {String} groupname
- * @param {Object} style An object containing borderColor,
- * backgroundColor, etc.
- * @return {Object} group The created group object
+ * disable control nodes
+ * @private
*/
- Groups.prototype.add = function (groupname, style) {
- this.groups[groupname] = style;
- if (style.color) {
- style.color = util.parseColor(style.color);
- }
- return style;
+ Edge.prototype._disableControlNodes = function() {
+ this.controlNodesEnabled = false;
};
- module.exports = Groups;
-
-
-/***/ },
-/* 50 */
-/***/ function(module, exports, __webpack_require__) {
-
/**
- * @class Images
- * This class loads images and keeps them stored.
+ * This checks if one of the control nodes is selected and if so, returns the control node object. Else it returns null.
+ * @param x
+ * @param y
+ * @returns {null}
+ * @private
*/
- function Images() {
- this.images = {};
+ Edge.prototype._getSelectedControlNode = function(x,y) {
+ var positions = this.controlNodes.positions;
+ var fromDistance = Math.sqrt(Math.pow(x - positions.from.x,2) + Math.pow(y - positions.from.y,2));
+ var toDistance = Math.sqrt(Math.pow(x - positions.to.x ,2) + Math.pow(y - positions.to.y ,2));
+
+ if (fromDistance < 15) {
+ this.connectedNode = this.from;
+ this.from = this.controlNodes.from;
+ return this.controlNodes.from;
+ }
+ else if (toDistance < 15) {
+ this.connectedNode = this.to;
+ this.to = this.controlNodes.to;
+ return this.controlNodes.to;
+ }
+ else {
+ return null;
+ }
+ };
- this.callback = undefined;
- }
/**
- * Set an onload callback function. This will be called each time an image
- * is loaded
- * @param {function} callback
+ * this resets the control nodes to their original position.
+ * @private
*/
- Images.prototype.setOnloadCallback = function(callback) {
- this.callback = callback;
+ Edge.prototype._restoreControlNodes = function() {
+ if (this.controlNodes.from.selected == true) {
+ this.from = this.connectedNode;
+ this.connectedNode = null;
+ this.controlNodes.from.unselect();
+ }
+ if (this.controlNodes.to.selected == true) {
+ this.to = this.connectedNode;
+ this.connectedNode = null;
+ this.controlNodes.to.unselect();
+ }
};
/**
+ * this calculates the position of the control nodes on the edges of the parent nodes.
*
- * @param {string} url Url of the image
- * @param {string} url Url of an image to use if the url image is not found
- * @return {Image} img The image object
+ * @param ctx
+ * @returns {{from: {x: number, y: number}, to: {x: *, y: *}}}
*/
- Images.prototype.load = function(url, brokenUrl) {
- var img = this.images[url];
- if (img == undefined) {
- // create the image
- var images = this;
- img = new Image();
- this.images[url] = img;
- img.onload = function() {
- if (images.callback) {
- images.callback(this);
- }
- };
-
- img.onerror = function () {
- this.src = brokenUrl;
- if (images.callback) {
- images.callback(this);
- }
- };
-
- img.src = url;
+ Edge.prototype.getControlNodePositions = function(ctx) {
+ var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
+ var dx = (this.to.x - this.from.x);
+ var dy = (this.to.y - this.from.y);
+ var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
+ var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
+ var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
+ var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
+ var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
+
+ var via;
+ if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true) {
+ via = this.via;
+ }
+ else if (this.options.smoothCurves.enabled == true) {
+ via = this._getViaCoordinates();
}
- return img;
- };
+ if (this.options.smoothCurves.enabled == true && via.x != null) {
+ angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x));
+ dx = (this.to.x - via.x);
+ dy = (this.to.y - via.y);
+ edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
+ }
+ var toBorderDist = this.to.distanceToBorder(ctx, angle);
+ var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
- module.exports = Images;
+ var xTo,yTo;
+ if (this.options.smoothCurves.enabled == true && via.x != null) {
+ xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x;
+ yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y;
+ }
+ else {
+ xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
+ yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
+ }
+ return {from:{x:xFrom,y:yFrom},to:{x:xTo,y:yTo}};
+ };
+
+ module.exports = Edge;
/***/ },
-/* 51 */
+/* 48 */
/***/ function(module, exports, __webpack_require__) {
var util = __webpack_require__(1);
@@ -26516,1349 +26676,1194 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ },
-/* 52 */
+/* 49 */
/***/ function(module, exports, __webpack_require__) {
var util = __webpack_require__(1);
- var Node = __webpack_require__(51);
/**
- * @class Edge
- *
- * A edge connects two nodes
- * @param {Object} properties Object with properties. Must contain
- * At least properties from and to.
- * Available properties: from (number),
- * to (number), label (string, color (string),
- * width (number), style (string),
- * length (number), title (string)
- * @param {Network} network A Network object, used to find and edge to
- * nodes.
- * @param {Object} constants An object with default values for
- * example for the color
+ * @class Groups
+ * This class can store groups and properties specific for groups.
*/
- function Edge (properties, network, networkConstants) {
- if (!network) {
- throw "No network provided";
- }
- var fields = ['edges','physics'];
- var constants = util.selectiveBridgeObject(fields,networkConstants);
- this.options = constants.edges;
- this.physics = constants.physics;
- this.options['smoothCurves'] = networkConstants['smoothCurves'];
-
-
- this.network = network;
-
- // initialize variables
- this.id = undefined;
- this.fromId = undefined;
- this.toId = undefined;
- this.title = undefined;
- this.widthSelected = this.options.width * this.options.widthSelectionMultiplier;
- this.value = undefined;
- this.selected = false;
- this.hover = false;
- this.labelDimensions = {top:0,left:0,width:0,height:0,yLine:0}; // could be cached
- this.dirtyLabel = true;
-
- this.from = null; // a node
- this.to = null; // a node
- this.via = null; // a temp node
+ function Groups() {
+ this.clear();
+ this.defaultIndex = 0;
+ }
- // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
- // by storing the original information we can revert to the original connection when the cluser is opened.
- this.originalFromId = [];
- this.originalToId = [];
- this.connected = false;
+ /**
+ * default constants for group colors
+ */
+ Groups.DEFAULT = [
+ {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}, hover: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
+ {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}, hover: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
+ {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}, hover: {border: "#FA0A10", background: "#FFAFB1"}}, // red
+ {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}, hover: {border: "#41A906", background: "#A1EC76"}}, // green
+ {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}, hover: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
+ {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}, hover: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
+ {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}, hover: {border: "#C37F00", background: "#FFCA66"}}, // orange
+ {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}, hover: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
+ {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}, hover: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
+ {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}, hover: {border: "#4AD63A", background: "#E6FFE3"}} // mint
+ ];
- this.widthFixed = false;
- this.lengthFixed = false;
- this.setProperties(properties);
+ /**
+ * Clear all groups
+ */
+ Groups.prototype.clear = function () {
+ this.groups = {};
+ this.groups.length = function()
+ {
+ var i = 0;
+ for ( var p in this ) {
+ if (this.hasOwnProperty(p)) {
+ i++;
+ }
+ }
+ return i;
+ }
+ };
- this.controlNodesEnabled = false;
- this.controlNodes = {from:null, to:null, positions:{}};
- this.connectedNode = null;
- }
/**
- * Set or overwrite properties for the edge
- * @param {Object} properties an object with properties
- * @param {Object} constants and object with default, global properties
+ * get group properties of a groupname. If groupname is not found, a new group
+ * is added.
+ * @param {*} groupname Can be a number, string, Date, etc.
+ * @return {Object} group The created group, containing all group properties
*/
- Edge.prototype.setProperties = function(properties) {
- if (!properties) {
- return;
+ Groups.prototype.get = function (groupname) {
+ var group = this.groups[groupname];
+ if (group == undefined) {
+ // create new group
+ var index = this.defaultIndex % Groups.DEFAULT.length;
+ this.defaultIndex++;
+ group = {};
+ group.color = Groups.DEFAULT[index];
+ this.groups[groupname] = group;
}
- var fields = ['style','fontSize','fontFace','fontColor','fontFill','width',
- 'widthSelectionMultiplier','hoverWidth','arrowScaleFactor','dash','inheritColor'
- ];
- util.selectiveDeepExtend(fields, this.options, properties);
-
- if (properties.from !== undefined) {this.fromId = properties.from;}
- if (properties.to !== undefined) {this.toId = properties.to;}
+ return group;
+ };
- if (properties.id !== undefined) {this.id = properties.id;}
- if (properties.label !== undefined) {this.label = properties.label; this.dirtyLabel = true;}
+ /**
+ * Add a custom group style
+ * @param {String} groupname
+ * @param {Object} style An object containing borderColor,
+ * backgroundColor, etc.
+ * @return {Object} group The created group object
+ */
+ Groups.prototype.add = function (groupname, style) {
+ this.groups[groupname] = style;
+ if (style.color) {
+ style.color = util.parseColor(style.color);
+ }
+ return style;
+ };
- if (properties.title !== undefined) {this.title = properties.title;}
- if (properties.value !== undefined) {this.value = properties.value;}
- if (properties.length !== undefined) {this.physics.springLength = properties.length;}
+ module.exports = Groups;
- if (properties.color !== undefined) {
- this.options.inheritColor = false;
- if (util.isString(properties.color)) {
- this.options.color.color = properties.color;
- this.options.color.highlight = properties.color;
- }
- else {
- if (properties.color.color !== undefined) {this.options.color.color = properties.color.color;}
- if (properties.color.highlight !== undefined) {this.options.color.highlight = properties.color.highlight;}
- if (properties.color.hover !== undefined) {this.options.color.hover = properties.color.hover;}
- }
- }
- // A node is connected when it has a from and to node.
- this.connect();
+/***/ },
+/* 50 */
+/***/ function(module, exports, __webpack_require__) {
- this.widthFixed = this.widthFixed || (properties.width !== undefined);
- this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
+ /**
+ * @class Images
+ * This class loads images and keeps them stored.
+ */
+ function Images() {
+ this.images = {};
- this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
+ this.callback = undefined;
+ }
- // set draw method based on style
- switch (this.options.style) {
- case 'line': this.draw = this._drawLine; break;
- case 'arrow': this.draw = this._drawArrow; break;
- case 'arrow-center': this.draw = this._drawArrowCenter; break;
- case 'dash-line': this.draw = this._drawDashLine; break;
- default: this.draw = this._drawLine; break;
- }
+ /**
+ * Set an onload callback function. This will be called each time an image
+ * is loaded
+ * @param {function} callback
+ */
+ Images.prototype.setOnloadCallback = function(callback) {
+ this.callback = callback;
};
/**
- * Connect an edge to its nodes
+ *
+ * @param {string} url Url of the image
+ * @param {string} url Url of an image to use if the url image is not found
+ * @return {Image} img The image object
*/
- Edge.prototype.connect = function () {
- this.disconnect();
-
- this.from = this.network.nodes[this.fromId] || null;
- this.to = this.network.nodes[this.toId] || null;
- this.connected = (this.from && this.to);
-
- if (this.connected) {
- this.from.attachEdge(this);
- this.to.attachEdge(this);
- }
- else {
- if (this.from) {
- this.from.detachEdge(this);
- }
- if (this.to) {
- this.to.detachEdge(this);
- }
- }
- };
-
- /**
- * Disconnect an edge from its nodes
- */
- Edge.prototype.disconnect = function () {
- if (this.from) {
- this.from.detachEdge(this);
- this.from = null;
- }
- if (this.to) {
- this.to.detachEdge(this);
- this.to = null;
+ Images.prototype.load = function(url, brokenUrl) {
+ var img = this.images[url];
+ if (img == undefined) {
+ // create the image
+ var images = this;
+ img = new Image();
+ this.images[url] = img;
+ img.onload = function() {
+ if (images.callback) {
+ images.callback(this);
+ }
+ };
+
+ img.onerror = function () {
+ this.src = brokenUrl;
+ if (images.callback) {
+ images.callback(this);
+ }
+ };
+
+ img.src = url;
}
- this.connected = false;
- };
-
- /**
- * get the title of this edge.
- * @return {string} title The title of the edge, or undefined when no title
- * has been set.
- */
- Edge.prototype.getTitle = function() {
- return typeof this.title === "function" ? this.title() : this.title;
+ return img;
};
+ module.exports = Images;
- /**
- * Retrieve the value of the edge. Can be undefined
- * @return {Number} value
- */
- Edge.prototype.getValue = function() {
- return this.value;
- };
- /**
- * Adjust the value range of the edge. The edge will adjust it's width
- * based on its value.
- * @param {Number} min
- * @param {Number} max
- */
- Edge.prototype.setValueRange = function(min, max) {
- if (!this.widthFixed && this.value !== undefined) {
- var scale = (this.options.widthMax - this.options.widthMin) / (max - min);
- this.options.width= (this.value - min) * scale + this.options.widthMin;
- this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
- }
- };
-
- /**
- * Redraw a edge
- * Draw this edge in the given canvas
- * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
- * @param {CanvasRenderingContext2D} ctx
- */
- Edge.prototype.draw = function(ctx) {
- throw "Method draw not initialized in edge";
- };
+/***/ },
+/* 51 */
+/***/ function(module, exports, __webpack_require__) {
/**
- * Check if this object is overlapping with the provided object
- * @param {Object} obj an object with parameters left, top
- * @return {boolean} True if location is located on the edge
+ * Popup is a class to create a popup window with some text
+ * @param {Element} container The container object.
+ * @param {Number} [x]
+ * @param {Number} [y]
+ * @param {String} [text]
+ * @param {Object} [style] An object containing borderColor,
+ * backgroundColor, etc.
*/
- Edge.prototype.isOverlappingWith = function(obj) {
- if (this.connected) {
- var distMax = 10;
- var xFrom = this.from.x;
- var yFrom = this.from.y;
- var xTo = this.to.x;
- var yTo = this.to.y;
- var xObj = obj.left;
- var yObj = obj.top;
-
- var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
-
- return (dist < distMax);
+ function Popup(container, x, y, text, style) {
+ if (container) {
+ this.container = container;
}
else {
- return false
- }
- };
-
- Edge.prototype._getColor = function() {
- var colorObj = this.options.color;
- if (this.options.inheritColor == "to") {
- colorObj = {
- highlight: this.to.options.color.highlight.border,
- hover: this.to.options.color.hover.border,
- color: this.to.options.color.border
- };
- }
- else if (this.options.inheritColor == "from" || this.options.inheritColor == true) {
- colorObj = {
- highlight: this.from.options.color.highlight.border,
- hover: this.from.options.color.hover.border,
- color: this.from.options.color.border
- };
+ this.container = document.body;
}
- if (this.selected == true) {return colorObj.highlight;}
- else if (this.hover == true) {return colorObj.hover;}
- else {return colorObj.color;}
- }
-
-
- /**
- * Redraw a edge as a line
- * Draw this edge in the given canvas
- * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
- * @param {CanvasRenderingContext2D} ctx
- * @private
- */
- Edge.prototype._drawLine = function(ctx) {
- // set style
- ctx.strokeStyle = this._getColor();
- ctx.lineWidth = this._getLineWidth();
-
- if (this.from != this.to) {
- // draw line
- var via = this._line(ctx);
-
- // draw label
- var point;
- if (this.label) {
- if (this.options.smoothCurves.enabled == true && via != null) {
- var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
- var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
- point = {x:midpointX, y:midpointY};
- }
- else {
- point = this._pointOnLine(0.5);
+ // x, y and text are optional, see if a style object was passed in their place
+ if (style === undefined) {
+ if (typeof x === "object") {
+ style = x;
+ x = undefined;
+ } else if (typeof text === "object") {
+ style = text;
+ text = undefined;
+ } else {
+ // for backwards compatibility, in case clients other than Network are creating Popup directly
+ style = {
+ fontColor: 'black',
+ fontSize: 14, // px
+ fontFace: 'verdana',
+ color: {
+ border: '#666',
+ background: '#FFFFC6'
+ }
}
- this._label(ctx, this.label, point.x, point.y);
- }
- }
- else {
- var x, y;
- var radius = this.physics.springLength / 4;
- var node = this.from;
- if (!node.width) {
- node.resize(ctx);
}
- if (node.width > node.height) {
- x = node.x + node.width / 2;
- y = node.y - radius;
- }
- else {
- x = node.x + radius;
- y = node.y - node.height / 2;
- }
- this._circle(ctx, x, y, radius);
- point = this._pointOnCircle(x, y, radius, 0.5);
- this._label(ctx, this.label, point.x, point.y);
}
- };
- /**
- * Get the line width of the edge. Depends on width and whether one of the
- * connected nodes is selected.
- * @return {Number} width
- * @private
- */
- Edge.prototype._getLineWidth = function() {
- if (this.selected == true) {
- return Math.max(Math.min(this.widthSelected, this.options.widthMax), 0.3*this.networkScaleInv);
- }
- else {
- if (this.hover == true) {
- return Math.max(Math.min(this.options.hoverWidth, this.options.widthMax), 0.3*this.networkScaleInv);
- }
- else {
- return Math.max(this.options.width, 0.3*this.networkScaleInv);
- }
- }
- };
-
- Edge.prototype._getViaCoordinates = function () {
- var xVia = null;
- var yVia = null;
- var factor = this.options.smoothCurves.roundness;
- var type = this.options.smoothCurves.type;
+ this.x = 0;
+ this.y = 0;
+ this.padding = 5;
- var dx = Math.abs(this.from.x - this.to.x);
- var dy = Math.abs(this.from.y - this.to.y);
- if (type == 'discrete' || type == 'diagonalCross') {
- if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
- if (this.from.y > this.to.y) {
- if (this.from.x < this.to.x) {
- xVia = this.from.x + factor * dy;
- yVia = this.from.y - factor * dy;
- }
- else if (this.from.x > this.to.x) {
- xVia = this.from.x - factor * dy;
- yVia = this.from.y - factor * dy;
- }
- }
- else if (this.from.y < this.to.y) {
- if (this.from.x < this.to.x) {
- xVia = this.from.x + factor * dy;
- yVia = this.from.y + factor * dy;
- }
- else if (this.from.x > this.to.x) {
- xVia = this.from.x - factor * dy;
- yVia = this.from.y + factor * dy;
- }
- }
- if (type == "discrete") {
- xVia = dx < factor * dy ? this.from.x : xVia;
- }
- }
- else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
- if (this.from.y > this.to.y) {
- if (this.from.x < this.to.x) {
- xVia = this.from.x + factor * dx;
- yVia = this.from.y - factor * dx;
- }
- else if (this.from.x > this.to.x) {
- xVia = this.from.x - factor * dx;
- yVia = this.from.y - factor * dx;
- }
- }
- else if (this.from.y < this.to.y) {
- if (this.from.x < this.to.x) {
- xVia = this.from.x + factor * dx;
- yVia = this.from.y + factor * dx;
- }
- else if (this.from.x > this.to.x) {
- xVia = this.from.x - factor * dx;
- yVia = this.from.y + factor * dx;
- }
- }
- if (type == "discrete") {
- yVia = dy < factor * dx ? this.from.y : yVia;
- }
- }
- }
- else if (type == "straightCross") {
- if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { // up - down
- xVia = this.from.x;
- if (this.from.y < this.to.y) {
- yVia = this.to.y - (1-factor) * dy;
- }
- else {
- yVia = this.to.y + (1-factor) * dy;
- }
- }
- else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { // left - right
- if (this.from.x < this.to.x) {
- xVia = this.to.x - (1-factor) * dx;
- }
- else {
- xVia = this.to.x + (1-factor) * dx;
- }
- yVia = this.from.y;
- }
- }
- else if (type == 'horizontal') {
- if (this.from.x < this.to.x) {
- xVia = this.to.x - (1-factor) * dx;
- }
- else {
- xVia = this.to.x + (1-factor) * dx;
- }
- yVia = this.from.y;
- }
- else if (type == 'vertical') {
- xVia = this.from.x;
- if (this.from.y < this.to.y) {
- yVia = this.to.y - (1-factor) * dy;
- }
- else {
- yVia = this.to.y + (1-factor) * dy;
- }
- }
- else { // continuous
- if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
- if (this.from.y > this.to.y) {
- if (this.from.x < this.to.x) {
- // console.log(1)
- xVia = this.from.x + factor * dy;
- yVia = this.from.y - factor * dy;
- xVia = this.to.x < xVia ? this.to.x : xVia;
- }
- else if (this.from.x > this.to.x) {
- // console.log(2)
- xVia = this.from.x - factor * dy;
- yVia = this.from.y - factor * dy;
- xVia = this.to.x > xVia ? this.to.x :xVia;
- }
- }
- else if (this.from.y < this.to.y) {
- if (this.from.x < this.to.x) {
- // console.log(3)
- xVia = this.from.x + factor * dy;
- yVia = this.from.y + factor * dy;
- xVia = this.to.x < xVia ? this.to.x : xVia;
- }
- else if (this.from.x > this.to.x) {
- // console.log(4, this.from.x, this.to.x)
- xVia = this.from.x - factor * dy;
- yVia = this.from.y + factor * dy;
- xVia = this.to.x > xVia ? this.to.x : xVia;
- }
- }
- }
- else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
- if (this.from.y > this.to.y) {
- if (this.from.x < this.to.x) {
- // console.log(5)
- xVia = this.from.x + factor * dx;
- yVia = this.from.y - factor * dx;
- yVia = this.to.y > yVia ? this.to.y : yVia;
- }
- else if (this.from.x > this.to.x) {
- // console.log(6)
- xVia = this.from.x - factor * dx;
- yVia = this.from.y - factor * dx;
- yVia = this.to.y > yVia ? this.to.y : yVia;
- }
- }
- else if (this.from.y < this.to.y) {
- if (this.from.x < this.to.x) {
- // console.log(7)
- xVia = this.from.x + factor * dx;
- yVia = this.from.y + factor * dx;
- yVia = this.to.y < yVia ? this.to.y : yVia;
- }
- else if (this.from.x > this.to.x) {
- // console.log(8)
- xVia = this.from.x - factor * dx;
- yVia = this.from.y + factor * dx;
- yVia = this.to.y < yVia ? this.to.y : yVia;
- }
- }
- }
+ if (x !== undefined && y !== undefined ) {
+ this.setPosition(x, y);
+ }
+ if (text !== undefined) {
+ this.setText(text);
}
-
- return {x:xVia, y:yVia};
+ // create the frame
+ this.frame = document.createElement("div");
+ var styleAttr = this.frame.style;
+ styleAttr.position = "absolute";
+ styleAttr.visibility = "hidden";
+ styleAttr.border = "1px solid " + style.color.border;
+ styleAttr.color = style.fontColor;
+ styleAttr.fontSize = style.fontSize + "px";
+ styleAttr.fontFamily = style.fontFace;
+ styleAttr.padding = this.padding + "px";
+ styleAttr.backgroundColor = style.color.background;
+ styleAttr.borderRadius = "3px";
+ styleAttr.MozBorderRadius = "3px";
+ styleAttr.WebkitBorderRadius = "3px";
+ styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
+ styleAttr.whiteSpace = "nowrap";
+ this.container.appendChild(this.frame);
}
/**
- * Draw a line between two nodes
- * @param {CanvasRenderingContext2D} ctx
- * @private
+ * @param {number} x Horizontal position of the popup window
+ * @param {number} y Vertical position of the popup window
*/
- Edge.prototype._line = function (ctx) {
- // draw a straight line
- ctx.beginPath();
- ctx.moveTo(this.from.x, this.from.y);
- if (this.options.smoothCurves.enabled == true) {
- if (this.options.smoothCurves.dynamic == false) {
- var via = this._getViaCoordinates();
- if (via.x == null) {
- ctx.lineTo(this.to.x, this.to.y);
- ctx.stroke();
- return null;
- }
- else {
- // this.via.x = via.x;
- // this.via.y = via.y;
- ctx.quadraticCurveTo(via.x,via.y,this.to.x, this.to.y);
- ctx.stroke();
- return via;
- }
- }
- else {
- ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
- ctx.stroke();
- return this.via;
- }
- }
- else {
- ctx.lineTo(this.to.x, this.to.y);
- ctx.stroke();
- return null;
- }
+ Popup.prototype.setPosition = function(x, y) {
+ this.x = parseInt(x);
+ this.y = parseInt(y);
};
/**
- * Draw a line from a node to itself, a circle
- * @param {CanvasRenderingContext2D} ctx
- * @param {Number} x
- * @param {Number} y
- * @param {Number} radius
- * @private
+ * Set the content for the popup window. This can be HTML code or text.
+ * @param {string | Element} content
*/
- Edge.prototype._circle = function (ctx, x, y, radius) {
- // draw a circle
- ctx.beginPath();
- ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
- ctx.stroke();
+ Popup.prototype.setText = function(content) {
+ if (content instanceof Element) {
+ this.frame.innerHTML = '';
+ this.frame.appendChild(content);
+ }
+ else {
+ this.frame.innerHTML = content; // string containing text or HTML
+ }
};
/**
- * Draw label with white background and with the middle at (x, y)
- * @param {CanvasRenderingContext2D} ctx
- * @param {String} text
- * @param {Number} x
- * @param {Number} y
- * @private
+ * Show the popup window
+ * @param {boolean} show Optional. Show or hide the window
*/
- Edge.prototype._label = function (ctx, text, x, y) {
- if (text) {
- ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
- this.options.fontSize + "px " + this.options.fontFace;
- var yLine;
-
- if (this.dirtyLabel == true) {
- var lines = String(text).split('\n');
- var lineCount = lines.length;
- var fontSize = (Number(this.options.fontSize) + 4);
- yLine = y + (1 - lineCount) / 2 * fontSize;
+ Popup.prototype.show = function (show) {
+ if (show === undefined) {
+ show = true;
+ }
- var width = ctx.measureText(lines[0]).width;
- for (var i = 1; i < lineCount; i++) {
- var lineWidth = ctx.measureText(lines[i]).width;
- width = lineWidth > width ? lineWidth : width;
- }
- var height = this.options.fontSize * lineCount;
- var left = x - width / 2;
- var top = y - height / 2;
+ if (show) {
+ var height = this.frame.clientHeight;
+ var width = this.frame.clientWidth;
+ var maxHeight = this.frame.parentNode.clientHeight;
+ var maxWidth = this.frame.parentNode.clientWidth;
- // cache
- this.labelDimensions = {top:top,left:left,width:width,height:height,yLine:yLine};
+ var top = (this.y - height);
+ if (top + height + this.padding > maxHeight) {
+ top = maxHeight - height - this.padding;
}
-
-
- if (this.options.fontFill !== undefined && this.options.fontFill !== null && this.options.fontFill !== "none") {
- ctx.fillStyle = this.options.fontFill;
- ctx.fillRect(this.labelDimensions.left,
- this.labelDimensions.top,
- this.labelDimensions.width,
- this.labelDimensions.height);
+ if (top < this.padding) {
+ top = this.padding;
}
- // draw text
- ctx.fillStyle = this.options.fontColor || "black";
- ctx.textAlign = "center";
- ctx.textBaseline = "middle";
- yLine = this.labelDimensions.yLine;
- for (var i = 0; i < lineCount; i++) {
- ctx.fillText(lines[i], x, yLine);
- yLine += fontSize;
+ var left = this.x;
+ if (left + width + this.padding > maxWidth) {
+ left = maxWidth - width - this.padding;
}
+ if (left < this.padding) {
+ left = this.padding;
+ }
+
+ this.frame.style.left = left + "px";
+ this.frame.style.top = top + "px";
+ this.frame.style.visibility = "visible";
+ }
+ else {
+ this.hide();
}
};
/**
- * Redraw a edge as a dashed line
- * Draw this edge in the given canvas
- * @author David Jordan
- * @date 2012-08-08
- * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
- * @param {CanvasRenderingContext2D} ctx
- * @private
+ * Hide the popup window
*/
- Edge.prototype._drawDashLine = function(ctx) {
- // set style
- if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight;}
- else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover;}
- else {ctx.strokeStyle = this.options.color.color;}
-
- ctx.lineWidth = this._getLineWidth();
+ Popup.prototype.hide = function () {
+ this.frame.style.visibility = "hidden";
+ };
- var via = null;
- // only firefox and chrome support this method, else we use the legacy one.
- if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
- // configure the dash pattern
- var pattern = [0];
- if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) {
- pattern = [this.options.dash.length,this.options.dash.gap];
- }
- else {
- pattern = [5,5];
- }
+ module.exports = Popup;
- // set dash settings for chrome or firefox
- if (typeof ctx.setLineDash !== 'undefined') { //Chrome
- ctx.setLineDash(pattern);
- ctx.lineDashOffset = 0;
- } else { //Firefox
- ctx.mozDash = pattern;
- ctx.mozDashOffset = 0;
- }
+/***/ },
+/* 52 */
+/***/ function(module, exports, __webpack_require__) {
- // draw the line
- via = this._line(ctx);
+ /**
+ * Parse a text source containing data in DOT language into a JSON object.
+ * The object contains two lists: one with nodes and one with edges.
+ *
+ * DOT language reference: http://www.graphviz.org/doc/info/lang.html
+ *
+ * @param {String} data Text containing a graph in DOT-notation
+ * @return {Object} graph An object containing two parameters:
+ * {Object[]} nodes
+ * {Object[]} edges
+ */
+ function parseDOT (data) {
+ dot = data;
+ return parseGraph();
+ }
- // restore the dash settings.
- if (typeof ctx.setLineDash !== 'undefined') { //Chrome
- ctx.setLineDash([0]);
- ctx.lineDashOffset = 0;
+ // token types enumeration
+ var TOKENTYPE = {
+ NULL : 0,
+ DELIMITER : 1,
+ IDENTIFIER: 2,
+ UNKNOWN : 3
+ };
- } else { //Firefox
- ctx.mozDash = [0];
- ctx.mozDashOffset = 0;
- }
- }
- else { // unsupporting smooth lines
- // draw dashed line
- ctx.beginPath();
- ctx.lineCap = 'round';
- if (this.options.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
- {
- ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
- [this.options.dash.length,this.options.dash.gap,this.options.dash.altLength,this.options.dash.gap]);
- }
- else if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) //If a dash and gap value has been set add to the array this value
- {
- ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
- [this.options.dash.length,this.options.dash.gap]);
- }
- else //If all else fails draw a line
- {
- ctx.moveTo(this.from.x, this.from.y);
- ctx.lineTo(this.to.x, this.to.y);
- }
- ctx.stroke();
- }
+ // map with all delimiters
+ var DELIMITERS = {
+ '{': true,
+ '}': true,
+ '[': true,
+ ']': true,
+ ';': true,
+ '=': true,
+ ',': true,
- // draw label
- if (this.label) {
- var point;
- if (this.options.smoothCurves.enabled == true && via != null) {
- var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
- var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
- point = {x:midpointX, y:midpointY};
- }
- else {
- point = this._pointOnLine(0.5);
- }
- this._label(ctx, this.label, point.x, point.y);
- }
+ '->': true,
+ '--': true
};
+ var dot = ''; // current dot file
+ var index = 0; // current index in dot file
+ var c = ''; // current token character in expr
+ var token = ''; // current token
+ var tokenType = TOKENTYPE.NULL; // type of the token
+
/**
- * Get a point on a line
- * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
- * @return {Object} point
- * @private
+ * Get the first character from the dot file.
+ * The character is stored into the char c. If the end of the dot file is
+ * reached, the function puts an empty string in c.
*/
- Edge.prototype._pointOnLine = function (percentage) {
- return {
- x: (1 - percentage) * this.from.x + percentage * this.to.x,
- y: (1 - percentage) * this.from.y + percentage * this.to.y
- }
- };
+ function first() {
+ index = 0;
+ c = dot.charAt(0);
+ }
/**
- * Get a point on a circle
- * @param {Number} x
- * @param {Number} y
- * @param {Number} radius
- * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
- * @return {Object} point
- * @private
+ * Get the next character from the dot file.
+ * The character is stored into the char c. If the end of the dot file is
+ * reached, the function puts an empty string in c.
*/
- Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
- var angle = (percentage - 3/8) * 2 * Math.PI;
- return {
- x: x + radius * Math.cos(angle),
- y: y - radius * Math.sin(angle)
- }
- };
+ function next() {
+ index++;
+ c = dot.charAt(index);
+ }
/**
- * Redraw a edge as a line with an arrow halfway the line
- * Draw this edge in the given canvas
- * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
- * @param {CanvasRenderingContext2D} ctx
- * @private
+ * Preview the next character from the dot file.
+ * @return {String} cNext
*/
- Edge.prototype._drawArrowCenter = function(ctx) {
- var point;
- // set style
- if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight; ctx.fillStyle = this.options.color.highlight;}
- else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover; ctx.fillStyle = this.options.color.hover;}
- else {ctx.strokeStyle = this.options.color.color; ctx.fillStyle = this.options.color.color;}
- ctx.lineWidth = this._getLineWidth();
+ function nextPreview() {
+ return dot.charAt(index + 1);
+ }
- if (this.from != this.to) {
- // draw line
- var via = this._line(ctx);
+ /**
+ * Test whether given character is alphabetic or numeric
+ * @param {String} c
+ * @return {Boolean} isAlphaNumeric
+ */
+ var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
+ function isAlphaNumeric(c) {
+ return regexAlphaNumeric.test(c);
+ }
- var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
- var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
- // draw an arrow halfway the line
- if (this.options.smoothCurves.enabled == true && via != null) {
- var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
- var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
- point = {x:midpointX, y:midpointY};
+ /**
+ * Merge all properties of object b into object b
+ * @param {Object} a
+ * @param {Object} b
+ * @return {Object} a
+ */
+ function merge (a, b) {
+ if (!a) {
+ a = {};
+ }
+
+ if (b) {
+ for (var name in b) {
+ if (b.hasOwnProperty(name)) {
+ a[name] = b[name];
+ }
+ }
+ }
+ return a;
+ }
+
+ /**
+ * Set a value in an object, where the provided parameter name can be a
+ * path with nested parameters. For example:
+ *
+ * var obj = {a: 2};
+ * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
+ *
+ * @param {Object} obj
+ * @param {String} path A parameter name or dot-separated parameter path,
+ * like "color.highlight.border".
+ * @param {*} value
+ */
+ function setValue(obj, path, value) {
+ var keys = path.split('.');
+ var o = obj;
+ while (keys.length) {
+ var key = keys.shift();
+ if (keys.length) {
+ // this isn't the end point
+ if (!o[key]) {
+ o[key] = {};
+ }
+ o = o[key];
}
else {
- point = this._pointOnLine(0.5);
+ // this is the end point
+ o[key] = value;
}
+ }
+ }
- ctx.arrow(point.x, point.y, angle, length);
- ctx.fill();
- ctx.stroke();
+ /**
+ * Add a node to a graph object. If there is already a node with
+ * the same id, their attributes will be merged.
+ * @param {Object} graph
+ * @param {Object} node
+ */
+ function addNode(graph, node) {
+ var i, len;
+ var current = null;
- // draw label
- if (this.label) {
- this._label(ctx, this.label, point.x, point.y);
+ // find root graph (in case of subgraph)
+ var graphs = [graph]; // list with all graphs from current graph to root graph
+ var root = graph;
+ while (root.parent) {
+ graphs.push(root.parent);
+ root = root.parent;
+ }
+
+ // find existing node (at root level) by its id
+ if (root.nodes) {
+ for (i = 0, len = root.nodes.length; i < len; i++) {
+ if (node.id === root.nodes[i].id) {
+ current = root.nodes[i];
+ break;
+ }
}
}
- else {
- // draw circle
- var x, y;
- var radius = 0.25 * Math.max(100,this.physics.springLength);
- var node = this.from;
- if (!node.width) {
- node.resize(ctx);
+
+ if (!current) {
+ // this is a new node
+ current = {
+ id: node.id
+ };
+ if (graph.node) {
+ // clone default attributes
+ current.attr = merge(current.attr, graph.node);
}
- if (node.width > node.height) {
- x = node.x + node.width * 0.5;
- y = node.y - radius;
+ }
+
+ // add node to this (sub)graph and all its parent graphs
+ for (i = graphs.length - 1; i >= 0; i--) {
+ var g = graphs[i];
+
+ if (!g.nodes) {
+ g.nodes = [];
}
- else {
- x = node.x + radius;
- y = node.y - node.height * 0.5;
+ if (g.nodes.indexOf(current) == -1) {
+ g.nodes.push(current);
}
- this._circle(ctx, x, y, radius);
+ }
- // draw all arrows
- var angle = 0.2 * Math.PI;
- var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
- point = this._pointOnCircle(x, y, radius, 0.5);
- ctx.arrow(point.x, point.y, angle, length);
- ctx.fill();
- ctx.stroke();
+ // merge attributes
+ if (node.attr) {
+ current.attr = merge(current.attr, node.attr);
+ }
+ }
- // draw label
- if (this.label) {
- point = this._pointOnCircle(x, y, radius, 0.5);
- this._label(ctx, this.label, point.x, point.y);
- }
+ /**
+ * Add an edge to a graph object
+ * @param {Object} graph
+ * @param {Object} edge
+ */
+ function addEdge(graph, edge) {
+ if (!graph.edges) {
+ graph.edges = [];
}
- };
+ graph.edges.push(edge);
+ if (graph.edge) {
+ var attr = merge({}, graph.edge); // clone default attributes
+ edge.attr = merge(attr, edge.attr); // merge attributes
+ }
+ }
+
+ /**
+ * Create an edge to a graph object
+ * @param {Object} graph
+ * @param {String | Number | Object} from
+ * @param {String | Number | Object} to
+ * @param {String} type
+ * @param {Object | null} attr
+ * @return {Object} edge
+ */
+ function createEdge(graph, from, to, type, attr) {
+ var edge = {
+ from: from,
+ to: to,
+ type: type
+ };
+ if (graph.edge) {
+ edge.attr = merge({}, graph.edge); // clone default attributes
+ }
+ edge.attr = merge(edge.attr || {}, attr); // merge attributes
+ return edge;
+ }
/**
- * Redraw a edge as a line with an arrow
- * Draw this edge in the given canvas
- * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
- * @param {CanvasRenderingContext2D} ctx
- * @private
+ * Get next token in the current dot file.
+ * The token and token type are available as token and tokenType
*/
- Edge.prototype._drawArrow = function(ctx) {
- // set style
- if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight; ctx.fillStyle = this.options.color.highlight;}
- else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover; ctx.fillStyle = this.options.color.hover;}
- else {ctx.strokeStyle = this.options.color.color; ctx.fillStyle = this.options.color.color;}
-
- ctx.lineWidth = this._getLineWidth();
+ function getToken() {
+ tokenType = TOKENTYPE.NULL;
+ token = '';
- var angle, length;
- //draw a line
- if (this.from != this.to) {
- angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
- var dx = (this.to.x - this.from.x);
- var dy = (this.to.y - this.from.y);
- var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
+ // skip over whitespaces
+ while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
+ next();
+ }
- var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
- var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
- var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
- var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
+ do {
+ var isComment = false;
- var via;
- if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true ) {
- via = this.via;
+ // skip comment
+ if (c == '#') {
+ // find the previous non-space character
+ var i = index - 1;
+ while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
+ i--;
+ }
+ if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
+ // the # is at the start of a line, this is indeed a line comment
+ while (c != '' && c != '\n') {
+ next();
+ }
+ isComment = true;
+ }
}
- else if (this.options.smoothCurves.enabled == true) {
- via = this._getViaCoordinates();
+ if (c == '/' && nextPreview() == '/') {
+ // skip line comment
+ while (c != '' && c != '\n') {
+ next();
+ }
+ isComment = true;
}
-
- if (this.options.smoothCurves.enabled == true && via.x != null) {
- angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x));
- dx = (this.to.x - via.x);
- dy = (this.to.y - via.y);
- edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
+ if (c == '/' && nextPreview() == '*') {
+ // skip block comment
+ while (c != '') {
+ if (c == '*' && nextPreview() == '/') {
+ // end of block comment found. skip these last two characters
+ next();
+ next();
+ break;
+ }
+ else {
+ next();
+ }
+ }
+ isComment = true;
}
- var toBorderDist = this.to.distanceToBorder(ctx, angle);
- var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
- var xTo,yTo;
- if (this.options.smoothCurves.enabled == true && via.x != null) {
- xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x;
- yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y;
- }
- else {
- xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
- yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
+ // skip over whitespaces
+ while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
+ next();
}
+ }
+ while (isComment);
- ctx.beginPath();
- ctx.moveTo(xFrom,yFrom);
- if (this.options.smoothCurves.enabled == true && via.x != null) {
- ctx.quadraticCurveTo(via.x,via.y,xTo, yTo);
- }
- else {
- ctx.lineTo(xTo, yTo);
- }
- ctx.stroke();
+ // check for end of dot file
+ if (c == '') {
+ // token is still empty
+ tokenType = TOKENTYPE.DELIMITER;
+ return;
+ }
- // draw arrow at the end of the line
- length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
- ctx.arrow(xTo, yTo, angle, length);
- ctx.fill();
- ctx.stroke();
+ // check for delimiters consisting of 2 characters
+ var c2 = c + nextPreview();
+ if (DELIMITERS[c2]) {
+ tokenType = TOKENTYPE.DELIMITER;
+ token = c2;
+ next();
+ next();
+ return;
+ }
- // draw label
- if (this.label) {
- var point;
- if (this.options.smoothCurves.enabled == true && via != null) {
- var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
- var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
- point = {x:midpointX, y:midpointY};
- }
- else {
- point = this._pointOnLine(0.5);
- }
- this._label(ctx, this.label, point.x, point.y);
- }
+ // check for delimiters consisting of 1 character
+ if (DELIMITERS[c]) {
+ tokenType = TOKENTYPE.DELIMITER;
+ token = c;
+ next();
+ return;
}
- else {
- // draw circle
- var node = this.from;
- var x, y, arrow;
- var radius = 0.25 * Math.max(100,this.physics.springLength);
- if (!node.width) {
- node.resize(ctx);
+
+ // check for an identifier (number or string)
+ // TODO: more precise parsing of numbers/strings (and the port separator ':')
+ if (isAlphaNumeric(c) || c == '-') {
+ token += c;
+ next();
+
+ while (isAlphaNumeric(c)) {
+ token += c;
+ next();
}
- if (node.width > node.height) {
- x = node.x + node.width * 0.5;
- y = node.y - radius;
- arrow = {
- x: x,
- y: node.y,
- angle: 0.9 * Math.PI
- };
+ if (token == 'false') {
+ token = false; // convert to boolean
}
- else {
- x = node.x + radius;
- y = node.y - node.height * 0.5;
- arrow = {
- x: node.x,
- y: y,
- angle: 0.6 * Math.PI
- };
+ else if (token == 'true') {
+ token = true; // convert to boolean
}
- ctx.beginPath();
- // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
- ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
- ctx.stroke();
-
- // draw all arrows
- var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
- ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
- ctx.fill();
- ctx.stroke();
-
- // draw label
- if (this.label) {
- point = this._pointOnCircle(x, y, radius, 0.5);
- this._label(ctx, this.label, point.x, point.y);
+ else if (!isNaN(Number(token))) {
+ token = Number(token); // convert to number
}
+ tokenType = TOKENTYPE.IDENTIFIER;
+ return;
}
- };
-
-
- /**
- * Calculate the distance between a point (x3,y3) and a line segment from
- * (x1,y1) to (x2,y2).
- * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
- * @param {number} x1
- * @param {number} y1
- * @param {number} x2
- * @param {number} y2
- * @param {number} x3
- * @param {number} y3
- * @private
- */
- Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
- var returnValue = 0;
- if (this.from != this.to) {
- if (this.options.smoothCurves.enabled == true) {
- var xVia, yVia;
- if (this.options.smoothCurves.enabled == true && this.options.smoothCurves.dynamic == true) {
- xVia = this.via.x;
- yVia = this.via.y;
- }
- else {
- var via = this._getViaCoordinates();
- xVia = via.x;
- yVia = via.y;
- }
- var minDistance = 1e9;
- var distance;
- var i,t,x,y, lastX, lastY;
- for (i = 0; i < 10; i++) {
- t = 0.1*i;
- x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*xVia + Math.pow(t,2)*x2;
- y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*yVia + Math.pow(t,2)*y2;
- if (i > 0) {
- distance = this._getDistanceToLine(lastX,lastY,x,y, x3,y3);
- minDistance = distance < minDistance ? distance : minDistance;
- }
- lastX = x; lastY = y;
+ // check for a string enclosed by double quotes
+ if (c == '"') {
+ next();
+ while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
+ token += c;
+ if (c == '"') { // skip the escape character
+ next();
}
- returnValue = minDistance;
+ next();
}
- else {
- returnValue = this._getDistanceToLine(x1,y1,x2,y2,x3,y3);
+ if (c != '"') {
+ throw newSyntaxError('End of string " expected');
}
+ next();
+ tokenType = TOKENTYPE.IDENTIFIER;
+ return;
}
- else {
- var x, y, dx, dy;
- var radius = 0.25 * this.physics.springLength;
- var node = this.from;
- if (node.width > node.height) {
- x = node.x + 0.5 * node.width;
- y = node.y - radius;
- }
- else {
- x = node.x + radius;
- y = node.y - 0.5 * node.height;
- }
- dx = x - x3;
- dy = y - y3;
- returnValue = Math.abs(Math.sqrt(dx*dx + dy*dy) - radius);
+
+ // something unknown is found, wrong characters, a syntax error
+ tokenType = TOKENTYPE.UNKNOWN;
+ while (c != '') {
+ token += c;
+ next();
}
+ throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
+ }
- if (this.labelDimensions.left < x3 &&
- this.labelDimensions.left + this.labelDimensions.width > x3 &&
- this.labelDimensions.top < y3 &&
- this.labelDimensions.top + this.labelDimensions.height > y3) {
- return 0;
+ /**
+ * Parse a graph.
+ * @returns {Object} graph
+ */
+ function parseGraph() {
+ var graph = {};
+
+ first();
+ getToken();
+
+ // optional strict keyword
+ if (token == 'strict') {
+ graph.strict = true;
+ getToken();
}
- else {
- return returnValue;
+
+ // graph or digraph keyword
+ if (token == 'graph' || token == 'digraph') {
+ graph.type = token;
+ getToken();
}
- };
- Edge.prototype._getDistanceToLine = function(x1,y1,x2,y2,x3,y3) {
- var px = x2-x1,
- py = y2-y1,
- something = px*px + py*py,
- u = ((x3 - x1) * px + (y3 - y1) * py) / something;
+ // optional graph id
+ if (tokenType == TOKENTYPE.IDENTIFIER) {
+ graph.id = token;
+ getToken();
+ }
- if (u > 1) {
- u = 1;
+ // open angle bracket
+ if (token != '{') {
+ throw newSyntaxError('Angle bracket { expected');
}
- else if (u < 0) {
- u = 0;
+ getToken();
+
+ // statements
+ parseStatements(graph);
+
+ // close angle bracket
+ if (token != '}') {
+ throw newSyntaxError('Angle bracket } expected');
}
+ getToken();
- var x = x1 + u * px,
- y = y1 + u * py,
- dx = x - x3,
- dy = y - y3;
+ // end of file
+ if (token !== '') {
+ throw newSyntaxError('End of file expected');
+ }
+ getToken();
- //# Note: If the actual distance does not matter,
- //# if you only want to compare what this function
- //# returns to other results of this function, you
- //# can just return the squared distance instead
- //# (i.e. remove the sqrt) to gain a little performance
+ // remove temporary default properties
+ delete graph.node;
+ delete graph.edge;
+ delete graph.graph;
- return Math.sqrt(dx*dx + dy*dy);
+ return graph;
}
/**
- * This allows the zoom level of the network to influence the rendering
- *
- * @param scale
+ * Parse a list with statements.
+ * @param {Object} graph
*/
- Edge.prototype.setScale = function(scale) {
- this.networkScaleInv = 1.0/scale;
- };
-
+ function parseStatements (graph) {
+ while (token !== '' && token != '}') {
+ parseStatement(graph);
+ if (token == ';') {
+ getToken();
+ }
+ }
+ }
- Edge.prototype.select = function() {
- this.selected = true;
- };
+ /**
+ * Parse a single statement. Can be a an attribute statement, node
+ * statement, a series of node statements and edge statements, or a
+ * parameter.
+ * @param {Object} graph
+ */
+ function parseStatement(graph) {
+ // parse subgraph
+ var subgraph = parseSubgraph(graph);
+ if (subgraph) {
+ // edge statements
+ parseEdge(graph, subgraph);
- Edge.prototype.unselect = function() {
- this.selected = false;
- };
+ return;
+ }
- Edge.prototype.positionBezierNode = function() {
- if (this.via !== null && this.from !== null && this.to !== null) {
- this.via.x = 0.5 * (this.from.x + this.to.x);
- this.via.y = 0.5 * (this.from.y + this.to.y);
+ // parse an attribute statement
+ var attr = parseAttributeStatement(graph);
+ if (attr) {
+ return;
}
- };
- /**
- * This function draws the control nodes for the manipulator. In order to enable this, only set the this.controlNodesEnabled to true.
- * @param ctx
- */
- Edge.prototype._drawControlNodes = function(ctx) {
- if (this.controlNodesEnabled == true) {
- if (this.controlNodes.from === null && this.controlNodes.to === null) {
- var nodeIdFrom = "edgeIdFrom:".concat(this.id);
- var nodeIdTo = "edgeIdTo:".concat(this.id);
- var constants = {
- nodes:{group:'', radius:8},
- physics:{damping:0},
- clustering: {maxNodeSizeIncrements: 0 ,nodeScaling: {width:0, height: 0, radius:0}}
- };
- this.controlNodes.from = new Node(
- {id:nodeIdFrom,
- shape:'dot',
- color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}}
- },{},{},constants);
- this.controlNodes.to = new Node(
- {id:nodeIdTo,
- shape:'dot',
- color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}}
- },{},{},constants);
- }
+ // parse node
+ if (tokenType != TOKENTYPE.IDENTIFIER) {
+ throw newSyntaxError('Identifier expected');
+ }
+ var id = token; // id can be a string or a number
+ getToken();
- if (this.controlNodes.from.selected == false && this.controlNodes.to.selected == false) {
- this.controlNodes.positions = this.getControlNodePositions(ctx);
- this.controlNodes.from.x = this.controlNodes.positions.from.x;
- this.controlNodes.from.y = this.controlNodes.positions.from.y;
- this.controlNodes.to.x = this.controlNodes.positions.to.x;
- this.controlNodes.to.y = this.controlNodes.positions.to.y;
+ if (token == '=') {
+ // id statement
+ getToken();
+ if (tokenType != TOKENTYPE.IDENTIFIER) {
+ throw newSyntaxError('Identifier expected');
}
-
- this.controlNodes.from.draw(ctx);
- this.controlNodes.to.draw(ctx);
+ graph[id] = token;
+ getToken();
+ // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
}
else {
- this.controlNodes = {from:null, to:null, positions:{}};
+ parseNodeStatement(graph, id);
}
- };
+ }
/**
- * Enable control nodes.
- * @private
+ * Parse a subgraph
+ * @param {Object} graph parent graph object
+ * @return {Object | null} subgraph
*/
- Edge.prototype._enableControlNodes = function() {
- this.controlNodesEnabled = true;
- };
+ function parseSubgraph (graph) {
+ var subgraph = null;
+
+ // optional subgraph keyword
+ if (token == 'subgraph') {
+ subgraph = {};
+ subgraph.type = 'subgraph';
+ getToken();
+
+ // optional graph id
+ if (tokenType == TOKENTYPE.IDENTIFIER) {
+ subgraph.id = token;
+ getToken();
+ }
+ }
+
+ // open angle bracket
+ if (token == '{') {
+ getToken();
+
+ if (!subgraph) {
+ subgraph = {};
+ }
+ subgraph.parent = graph;
+ subgraph.node = graph.node;
+ subgraph.edge = graph.edge;
+ subgraph.graph = graph.graph;
+
+ // statements
+ parseStatements(subgraph);
+
+ // close angle bracket
+ if (token != '}') {
+ throw newSyntaxError('Angle bracket } expected');
+ }
+ getToken();
+
+ // remove temporary default properties
+ delete subgraph.node;
+ delete subgraph.edge;
+ delete subgraph.graph;
+ delete subgraph.parent;
+
+ // register at the parent graph
+ if (!graph.subgraphs) {
+ graph.subgraphs = [];
+ }
+ graph.subgraphs.push(subgraph);
+ }
- /**
- * disable control nodes
- * @private
- */
- Edge.prototype._disableControlNodes = function() {
- this.controlNodesEnabled = false;
- };
+ return subgraph;
+ }
/**
- * This checks if one of the control nodes is selected and if so, returns the control node object. Else it returns null.
- * @param x
- * @param y
- * @returns {null}
- * @private
+ * parse an attribute statement like "node [shape=circle fontSize=16]".
+ * Available keywords are 'node', 'edge', 'graph'.
+ * The previous list with default attributes will be replaced
+ * @param {Object} graph
+ * @returns {String | null} keyword Returns the name of the parsed attribute
+ * (node, edge, graph), or null if nothing
+ * is parsed.
*/
- Edge.prototype._getSelectedControlNode = function(x,y) {
- var positions = this.controlNodes.positions;
- var fromDistance = Math.sqrt(Math.pow(x - positions.from.x,2) + Math.pow(y - positions.from.y,2));
- var toDistance = Math.sqrt(Math.pow(x - positions.to.x ,2) + Math.pow(y - positions.to.y ,2));
+ function parseAttributeStatement (graph) {
+ // attribute statements
+ if (token == 'node') {
+ getToken();
- if (fromDistance < 15) {
- this.connectedNode = this.from;
- this.from = this.controlNodes.from;
- return this.controlNodes.from;
+ // node attributes
+ graph.node = parseAttributeList();
+ return 'node';
}
- else if (toDistance < 15) {
- this.connectedNode = this.to;
- this.to = this.controlNodes.to;
- return this.controlNodes.to;
+ else if (token == 'edge') {
+ getToken();
+
+ // edge attributes
+ graph.edge = parseAttributeList();
+ return 'edge';
}
- else {
- return null;
+ else if (token == 'graph') {
+ getToken();
+
+ // graph attributes
+ graph.graph = parseAttributeList();
+ return 'graph';
}
- };
+ return null;
+ }
/**
- * this resets the control nodes to their original position.
- * @private
+ * parse a node statement
+ * @param {Object} graph
+ * @param {String | Number} id
*/
- Edge.prototype._restoreControlNodes = function() {
- if (this.controlNodes.from.selected == true) {
- this.from = this.connectedNode;
- this.connectedNode = null;
- this.controlNodes.from.unselect();
- }
- if (this.controlNodes.to.selected == true) {
- this.to = this.connectedNode;
- this.connectedNode = null;
- this.controlNodes.to.unselect();
+ function parseNodeStatement(graph, id) {
+ // node statement
+ var node = {
+ id: id
+ };
+ var attr = parseAttributeList();
+ if (attr) {
+ node.attr = attr;
}
- };
+ addNode(graph, node);
+
+ // edge statements
+ parseEdge(graph, id);
+ }
/**
- * this calculates the position of the control nodes on the edges of the parent nodes.
- *
- * @param ctx
- * @returns {{from: {x: number, y: number}, to: {x: *, y: *}}}
+ * Parse an edge or a series of edges
+ * @param {Object} graph
+ * @param {String | Number} from Id of the from node
*/
- Edge.prototype.getControlNodePositions = function(ctx) {
- var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
- var dx = (this.to.x - this.from.x);
- var dy = (this.to.y - this.from.y);
- var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
- var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
- var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
- var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
- var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
+ function parseEdge(graph, from) {
+ while (token == '->' || token == '--') {
+ var to;
+ var type = token;
+ getToken();
- var via;
- if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true) {
- via = this.via;
- }
- else if (this.options.smoothCurves.enabled == true) {
- via = this._getViaCoordinates();
- }
+ var subgraph = parseSubgraph(graph);
+ if (subgraph) {
+ to = subgraph;
+ }
+ else {
+ if (tokenType != TOKENTYPE.IDENTIFIER) {
+ throw newSyntaxError('Identifier or subgraph expected');
+ }
+ to = token;
+ addNode(graph, {
+ id: to
+ });
+ getToken();
+ }
- if (this.options.smoothCurves.enabled == true && via.x != null) {
- angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x));
- dx = (this.to.x - via.x);
- dy = (this.to.y - via.y);
- edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
- }
- var toBorderDist = this.to.distanceToBorder(ctx, angle);
- var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
+ // parse edge attributes
+ var attr = parseAttributeList();
- var xTo,yTo;
- if (this.options.smoothCurves.enabled == true && via.x != null) {
- xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x;
- yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y;
- }
- else {
- xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
- yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
+ // create edge
+ var edge = createEdge(graph, from, to, type, attr);
+ addEdge(graph, edge);
+
+ from = to;
}
+ }
- return {from:{x:xFrom,y:yFrom},to:{x:xTo,y:yTo}};
- };
+ /**
+ * Parse a set with attributes,
+ * for example [label="1.000", shape=solid]
+ * @return {Object | null} attr
+ */
+ function parseAttributeList() {
+ var attr = null;
- module.exports = Edge;
+ while (token == '[') {
+ getToken();
+ attr = {};
+ while (token !== '' && token != ']') {
+ if (tokenType != TOKENTYPE.IDENTIFIER) {
+ throw newSyntaxError('Attribute name expected');
+ }
+ var name = token;
-/***/ },
-/* 53 */
-/***/ function(module, exports, __webpack_require__) {
+ getToken();
+ if (token != '=') {
+ throw newSyntaxError('Equal sign = expected');
+ }
+ getToken();
- /**
- * Popup is a class to create a popup window with some text
- * @param {Element} container The container object.
- * @param {Number} [x]
- * @param {Number} [y]
- * @param {String} [text]
- * @param {Object} [style] An object containing borderColor,
- * backgroundColor, etc.
- */
- function Popup(container, x, y, text, style) {
- if (container) {
- this.container = container;
- }
- else {
- this.container = document.body;
- }
+ if (tokenType != TOKENTYPE.IDENTIFIER) {
+ throw newSyntaxError('Attribute value expected');
+ }
+ var value = token;
+ setValue(attr, name, value); // name can be a path
- // x, y and text are optional, see if a style object was passed in their place
- if (style === undefined) {
- if (typeof x === "object") {
- style = x;
- x = undefined;
- } else if (typeof text === "object") {
- style = text;
- text = undefined;
- } else {
- // for backwards compatibility, in case clients other than Network are creating Popup directly
- style = {
- fontColor: 'black',
- fontSize: 14, // px
- fontFace: 'verdana',
- color: {
- border: '#666',
- background: '#FFFFC6'
- }
+ getToken();
+ if (token ==',') {
+ getToken();
}
}
- }
-
- this.x = 0;
- this.y = 0;
- this.padding = 5;
- if (x !== undefined && y !== undefined ) {
- this.setPosition(x, y);
- }
- if (text !== undefined) {
- this.setText(text);
+ if (token != ']') {
+ throw newSyntaxError('Bracket ] expected');
+ }
+ getToken();
}
- // create the frame
- this.frame = document.createElement("div");
- var styleAttr = this.frame.style;
- styleAttr.position = "absolute";
- styleAttr.visibility = "hidden";
- styleAttr.border = "1px solid " + style.color.border;
- styleAttr.color = style.fontColor;
- styleAttr.fontSize = style.fontSize + "px";
- styleAttr.fontFamily = style.fontFace;
- styleAttr.padding = this.padding + "px";
- styleAttr.backgroundColor = style.color.background;
- styleAttr.borderRadius = "3px";
- styleAttr.MozBorderRadius = "3px";
- styleAttr.WebkitBorderRadius = "3px";
- styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
- styleAttr.whiteSpace = "nowrap";
- this.container.appendChild(this.frame);
+ return attr;
+ }
+
+ /**
+ * Create a syntax error with extra information on current token and index.
+ * @param {String} message
+ * @returns {SyntaxError} err
+ */
+ function newSyntaxError(message) {
+ return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
}
/**
- * @param {number} x Horizontal position of the popup window
- * @param {number} y Vertical position of the popup window
+ * Chop off text after a maximum length
+ * @param {String} text
+ * @param {Number} maxLength
+ * @returns {String}
*/
- Popup.prototype.setPosition = function(x, y) {
- this.x = parseInt(x);
- this.y = parseInt(y);
- };
+ function chop (text, maxLength) {
+ return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
+ }
/**
- * Set the content for the popup window. This can be HTML code or text.
- * @param {string | Element} content
+ * Execute a function fn for each pair of elements in two arrays
+ * @param {Array | *} array1
+ * @param {Array | *} array2
+ * @param {function} fn
*/
- Popup.prototype.setText = function(content) {
- if (content instanceof Element) {
- this.frame.innerHTML = '';
- this.frame.appendChild(content);
+ function forEach2(array1, array2, fn) {
+ if (Array.isArray(array1)) {
+ array1.forEach(function (elem1) {
+ if (Array.isArray(array2)) {
+ array2.forEach(function (elem2) {
+ fn(elem1, elem2);
+ });
+ }
+ else {
+ fn(elem1, array2);
+ }
+ });
}
else {
- this.frame.innerHTML = content; // string containing text or HTML
+ if (Array.isArray(array2)) {
+ array2.forEach(function (elem2) {
+ fn(array1, elem2);
+ });
+ }
+ else {
+ fn(array1, array2);
+ }
}
- };
+ }
/**
- * Show the popup window
- * @param {boolean} show Optional. Show or hide the window
+ * Convert a string containing a graph in DOT language into a map containing
+ * with nodes and edges in the format of graph.
+ * @param {String} data Text containing a graph in DOT-notation
+ * @return {Object} graphData
*/
- Popup.prototype.show = function (show) {
- if (show === undefined) {
- show = true;
- }
+ function DOTToGraph (data) {
+ // parse the DOT file
+ var dotData = parseDOT(data);
+ var graphData = {
+ nodes: [],
+ edges: [],
+ options: {}
+ };
- if (show) {
- var height = this.frame.clientHeight;
- var width = this.frame.clientWidth;
- var maxHeight = this.frame.parentNode.clientHeight;
- var maxWidth = this.frame.parentNode.clientWidth;
+ // copy the nodes
+ if (dotData.nodes) {
+ dotData.nodes.forEach(function (dotNode) {
+ var graphNode = {
+ id: dotNode.id,
+ label: String(dotNode.label || dotNode.id)
+ };
+ merge(graphNode, dotNode.attr);
+ if (graphNode.image) {
+ graphNode.shape = 'image';
+ }
+ graphData.nodes.push(graphNode);
+ });
+ }
- var top = (this.y - height);
- if (top + height + this.padding > maxHeight) {
- top = maxHeight - height - this.padding;
- }
- if (top < this.padding) {
- top = this.padding;
+ // copy the edges
+ if (dotData.edges) {
+ /**
+ * Convert an edge in DOT format to an edge with VisGraph format
+ * @param {Object} dotEdge
+ * @returns {Object} graphEdge
+ */
+ function convertEdge(dotEdge) {
+ var graphEdge = {
+ from: dotEdge.from,
+ to: dotEdge.to
+ };
+ merge(graphEdge, dotEdge.attr);
+ graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
+ return graphEdge;
}
- var left = this.x;
- if (left + width + this.padding > maxWidth) {
- left = maxWidth - width - this.padding;
- }
- if (left < this.padding) {
- left = this.padding;
+ dotData.edges.forEach(function (dotEdge) {
+ var from, to;
+ if (dotEdge.from instanceof Object) {
+ from = dotEdge.from.nodes;
+ }
+ else {
+ from = {
+ id: dotEdge.from
+ }
+ }
+
+ if (dotEdge.to instanceof Object) {
+ to = dotEdge.to.nodes;
+ }
+ else {
+ to = {
+ id: dotEdge.to
+ }
+ }
+
+ if (dotEdge.from instanceof Object && dotEdge.from.edges) {
+ dotEdge.from.edges.forEach(function (subEdge) {
+ var graphEdge = convertEdge(subEdge);
+ graphData.edges.push(graphEdge);
+ });
+ }
+
+ forEach2(from, to, function (from, to) {
+ var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
+ var graphEdge = convertEdge(subEdge);
+ graphData.edges.push(graphEdge);
+ });
+
+ if (dotEdge.to instanceof Object && dotEdge.to.edges) {
+ dotEdge.to.edges.forEach(function (subEdge) {
+ var graphEdge = convertEdge(subEdge);
+ graphData.edges.push(graphEdge);
+ });
+ }
+ });
+ }
+
+ // copy the options
+ if (dotData.attr) {
+ graphData.options = dotData.attr;
+ }
+
+ return graphData;
+ }
+
+ // exports
+ exports.parseDOT = parseDOT;
+ exports.DOTToGraph = DOTToGraph;
+
+
+/***/ },
+/* 53 */
+/***/ function(module, exports, __webpack_require__) {
+
+
+ function parseGephi(gephiJSON, options) {
+ var edges = [];
+ var nodes = [];
+ this.options = {
+ edges: {
+ inheritColor: true
+ },
+ nodes: {
+ allowedToMove: false,
+ parseColor: false
}
+ };
- this.frame.style.left = left + "px";
- this.frame.style.top = top + "px";
- this.frame.style.visibility = "visible";
+ if (options !== undefined) {
+ this.options.nodes['allowedToMove'] = options.allowedToMove | false;
+ this.options.nodes['parseColor'] = options.parseColor | false;
+ this.options.edges['inheritColor'] = options.inheritColor | true;
}
- else {
- this.hide();
+
+ var gEdges = gephiJSON.edges;
+ var gNodes = gephiJSON.nodes;
+ for (var i = 0; i < gEdges.length; i++) {
+ var edge = {};
+ var gEdge = gEdges[i];
+ edge['id'] = gEdge.id;
+ edge['from'] = gEdge.source;
+ edge['to'] = gEdge.target;
+ edge['attributes'] = gEdge.attributes;
+ // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined;
+ // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size;
+ edge['color'] = gEdge.color;
+ edge['inheritColor'] = edge['color'] !== undefined ? false : this.options.inheritColor;
+ edges.push(edge);
}
- };
- /**
- * Hide the popup window
- */
- Popup.prototype.hide = function () {
- this.frame.style.visibility = "hidden";
- };
+ for (var i = 0; i < gNodes.length; i++) {
+ var node = {};
+ var gNode = gNodes[i];
+ node['id'] = gNode.id;
+ node['attributes'] = gNode.attributes;
+ node['x'] = gNode.x;
+ node['y'] = gNode.y;
+ node['label'] = gNode.label;
+ if (this.options.nodes.parseColor == true) {
+ node['color'] = gNode.color;
+ }
+ else {
+ node['color'] = gNode.color !== undefined ? {background:gNode.color, border:gNode.color} : undefined;
+ }
+ node['radius'] = gNode.size;
+ node['allowedToMoveX'] = this.options.nodes.allowedToMove;
+ node['allowedToMoveY'] = this.options.nodes.allowedToMove;
+ nodes.push(node);
+ }
- module.exports = Popup;
+ return {nodes:nodes, edges:edges};
+ }
+ exports.parseGephi = parseGephi;
/***/ },
/* 54 */
@@ -30554,7 +30559,7 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ function(module, exports, __webpack_require__) {
var util = __webpack_require__(1);
- var Node = __webpack_require__(51);
+ var Node = __webpack_require__(48);
/**
* Creation of the SectorMixin var.
@@ -31112,7 +31117,7 @@ return /******/ (function(modules) { // webpackBootstrap
/* 61 */
/***/ function(module, exports, __webpack_require__) {
- var Node = __webpack_require__(51);
+ var Node = __webpack_require__(48);
/**
* This function can be called from the _doInAllSectors function
@@ -31601,21 +31606,23 @@ return /******/ (function(modules) { // webpackBootstrap
* @private
*/
exports._handleTap = function(pointer) {
- var node = this._getNodeAt(pointer);
- if (node != null) {
- this._selectObject(node,false);
- }
- else {
- var edge = this._getEdgeAt(pointer);
- if (edge != null) {
- this._selectObject(edge,false);
+ if (this.constants.selectable == true) {
+ var node = this._getNodeAt(pointer);
+ if (node != null) {
+ this._selectObject(node, false);
}
else {
- this._unselectAll();
+ var edge = this._getEdgeAt(pointer);
+ if (edge != null) {
+ this._selectObject(edge, false);
+ }
+ else {
+ this._unselectAll();
+ }
}
+ this.emit("click", this.getSelection());
+ this._redraw();
}
- this.emit("click", this.getSelection());
- this._redraw();
};
@@ -31827,8 +31834,8 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ function(module, exports, __webpack_require__) {
var util = __webpack_require__(1);
- var Node = __webpack_require__(51);
- var Edge = __webpack_require__(52);
+ var Node = __webpack_require__(48);
+ var Edge = __webpack_require__(47);
/**
* clears the toolbar div element of children
diff --git a/docs/network.html b/docs/network.html
index 866b43b8..30cc70ca 100644
--- a/docs/network.html
+++ b/docs/network.html
@@ -2287,9 +2287,9 @@ var options: {
or in percentages.