Browse Source

Merged develop branch

v3_develop
jos 10 years ago
parent
commit
6d8df70efd
136 changed files with 93204 additions and 34163 deletions
  1. +0
    -1
      .npmignore
  2. +48
    -0
      HISTORY.md
  3. +0
    -208
      Jakefile.js
  4. +129
    -9
      README.md
  5. +2
    -3
      bower.json
  6. +26664
    -0
      dist/vis-light.js
  7. +1
    -1
      dist/vis.css
  8. +27005
    -25723
      dist/vis.js
  9. +1
    -0
      dist/vis.map
  10. +0
    -0
      dist/vis.min.css
  11. +15
    -14
      dist/vis.min.js
  12. +7
    -0
      docs/dataset.html
  13. +150
    -4
      docs/network.html
  14. +21
    -1
      docs/timeline.html
  15. +7
    -6
      examples/network/02_random_nodes.html
  16. +1
    -1
      examples/network/07_selections.html
  17. +1
    -0
      examples/network/23_hierarchical_layout.html
  18. +34
    -1
      examples/network/24_hierarchical_layout_userdefined.html
  19. +75
    -0
      examples/network/26_staticSmoothCurves.html
  20. +10109
    -0
      examples/network/27_world_cup_network.html
  21. +10053
    -0
      examples/network/28_world_cup_network_performance.html
  22. +10213
    -0
      examples/network/29_neighbourhood_highlight.html
  23. +166
    -0
      examples/network/30_importing_from_gephi.html
  24. +1
    -0
      examples/network/data/WorldCup2014.json
  25. +5
    -0
      examples/network/index.html
  26. +152
    -0
      gulpfile.js
  27. +69
    -0
      index.js
  28. +10
    -14
      lib/DOMutil.js
  29. +14
    -2
      lib/DataSet.js
  30. +5
    -0
      lib/DataView.js
  31. +135
    -0
      lib/graph3d/Camera.js
  32. +218
    -0
      lib/graph3d/Filter.js
  33. +32
    -1074
      lib/graph3d/Graph3d.js
  34. +11
    -0
      lib/graph3d/Point2d.js
  35. +85
    -0
      lib/graph3d/Point3d.js
  36. +346
    -0
      lib/graph3d/Slider.js
  37. +140
    -0
      lib/graph3d/StepNumber.js
  38. +28
    -0
      lib/hammerUtil.js
  39. +0
    -0
      lib/header.js
  40. +10
    -0
      lib/module/hammer.js
  41. +3
    -0
      lib/module/moment.js
  42. +320
    -84
      lib/network/Edge.js
  43. +14
    -11
      lib/network/Groups.js
  44. +2
    -0
      lib/network/Images.js
  45. +140
    -50
      lib/network/Network.js
  46. +40
    -28
      lib/network/Node.js
  47. +2
    -0
      lib/network/Popup.js
  48. +0
    -0
      lib/network/css/network-manipulation.css
  49. +0
    -0
      lib/network/css/network-navigation.css
  50. +826
    -0
      lib/network/dotparser.js
  51. +60
    -0
      lib/network/gephiParser.js
  52. +0
    -0
      lib/network/img/acceptDeleteIcon.png
  53. +0
    -0
      lib/network/img/addNodeIcon.png
  54. +0
    -0
      lib/network/img/backIcon.png
  55. +0
    -0
      lib/network/img/connectIcon.png
  56. +0
    -0
      lib/network/img/cross.png
  57. +0
    -0
      lib/network/img/cross2.png
  58. +0
    -0
      lib/network/img/deleteIcon.png
  59. +0
    -0
      lib/network/img/downArrow.png
  60. +0
    -0
      lib/network/img/editIcon.png
  61. +0
    -0
      lib/network/img/leftArrow.png
  62. +0
    -0
      lib/network/img/minus.png
  63. +0
    -0
      lib/network/img/plus.png
  64. +0
    -0
      lib/network/img/rightArrow.png
  65. +0
    -0
      lib/network/img/upArrow.png
  66. +0
    -0
      lib/network/img/zoomExtends.png
  67. +1137
    -0
      lib/network/mixins/ClusterMixin.js
  68. +322
    -0
      lib/network/mixins/HierarchicalLayoutMixin.js
  69. +576
    -0
      lib/network/mixins/ManipulationMixin.js
  70. +198
    -0
      lib/network/mixins/MixinLoader.js
  71. +181
    -0
      lib/network/mixins/NavigationMixin.js
  72. +548
    -0
      lib/network/mixins/SectorsMixin.js
  73. +705
    -0
      lib/network/mixins/SelectionMixin.js
  74. +393
    -0
      lib/network/mixins/physics/BarnesHutMixin.js
  75. +154
    -0
      lib/network/mixins/physics/HierarchialRepulsionMixin.js
  76. +708
    -0
      lib/network/mixins/physics/PhysicsMixin.js
  77. +58
    -0
      lib/network/mixins/physics/RepulsionMixin.js
  78. +0
    -0
      lib/network/shapes.js
  79. +8
    -2
      lib/timeline/DataStep.js
  80. +13
    -0
      lib/timeline/Graph2d.js
  81. +10
    -3
      lib/timeline/Range.js
  82. +18
    -22
      lib/timeline/Stack.js
  83. +4
    -0
      lib/timeline/TimeStep.js
  84. +22
    -0
      lib/timeline/Timeline.js
  85. +2
    -0
      lib/timeline/component/Component.js
  86. +5
    -1
      lib/timeline/component/CurrentTime.js
  87. +6
    -0
      lib/timeline/component/CustomTime.js
  88. +7
    -0
      lib/timeline/component/DataAxis.js
  89. +8
    -3
      lib/timeline/component/GraphGroup.js
  90. +10
    -3
      lib/timeline/component/Group.js
  91. +71
    -9
      lib/timeline/component/ItemSet.js
  92. +14
    -8
      lib/timeline/component/Legend.js
  93. +10
    -4
      lib/timeline/component/LineGraph.js
  94. +6
    -0
      lib/timeline/component/TimeAxis.js
  95. +0
    -0
      lib/timeline/component/css/animation.css
  96. +0
    -0
      lib/timeline/component/css/currenttime.css
  97. +0
    -0
      lib/timeline/component/css/customtime.css
  98. +0
    -0
      lib/timeline/component/css/dataaxis.css
  99. +0
    -0
      lib/timeline/component/css/item.css
  100. +0
    -0
      lib/timeline/component/css/itemset.css

+ 0
- 1
.npmignore View File

@ -1,6 +1,5 @@
misc
node_modules
src
test
tools
.idea

+ 48
- 0
HISTORY.md View File

@ -2,6 +2,54 @@
http://visjs.org
## 2014-07-22, version 3.1.0
### General
- Refactored the code to commonjs modules, which are browserifyable. This allows
to create custom builds.
### Timeline
- Implemented function `getVisibleItems()`, which returns the items visible
in the current window.
- Added options `margin.item.horizontal` and `margin.item.vertical`, which
allows to specify different margins horizontally/vertically.
- Removed check for number of arguments in callbacks `onAdd`, `onUpdate`,
`onRemove`, and `onMove`.
- Fixed items in groups sometimes being displayed but not positioned correctly.
- Fixed range where the `end` of the first is equal to the `start` of the second
sometimes being stacked instead of put besides each other when `item.margin=0`
due to round-off errors.
### Network (formerly named Graph)
- Expanded smoothCurves options for improved support for large clusters.
- Added multiple types of smoothCurve drawing for greatly improved performance.
- Option for inherited edge colors from connected nodes.
- Option to disable the drawing of nodes or edges on drag.
- Fixed support nodes not being cleaned up if edges are removed.
- Improved edge selection detection for long smooth curves.
- Fixed dot radius bug.
- Updated max velocity of nodes to three times it's original value.
- Made "stabilized" event fire every time the network stabilizes.
- Fixed drift in dragging nodes while zooming.
- Fixed recursively constructing of hierarchical layouts.
- Added borderWidth option for nodes.
- Implemented new Hierarchical view solver.
- Fixed an issue with selecting nodes when the web page is scrolled down.
- Added Gephi JSON parser
- Added Neighbour Highlight example
- Added Import From Gephi example
- Enabled color parsing for nodes when supplied with rgb(xxx,xxx,xxx) value.
### DataSet
- Added .get() returnType option to return as JSON object, Array or Google
DataTable.
## 2014-07-07, version 3.0.0
### Timeline

+ 0
- 208
Jakefile.js View File

@ -1,208 +0,0 @@
/**
* Jake build script
*/
var jake = require('jake'),
browserify = require('browserify'),
wrench = require('wrench'),
CleanCSS = require('clean-css'),
fs = require('fs');
require('jake-utils');
// constants
var DIST = './dist';
var VIS = DIST + '/vis.js';
var VIS_CSS = DIST + '/vis.css';
var VIS_TMP = DIST + '/vis.js.tmp';
var VIS_MIN = DIST + '/vis.min.js';
var VIS_MIN_CSS = DIST + '/vis.min.css';
/**
* default task
*/
desc('Default task: build all libraries');
task('default', ['build', 'minify'], function () {
console.log('done');
});
/**
* build the visualization library vis.js
*/
desc('Build the visualization library vis.js');
task('build', {async: true}, function () {
jake.mkdirP(DIST);
jake.mkdirP(DIST + '/img');
// concatenate and stringify the css files
concat({
src: [
'./src/timeline/component/css/timeline.css',
'./src/timeline/component/css/panel.css',
'./src/timeline/component/css/labelset.css',
'./src/timeline/component/css/itemset.css',
'./src/timeline/component/css/item.css',
'./src/timeline/component/css/timeaxis.css',
'./src/timeline/component/css/currenttime.css',
'./src/timeline/component/css/customtime.css',
'./src/timeline/component/css/animation.css',
'./src/timeline/component/css/dataaxis.css',
'./src/timeline/component/css/pathStyles.css',
'./src/network/css/network-manipulation.css',
'./src/network/css/network-navigation.css'
],
dest: VIS_CSS,
separator: '\n'
});
console.log('created ' + VIS_CSS);
// concatenate the script files
concat({
dest: VIS_TMP,
src: [
'./src/module/imports.js',
'./src/shim.js',
'./src/util.js',
'./src/DOMutil.js',
'./src/DataSet.js',
'./src/DataView.js',
'./src/timeline/component/GraphGroup.js',
'./src/timeline/component/Legend.js',
'./src/timeline/component/DataAxis.js',
'./src/timeline/component/LineGraph.js',
'./src/timeline/DataStep.js',
'./src/timeline/Stack.js',
'./src/timeline/TimeStep.js',
'./src/timeline/Range.js',
'./src/timeline/component/Component.js',
'./src/timeline/component/TimeAxis.js',
'./src/timeline/component/CurrentTime.js',
'./src/timeline/component/CustomTime.js',
'./src/timeline/component/ItemSet.js',
'./src/timeline/component/item/*.js',
'./src/timeline/component/Group.js',
'./src/timeline/Timeline.js',
'./src/timeline/Graph2d.js',
'./src/network/dotparser.js',
'./src/network/shapes.js',
'./src/network/Node.js',
'./src/network/Edge.js',
'./src/network/Popup.js',
'./src/network/Groups.js',
'./src/network/Images.js',
'./src/network/networkMixins/physics/PhysicsMixin.js',
'./src/network/networkMixins/physics/HierarchialRepulsion.js',
'./src/network/networkMixins/physics/BarnesHut.js',
'./src/network/networkMixins/physics/Repulsion.js',
'./src/network/networkMixins/HierarchicalLayoutMixin.js',
'./src/network/networkMixins/ManipulationMixin.js',
'./src/network/networkMixins/SectorsMixin.js',
'./src/network/networkMixins/ClusterMixin.js',
'./src/network/networkMixins/SelectionMixin.js',
'./src/network/networkMixins/NavigationMixin.js',
'./src/network/networkMixins/MixinLoader.js',
'./src/network/Network.js',
'./src/graph3d/Graph3d.js',
'./src/module/exports.js'
],
separator: '\n'
});
// copy images
wrench.copyDirSyncRecursive('./src/network/img', DIST + '/img/network', {
forceDelete: true
});
wrench.copyDirSyncRecursive('./src/timeline/img', DIST + '/img/timeline', {
forceDelete: true
});
var timeStart = Date.now();
// bundle the concatenated script and dependencies into one file
var b = browserify();
b.add(VIS_TMP);
b.bundle({
standalone: 'vis'
}, function (err, code) {
if(err) {
throw err;
}
console.log("browserify",Date.now() - timeStart); timeStart = Date.now();
// add header and footer
var lib = read('./src/module/header.js') + code;
// write bundled file
write(VIS, lib);
console.log('created js' + VIS);
// remove temporary file
fs.unlinkSync(VIS_TMP);
// update version number and stuff in the javascript files
replacePlaceholders(VIS);
complete();
});
});
/**
* minify the visualization library vis.js
*/
desc('Minify the visualization library vis.js');
task('minify', {async: true}, function () {
// minify javascript
minify({
src: VIS,
dest: VIS_MIN,
header: read('./src/module/header.js')
});
// update version number and stuff in the javascript files
replacePlaceholders(VIS_MIN);
console.log('created minified ' + VIS_MIN);
var minified = new CleanCSS().minify(read(VIS_CSS));
write(VIS_MIN_CSS, minified);
console.log('created minified ' + VIS_MIN_CSS);
});
/**
* test task
*/
desc('Test the library');
task('test', function () {
// TODO: use a testing suite for testing: nodeunit, mocha, tap, ...
var filelist = new jake.FileList();
filelist.include([
'./test/**/*.js'
]);
var files = filelist.toArray();
files.forEach(function (file) {
require('./' + file);
});
console.log('Executed ' + files.length + ' test files successfully');
});
/**
* replace version, date, and name placeholders in the provided file
* @param {String} filename
*/
var replacePlaceholders = function (filename) {
replace({
replacements: [
{pattern: '@@date', replacement: today()},
{pattern: '@@version', replacement: version()}
],
src: filename
});
};

+ 129
- 9
README.md View File

@ -57,7 +57,7 @@ or load vis.js using require.js. Note that vis.css must be loaded too.
```js
require.config({
paths: {
vis: 'path/to/vis',
vis: 'path/to/vis/dist',
}
});
require(['vis'], function (math) {
@ -124,15 +124,9 @@ To build the library from source, clone the project from github
git clone git://github.com/almende/vis.git
The project uses [jake](https://github.com/mde/jake) as build tool.
The build script uses [Browserify](http://browserify.org/) to
bundle the source code into a library,
and uses [UglifyJS](http://lisperator.net/uglifyjs/) to minify the code.
The source code uses the module style of node (require and module.exports) to
organize dependencies.
To install all dependencies and build the library, run `npm install` in the
root of the project.
organize dependencies. To install all dependencies and build the library,
run `npm install` in the root of the project.
cd vis
npm install
@ -141,6 +135,132 @@ Then, the project can be build running:
npm run build
To automatically rebuild on changes in the source files, once can use
npm run watch
This will both build and minify the library on changes. Minifying is relatively
slow, so when only the non-minified library is needed, one can use the
`watch-dev` script instead:
npm run watch-dev
## Custom builds
The folder `dist` contains bundled versions of vis.js for direct use in the browser. These bundles contain the all visualizations and includes external dependencies such as hammer.js and moment.js.
The source code of vis.js consists of commonjs modules, which makes it possible to create custom bundles using tools like [Browserify](http://browserify.org/) or [Webpack](http://webpack.github.io/). This can be bundling just one visualization like the Timeline, or bundling vis.js as part of your own browserified web application. Note that hammer.js v1.0.6 or newer is required.
#### Example 1: Bundle a single visualization
For example, to create a bundle with just the Timeline and DataSet, create an index file named **custom.js** in the root of the project, containing:
```js
exports.DataSet = require('./lib/DataSet');
exports.Timeline = require('./lib/timeline/Timeline');
```
Install browserify globally via `[sudo] npm install -g browserify`, then create a custom bundle like:
browserify custom.js -o vis-custom.js -s vis
This will generate a custom bundle *vis-custom.js*, which exposes the namespace `vis` containing only `DataSet` and `Timeline`. The generated bundle can be minified with uglifyjs (installed globally with `[sudo] npm install -g uglify-js`):
uglifyjs vis-custom.js -o vis-custom.min.js
The custom bundle can now be loaded like:
```html
<!DOCTYPE HTML>
<html>
<head>
<script src="vis-custom.min.js"></script>
<link href="dist/vis.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
...
</body>
</html>
```
#### Example 2: Exclude external libraries
The default bundle `vis.js` is standalone and includes external dependencies such as hammer.js and moment.js. When these libraries are already loaded by the application, vis.js does not need to include these dependencies itself too. To build a custom bundle of vis.js excluding moment.js and hammer.js, run browserify in the root of the project:
browserify index.js -o vis-custom.js -s vis -x moment -x hammerjs
This will generate a custom bundle *vis-custom.js*, which exposes the namespace `vis`, and has moment and hammerjs excluded. The generated bundle can be minified with uglifyjs:
uglifyjs vis-custom.js -o vis-custom.min.js
The custom bundle can now be loaded as:
```html
<!DOCTYPE HTML>
<html>
<head>
<!-- load external dependencies -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.7.0/moment.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/hammer.js/1.1.3/hammer.min.js"></script>
<!-- load vis.js -->
<script src="vis-custom.min.js"></script>
<link href="dist/vis.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
...
</body>
</html>
```
#### Example 3: Bundle vis.js as part of your (commonjs) application
When writing a web application with commonjs modules, vis.js can be packaged automatically into the application. Create a file **app.js** containing:
```js
var moment = require('moment');
var DataSet = require('vis/lib/DataSet');
var Timeline = require('vis/lib/timeline/Timeline');
var container = document.getElementById('visualization');
var data = new DataSet([
{id: 1, content: 'item 1', start: moment('2013-04-20')},
{id: 2, content: 'item 2', start: moment('2013-04-14')},
{id: 3, content: 'item 3', start: moment('2013-04-18')},
{id: 4, content: 'item 4', start: moment('2013-04-16'), end: moment('2013-04-19')},
{id: 5, content: 'item 5', start: moment('2013-04-25')},
{id: 6, content: 'item 6', start: moment('2013-04-27')}
]);
var options = {};
var timeline = new Timeline(container, data, options);
```
Install the application dependencies via npm:
npm install vis moment
The application can be bundled and minified:
browserify app.js -o app-bundle.js
uglifyjs app-bundle.js -o app-bundle.min.js
And loaded into a webpage:
```html
<!DOCTYPE HTML>
<html>
<head>
<link href="node_modules/vis/dist/vis.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="visualization"></div>
<script src="app-bundle.min.js"></script>
</body>
</html>
```
## Test

+ 2
- 3
bower.json View File

@ -1,6 +1,6 @@
{
"name": "vis",
"version": "3.0.0",
"version": "3.1.0",
"description": "A dynamic, browser-based visualization library.",
"homepage": "http://visjs.org/",
"repository": {
@ -10,11 +10,10 @@
"ignore": [
"misc",
"node_modules",
"src",
"test",
"tools",
".idea",
"Jakefile.js",
"gulpfile.js",
"package.json",
".npmignore",
".gitignore"

+ 26664
- 0
dist/vis-light.js
File diff suppressed because it is too large
View File


+ 1
- 1
dist/vis.css View File

@ -703,4 +703,4 @@ div.network-navigation.zoomExtends {
background-image: url("img/network/zoomExtends.png");
bottom:50px;
right:15px;
}
}

+ 27005
- 25723
dist/vis.js
File diff suppressed because it is too large
View File


+ 1
- 0
dist/vis.map
File diff suppressed because it is too large
View File


+ 0
- 0
dist/vis.min.css View File


+ 15
- 14
dist/vis.min.js
File diff suppressed because it is too large
View File


+ 7
- 0
docs/dataset.html View File

@ -691,6 +691,13 @@ DataSet.map(callback [, options]);
<td>Order the items by a field name or custom sort function.</td>
</tr>
<tr>
<td>returnType</td>
<td>String</td>
<td>Determine the type of output of the get function. Allowed values are <code>Array | Object | DataTable</code>.
The <code>DataTable</code> refers to a Google DataTable. The default returnType is an array. The object type will return a JSON object with the ID's as keys.</td>
</tr>
</table>
<p>

+ 150
- 4
docs/network.html View File

@ -54,6 +54,7 @@
<li><a href="#Nodes">Nodes</a></li>
<li><a href="#Edges">Edges</a></li>
<li><a href="#DOT_language">DOT language</a></li>
<li><a href="#Gephi_import">Gephi import</a></li>
</ul>
</li>
<li>
@ -262,6 +263,21 @@ When using a DataSet, the network is automatically updating to changes in the Da
<th>Description</th>
</tr>
<tr>
<td>borderWidth</td>
<td>Number</td>
<td>1</td>
<td>The width of the border of the node when it is not selected, automatically limited by the width of the node.</td>
</tr>
<tr>
<td>borderWidthSelected</td>
<td>Number</td>
<td>undefined</td>
<td>The width of the border of the node when it is selected. If left at undefined, double the borderWidth will be used.</td>
</tr>
<tr>
<td>color</td>
<td>String | Object</td>
@ -672,6 +688,14 @@ When using a DataSet, the network is automatically updating to changes in the Da
<td>physics.[method].springLength</td>
<td>The resting length of the edge when modeled as a spring. By default the springLength determined by the physics is used. By using this setting you can make certain edges have different resting lengths.</td>
</tr>
<tr>
<td>inheritColor</td>
<td>String | Boolean</td>
<td>false</td>
<td>Possible values: <code>"to","from", true, false</code>. If this value is set to false, the edge color information is used. If the value is set to true or "from",
the color data from the borders of the "from" node is used. If this value is "to", the color data from the borders of the "to" node is used.</td>
</tr>
<tr>
<td>title</td>
<td>string | function</td>
@ -736,7 +760,85 @@ var data = {
var network = new vis.Network(container, data);
</pre>
<h3 id="Gephi_import">Gephi import (JSON)</h3>
<p>
network can import data straight from an exported json file from gephi. You can get the JSON exporter here:
<a href="https://marketplace.gephi.org/plugin/json-exporter/" target="_blank">https://marketplace.gephi.org/plugin/json-exporter/</a>.
An example exists showing how to get a JSON file into Vis: <a href="../examples/Network/30_importing_from_gephi.html">30_importing_from_gephi</a>.
</p>
<p>
Example usage:
</p>
<pre class="prettyprint lang-js">
// load the JSON file containing the Gephi network.
var gephiJSON = loadJSON("./data/WorldCup2014.json"); // code in example 30
// create a data object with the gephi key:
var data = {
gephi: gephiJSON
};
// create a network
var network = new vis.Network(container, data);
</pre>
Alternatively you can use the parser manually:
<pre class="prettyprint lang-js">
// load the JSON file containing the Gephi network.
var gephiJSON = loadJSON("./data/WorldCup2014.json"); // code in example 30
// parse the gephi file to receive an object
// containing nodes and edges in vis format.
var parsed = vis.network.gephiParser.parseGephi(gephiJSON);
// provide data in the normal fashion
var data = {
nodes: parsed.nodes,
edged: parsed.edges
};
// create a network
var network = new vis.Network(container, data);
</pre>
<h4>Gephi parser options</h4>
There are a few options you can use to tell Vis what to do with the data from Gephi.
<pre class="prettyprint lang-js">
var parserOptions = {
allowedToMove: false,
parseColor: false
}
var parsed = vis.network.gephiParser.parseGephi(gephiJSON, parserOptions);
</pre>
<table>
<tr>
<th>Name</th>
<th>Type</th>
<th>Default</th>
<th>Description</th>
</tr>
<tr>
<td>allowedToMove</td>
<td>Boolean</td>
<td>false</td>
<td>
If true, the nodes will move according to the physics model after import. If false, the nodes do not move at all.
</td>
</tr>
<tr>
<td>parseColor</td>
<td>Boolean</td>
<td>false</td>
<td>
If true, the color will be parsed by the vis parser, generating extra colors for the borders, highlighs and hover. If false, the node will be the supplied color.
</td>
</tr>
</table>
<h2 id="Configuration_options">Configuration options</h2>
@ -874,7 +976,22 @@ var options = {
Toggle if the nodes can be dragged. This will not affect the dragging of the network.
</td>
</tr>
<tr>
<td>hideNodesOnDrag</td>
<td>Boolean</td>
<td>false</td>
<td>
Toggle if the nodes are drawn during a drag. This can greatly improve performance if you have many nodes.
</td>
</tr>
<tr>
<td>hideEdgesOnDrag</td>
<td>Boolean</td>
<td>false</td>
<td>
Toggle if the edges are drawn during a drag. This can greatly improve performance if you have many edges.
</td>
</tr>
<tr>
<td><a href="#Navigation_controls">navigation</a></td>
<td>Object</td>
@ -895,11 +1012,31 @@ var options = {
<tr>
<td>smoothCurves</td>
<td>Boolean || object</td>
<td>object</td>
<td>If true, edges are drawn as smooth curves. This is more computationally intensive since the edge now is a quadratic Bezier curve. This can be further configured by the options below.</td>
</tr>
<tr>
<td>smoothCurves.dynamic</td>
<td>Boolean</td>
<td>true</td>
<td>If true, edges are drawn as smooth curves. This is more computationally intensive since the edge now is a quadratic Bezier curve with control points on both nodes and an invisible node in the center of the edge. This support node is also handed by the physics simulation.</td>
<td>By default, the edges are dynamic. This means there are support nodes placed in the middle of the edge. This support node is also handed by the physics simulation. If false, the smoothness will be based on the
relative positions of the to and from nodes. This is computationally cheaper but there is no self organisation.</td>
</tr>
<tr>
<td>smoothCurves.type</td>
<td>String</td>
<td>"continuous"</td>
<td>This option only affects NONdynamic smooth curves. The supported types are: <code>continuous, discrete, diagonalCross, straightCross, horizontal, vertical</code>. The effects of these types
are shown in examples <a href="../examples/Network/26_staticSmoothCurves.html">26</a> and <a href="../examples/Network/27_world_cup_network.html">27</a></td>
</tr>
<tr>
<td>smoothCurves.roundness</td>
<td>Number</td>
<td>0.5</td>
<td>This only affects NONdynamic smooth curves. The roundness can be tweaked with the parameter. The value range is from 0 to 1 with a maximum roundness at 0.5.</td>
</tr>
<tr>
<td>selectable</td>
<td>Boolean</td>
@ -1223,6 +1360,14 @@ var options = {
<td>The resting length of the edge when modeled as a spring. By default the springLength determined by the physics is used. By using this setting you can make certain edges have different resting lengths.</td>
</tr>
<tr>
<td>inheritColor</td>
<td>String | Boolean</td>
<td>false</td>
<td>Possible values: <code>"to","from", true, false</code>. If this value is set to false, the edge color information is used. If the value is set to true or "from",
the color data from the borders of the "from" node is used. If this value is "to", the color data from the borders of the "to" node is used.</td>
</tr>
<tr>
<td>style</td>
<td>String</td>
@ -2366,7 +2511,8 @@ network.off('select', onSelect);
</tr>
<tr>
<td>stabilized</td>
<td>Fired when the network has been stabilized after initialization. This event can be used to trigger the .storePosition() function after stabilization.</td>
<td>Fired when the network has been stabilized. This event can be used to trigger the .storePosition() function after stabilization. When the network in initialized, the parameter
iterations will be the amount of iterations it took to stabilize. After initialization, this parameter is null.</td>
<td>
<ul>
<li><code>iterations</code>: number of iterations used to stabilize</li>

+ 21
- 1
docs/timeline.html View File

@ -449,7 +449,21 @@ var options = {
<td>margin.item</td>
<td>Number</td>
<td>10</td>
<td>The minimal margin in pixels between items.</td>
<td>The minimal margin in pixels between items in both horizontal and vertical direction.</td>
</tr>
<tr>
<td>margin.item.horizontal</td>
<td>Number</td>
<td>10</td>
<td>The minimal horizontal margin in pixels between items.</td>
</tr>
<tr>
<td>margin.item.vertical</td>
<td>Number</td>
<td>10</td>
<td>The minimal vertical margin in pixels between items.</td>
</tr>
<tr>
@ -726,6 +740,12 @@ timeline.clear({options: true}); // clear options only
<td>Get an array with the ids of the currently selected items.</td>
</tr>
<tr>
<td>getVisibleItems()</td>
<td>Number[]</td>
<td>Get an array with the ids of the currently visible items.</td>
</tr>
<tr>
<td>getWindow()</td>
<td>Object</td>

+ 7
- 6
examples/network/02_random_nodes.html View File

@ -31,7 +31,8 @@
for (var i = 0; i < nodeCount; i++) {
nodes.push({
id: i,
label: String(i)
label: String(i),
radius:300
});
connectionCount[i] = 0;
@ -81,12 +82,12 @@
},
stabilize: false
};
network = new vis.Network(container, data, options);
network = new vis.Network(container, data, options);
// add event listeners
network.on('select', function(params) {
document.getElementById('selection').innerHTML = 'Selection: ' + params.nodes;
});
// add event listeners
network.on('select', function(params) {
document.getElementById('selection').innerHTML = 'Selection: ' + params.nodes;
});
}
</script>
</head>

+ 1
- 1
examples/network/07_selections.html View File

@ -56,7 +56,7 @@
});
// set initial selection (id's of some nodes)
network.setSelection([3, 4, 5]);
network.selectNodes([3, 4, 5]);
</script>
</body>

+ 1
- 0
examples/network/23_hierarchical_layout.html View File

@ -82,6 +82,7 @@
edges: {
},
stabilize: false,
smoothCurves: false,
hierarchicalLayout: {
direction: directionInput.value
}

+ 34
- 1
examples/network/24_hierarchical_layout_userdefined.html View File

@ -20,6 +20,7 @@
var nodes = null;
var edges = null;
var network = null;
var directionInput = document.getElementById("direction");
function draw() {
nodes = [];
@ -113,7 +114,9 @@
};
var options = {
hierarchicalLayout:true
hierarchicalLayout: {
direction: directionInput.value
}
};
network = new vis.Network(container, data, options);
@ -122,6 +125,7 @@
document.getElementById('selection').innerHTML = 'Selection: ' + params.nodes;
});
}
</script>
</head>
@ -129,11 +133,40 @@
<h2>Hierarchical Layout - User-defined</h2>
<div style="width:700px; font-size:14px;">
This example shows a user-defined hierarchical layout. If the user defines levels for nodes but does not do so for all nodes, an alert will show up and hierarchical layout will be disabled. Either all or none can be defined.
If the smooth curves appear to be inverted, the direction of the edge is not in the same direction as the network.
</div>
<input type="button" id="btn-UD" value="Up-Down">
<input type="button" id="btn-DU" value="Down-Up">
<input type="button" id="btn-LR" value="Left-Right">
<input type="button" id="btn-RL" value="Right-Left">
<input type="hidden" id='direction' value="UD">
<br />
<div id="mynetwork"></div>
<p id="selection"></p>
<script language="JavaScript">
var directionInput = document.getElementById("direction");
var btnUD = document.getElementById("btn-UD");
btnUD.onclick = function() {
directionInput.value = "UD";
draw();
}
var btnDU = document.getElementById("btn-DU");
btnDU.onclick = function() {
directionInput.value = "DU";
draw();
};
var btnLR = document.getElementById("btn-LR");
btnLR.onclick = function() {
directionInput.value = "LR";
draw();
};
var btnRL = document.getElementById("btn-RL");
btnRL.onclick = function() {
directionInput.value = "RL";
draw();
};
</script>
</body>
</html>

+ 75
- 0
examples/network/26_staticSmoothCurves.html View File

@ -0,0 +1,75 @@
<!doctype html>
<html>
<head>
<title>Network | Static smooth curves</title>
<script type="text/javascript" src="../../dist/vis.js"></script>
<style type="text/css">
#mynetwork {
width: 400px;
height: 400px;
border: 1px solid lightgray;
}
</style>
</head>
<body>
<h2>Static smooth curves</h2>
<div style="width:700px; font-size:14px;">
All the smooth curves in the examples so far have been using dynamic smooth curves. This means that each curve has a
support node which takes part in the physics simulation. For large networks or dense clusters, this may not be the ideal
solution. To solve this, static smooth curves have been added. The static smooth curves are based only on the positions of the connected
nodes. There are multiple ways to determine the way this curve is drawn. This example shows the effect of the different
types. <br /> <br />
Drag the nodes around each other to see how the smooth curves are drawn for each setting. For animated system, we
recommend only the continuous mode. In the next example you can see the effect of these methods on a large network. Keep in mind
that the direction (the from and to) of the curve matters.
<br /> <br />
</div>
Smooth curve type:
<select id="dropdownID">
<option value="continuous">continuous</option>
<option value="discrete">discrete</option>
<option value="diagonalCross">diagonalCross</option>
<option value="straightCross">straightCross</option>
<option value="horizontal">horizontal</option>
<option value="vertical">vertical</option>
</select>
<div id="mynetwork"></div>
<script type="text/javascript">
var dropdown = document.getElementById("dropdownID");
dropdown.onchange = update;
// create an array with nodes
var nodes = [
{id: 1, label: 'Node 1'},
{id: 2, label: 'Node 2', x:150, y:130, allowedToMoveX: true, allowedToMoveY: true}
];
// create an array with edges
var edges = [
{from: 1, to: 2}
];
// create a network
var container = document.getElementById('mynetwork');
var data = {
nodes: nodes,
edges: edges
};
var options = {physics:{barnesHut:{gravitationalConstant:0, springConstant:0, centralGravity: 0}},
smoothCurves:{dynamic:false, type: '1'}};
var network = new vis.Network(container, data, options);
function update() {
var type = dropdown.value;
network.setOptions({smoothCurves:{type:type}});
}
</script>
</body>
</html>

+ 10109
- 0
examples/network/27_world_cup_network.html
File diff suppressed because it is too large
View File


+ 10053
- 0
examples/network/28_world_cup_network_performance.html
File diff suppressed because it is too large
View File


+ 10213
- 0
examples/network/29_neighbourhood_highlight.html
File diff suppressed because it is too large
View File


+ 166
- 0
examples/network/30_importing_from_gephi.html View File

@ -0,0 +1,166 @@
<!DOCTYPE html>
<!-- saved from url=(0044)http://kenedict.com/networks/worldcup14/vis/ , thanks Andre!-->
<html><head><meta http-equiv="content-type" content="text/html; charset=UTF8">
<title>Dynamic Data - Importing from Gephi (JSON)</title>
<script type="text/javascript" src="../../dist/vis.js"></script>
<link type="text/css" rel="stylesheet" href="../../dist/vis.css">
<style type="text/css">
#mynetwork {
width: 800px;
height: 800px;
border: 1px solid lightgray;
}
div.nodeContent {
position: relative;
border: 1px solid lightgray;
width:480px;
height:780px;
margin-top: -802px;
margin-left: 810px;
padding:10px;
}
pre {padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>
</head>
<body>
<h2>Dynamic Data - Importing from Gephi (JSON)</h2>
<div style="width:700px; font-size:14px;">
This example shows how to import a JSON file exported by Gephi. The two options available for the import are
available through the checkboxes. You can download the Gephi JSON exporter here:
<a href="https://marketplace.gephi.org/plugin/json-exporter/" target="_blank">https://marketplace.gephi.org/plugin/json-exporter/</a>.
All of Gephi's attributes are also contained within the node elements. This means you can access all of this data through the DataSet.
<br />
</div>
<input type="checkbox" id="allowedToMove">: Allow to move after import. <br/>
<input type="checkbox" id="parseColor">: Parse the color instead of copy (adds borders, highlights etc.)
<div id="mynetwork"></div>
<div class="nodeContent"><h4>Node Content:</h4> <pre id="nodeContent"></pre></div>
<script type="text/javascript">
var network;
var nodes = new vis.DataSet();
var edges = new vis.DataSet();
var gephiImported;
var allowedToMoveCheckbox = document.getElementById("allowedToMove");
allowedToMoveCheckbox.onchange = redrawAll;
var parseColorCheckbox = document.getElementById("parseColor");
parseColorCheckbox.onchange = redrawAll;
var nodeContent = document.getElementById("nodeContent");
loadJSON("./data/WorldCup2014.json",redrawAll);
var container = document.getElementById('mynetwork');
var data = {
nodes: nodes,
edges: edges
};
var options = {
nodes: {
shape: 'dot',
fontFace: "Tahoma"
},
edges: {
width: 0.15,
inheritColor: "from"
},
tooltip: {
delay: 200,
fontSize: 12,
color: {
background: "#fff"
}
},
smoothCurves: {dynamic:false, type: "continuous"},
stabilize: false,
physics: {barnesHut: {gravitationalConstant: -10000, springConstant: 0.002, springLength: 150}},
hideEdgesOnDrag: true
};
network = new vis.Network(container, data, options);
/**
* This function fills the DataSets. These DataSets will update the network.
*/
function redrawAll(gephiJSON) {
if (gephiJSON.nodes === undefined) {
gephiJSON = gephiImported;
}
else {
gephiImported = gephiJSON;
}
nodes.clear();
edges.clear();
var allowedToMove = allowedToMoveCheckbox.checked;
var parseColor = parseColorCheckbox.checked;
var parsed = vis.network.gephiParser.parseGephi(gephiJSON, {allowedToMove:allowedToMove, parseColor:parseColor});
// add the parsed data to the DataSets.
nodes.add(parsed.nodes);
edges.add(parsed.edges);
var data = nodes.get(2); // get the data from node 2
nodeContent.innerHTML = syntaxHighlight(data); // show the data in the div
network.zoomExtent(); // zoom to fit
}
// from http://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript
function syntaxHighlight(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
function loadJSON(path, success, error) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
success(JSON.parse(xhr.responseText));
}
else {
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
</script>
</body></html>

+ 1
- 0
examples/network/data/WorldCup2014.json
File diff suppressed because it is too large
View File


+ 5
- 0
examples/network/index.html View File

@ -37,6 +37,11 @@
<p><a href="23_hierarchical_layout.html">23_hierarchical_layout.html</a></p>
<p><a href="24_hierarchical_layout_userdefined.html">24_hierarchical_layout_userdefined.html</a></p>
<p><a href="25_physics_configuration.html">25_physics_configuration.html</a></p>
<p><a href="26_staticSmoothCurves.html">26_staticSmoothCurves.html</a></p>
<p><a href="27_world_cup_network.html">27_world_cup_network.html</a></p>
<p><a href="28_world_cup_network_performance.html">28_world_cup_network_performance.html</a></p>
<p><a href="29_neighbourhood_highlight.html">29_neighbourhood_highlight.html</a></p>
<p><a href="30_importing_from_gephi.html">30_importing_from_gephi.html</a></p>
<p><a href="graphviz/graphviz_gallery.html">graphviz_gallery.html</a></p>
</div>

+ 152
- 0
gulpfile.js View File

@ -0,0 +1,152 @@
var fs = require('fs');
var gulp = require('gulp');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var minifyCSS = require('gulp-minify-css');
var rename = require("gulp-rename");
var webpack = require('webpack');
var uglify = require('uglify-js');
var rimraf = require('rimraf');
var merge = require('merge-stream');
var argv = require('yargs').argv;
var ENTRY = './index.js';
var HEADER = './lib/header.js';
var DIST = './dist';
var VIS_JS = 'vis.js';
var VIS_MAP = 'vis.map';
var VIS_MIN_JS = 'vis.min.js';
var VIS_CSS = 'vis.css';
var VIS_MIN_CSS = 'vis.min.css';
// generate banner with today's date and correct version
function createBanner() {
var today = gutil.date(new Date(), 'yyyy-mm-dd'); // today, formatted as yyyy-mm-dd
var version = require('./package.json').version;
return String(fs.readFileSync(HEADER))
.replace('@@date', today)
.replace('@@version', version);
}
var bannerPlugin = new webpack.BannerPlugin(createBanner(), {
entryOnly: true,
raw: true
});
// TODO: the moment.js language files should be excluded by default (they are quite big)
var webpackConfig = {
entry: ENTRY,
output: {
library: 'vis',
libraryTarget: 'umd',
path: DIST,
filename: VIS_JS,
sourcePrefix: ' '
},
// exclude requires of moment.js language files
module: {
wrappedContextRegExp: /$^/
},
plugins: [ bannerPlugin ],
cache: true
};
var uglifyConfig = {
outSourceMap: VIS_MAP,
output: {
comments: /@license/
}
};
// create a single instance of the compiler to allow caching
var compiler = webpack(webpackConfig);
// clean the dist/img directory
gulp.task('clean', function (cb) {
rimraf(DIST + '/img', cb);
});
gulp.task('bundle-js', ['clean'], function (cb) {
// update the banner contents (has a date in it which should stay up to date)
bannerPlugin.banner = createBanner();
compiler.run(function (err, stats) {
if (err) gutil.log(err);
cb();
});
});
// bundle and minify css
gulp.task('bundle-css', ['clean'], function () {
var files = [
'./lib/timeline/component/css/timeline.css',
'./lib/timeline/component/css/panel.css',
'./lib/timeline/component/css/labelset.css',
'./lib/timeline/component/css/itemset.css',
'./lib/timeline/component/css/item.css',
'./lib/timeline/component/css/timeaxis.css',
'./lib/timeline/component/css/currenttime.css',
'./lib/timeline/component/css/customtime.css',
'./lib/timeline/component/css/animation.css',
'./lib/timeline/component/css/dataaxis.css',
'./lib/timeline/component/css/pathStyles.css',
'./lib/network/css/network-manipulation.css',
'./lib/network/css/network-navigation.css'
];
return gulp.src(files)
.pipe(concat(VIS_CSS))
.pipe(gulp.dest(DIST))
// TODO: nicer to put minifying css in a separate task?
.pipe(minifyCSS())
.pipe(rename(VIS_MIN_CSS))
.pipe(gulp.dest(DIST));
});
gulp.task('copy', ['clean'], function () {
var network = gulp.src('./lib/network/img/**/*')
.pipe(gulp.dest(DIST + '/img/network'));
var timeline = gulp.src('./lib/timeline/img/**/*')
.pipe(gulp.dest(DIST + '/img/timeline'));
return merge(network, timeline);
});
gulp.task('minify', ['bundle-js'], function (cb) {
var result = uglify.minify([DIST + '/' + VIS_JS], uglifyConfig);
fs.writeFileSync(DIST + '/' + VIS_MIN_JS, result.code);
fs.writeFileSync(DIST + '/' + VIS_MAP, result.map);
cb();
});
gulp.task('bundle', ['bundle-js', 'bundle-css', 'copy']);
// read command line arguments --bundle and --minify
var bundle = 'bundle' in argv;
var minify = 'minify' in argv;
var watchTasks = [];
if (bundle || minify) {
// do bundling and/or minifying only when specified on the command line
watchTasks = [];
if (bundle) watchTasks.push('bundle');
if (minify) watchTasks.push('minify');
}
else {
// by default, do both bundling and minifying
watchTasks = ['bundle', 'minify'];
}
// The watch task (to automatically rebuild when the source code changes)
gulp.task('watch', watchTasks, function () {
gulp.watch(['index.js', 'lib/**/*'], watchTasks);
});
// The default task (called when you run `gulp`)
gulp.task('default', ['clean', 'bundle', 'minify']);

+ 69
- 0
index.js View File

@ -0,0 +1,69 @@
// utils
exports.util = require('./lib/util');
exports.DOMutil = require('./lib/DOMutil');
// data
exports.DataSet = require('./lib/DataSet');
exports.DataView = require('./lib/DataView');
// Graph3d
exports.Graph3d = require('./lib/graph3d/Graph3d');
exports.graph3d = {
Camera: require('./lib/graph3d/Camera'),
Filter: require('./lib/graph3d/Filter'),
Point2d: require('./lib/graph3d/Point2d'),
Point3d: require('./lib/graph3d/Point3d'),
Slider: require('./lib/graph3d/Slider'),
StepNumber: require('./lib/graph3d/StepNumber')
};
// Timeline
exports.Timeline = require('./lib/timeline/Timeline');
exports.Graph2d = require('./lib/timeline/Graph2d');
exports.timeline = {
DataStep: require('./lib/timeline/DataStep'),
Range: require('./lib/timeline/Range'),
stack: require('./lib/timeline/Stack'),
TimeStep: require('./lib/timeline/TimeStep'),
components: {
items: {
Item: require('./lib/timeline/component/item/Item'),
ItemBox: require('./lib/timeline/component/item/ItemBox'),
ItemPoint: require('./lib/timeline/component/item/ItemPoint'),
ItemRange: require('./lib/timeline/component/item/ItemRange')
},
Component: require('./lib/timeline/component/Component'),
CurrentTime: require('./lib/timeline/component/CurrentTime'),
CustomTime: require('./lib/timeline/component/CustomTime'),
DataAxis: require('./lib/timeline/component/DataAxis'),
GraphGroup: require('./lib/timeline/component/GraphGroup'),
Group: require('./lib/timeline/component/Group'),
ItemSet: require('./lib/timeline/component/ItemSet'),
Legend: require('./lib/timeline/component/Legend'),
LineGraph: require('./lib/timeline/component/LineGraph'),
TimeAxis: require('./lib/timeline/component/TimeAxis')
}
};
// Network
exports.Network = require('./lib/network/Network');
exports.network = {
Edge: require('./lib/network/Edge'),
Groups: require('./lib/network/Groups'),
Images: require('./lib/network/Images'),
Node: require('./lib/network/Node'),
Popup: require('./lib/network/Popup'),
dotparser: require('./lib/network/dotparser'),
gephiParser: require('./lib/network/gephiParser')
};
// Deprecated since v3.0.0
exports.Graph = function () {
throw new Error('Graph is renamed to Network. Please create a graph as new vis.Network(...)');
};
// bundled external libraries
exports.moment = require('./lib/module/moment');
exports.hammer = require('./lib/module/hammer');

src/DOMutil.js → lib/DOMutil.js View File

@ -1,15 +1,11 @@
/**
* Created by Alex on 6/20/14.
*/
var DOMutil = {};
// DOM utility methods
/**
* this prepares the JSON container for allocating SVG elements
* @param JSONcontainer
* @private
*/
DOMutil.prepareElements = function(JSONcontainer) {
exports.prepareElements = function(JSONcontainer) {
// cleanup the redundant svgElements;
for (var elementType in JSONcontainer) {
if (JSONcontainer.hasOwnProperty(elementType)) {
@ -26,7 +22,7 @@ DOMutil.prepareElements = function(JSONcontainer) {
* @param JSONcontainer
* @private
*/
DOMutil.cleanupElements = function(JSONcontainer) {
exports.cleanupElements = function(JSONcontainer) {
// cleanup the redundant svgElements;
for (var elementType in JSONcontainer) {
if (JSONcontainer.hasOwnProperty(elementType)) {
@ -50,7 +46,7 @@ DOMutil.cleanupElements = function(JSONcontainer) {
* @returns {*}
* @private
*/
DOMutil.getSVGElement = function (elementType, JSONcontainer, svgContainer) {
exports.getSVGElement = function (elementType, JSONcontainer, svgContainer) {
var element;
// allocate SVG element, if it doesnt yet exist, create one.
if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before
@ -86,7 +82,7 @@ DOMutil.getSVGElement = function (elementType, JSONcontainer, svgContainer) {
* @returns {*}
* @private
*/
DOMutil.getDOMElement = function (elementType, JSONcontainer, DOMContainer) {
exports.getDOMElement = function (elementType, JSONcontainer, DOMContainer) {
var element;
// allocate SVG element, if it doesnt yet exist, create one.
if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before
@ -126,17 +122,17 @@ DOMutil.getDOMElement = function (elementType, JSONcontainer, DOMContainer) {
* @param svgContainer
* @returns {*}
*/
DOMutil.drawPoint = function(x, y, group, JSONcontainer, svgContainer) {
exports.drawPoint = function(x, y, group, JSONcontainer, svgContainer) {
var point;
if (group.options.drawPoints.style == 'circle') {
point = DOMutil.getSVGElement('circle',JSONcontainer,svgContainer);
point = exports.getSVGElement('circle',JSONcontainer,svgContainer);
point.setAttributeNS(null, "cx", x);
point.setAttributeNS(null, "cy", y);
point.setAttributeNS(null, "r", 0.5 * group.options.drawPoints.size);
point.setAttributeNS(null, "class", group.className + " point");
}
else {
point = DOMutil.getSVGElement('rect',JSONcontainer,svgContainer);
point = exports.getSVGElement('rect',JSONcontainer,svgContainer);
point.setAttributeNS(null, "x", x - 0.5*group.options.drawPoints.size);
point.setAttributeNS(null, "y", y - 0.5*group.options.drawPoints.size);
point.setAttributeNS(null, "width", group.options.drawPoints.size);
@ -153,8 +149,8 @@ DOMutil.drawPoint = function(x, y, group, JSONcontainer, svgContainer) {
* @param y
* @param className
*/
DOMutil.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer) {
var rect = DOMutil.getSVGElement('rect',JSONcontainer, svgContainer);
exports.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer) {
var rect = exports.getSVGElement('rect',JSONcontainer, svgContainer);
rect.setAttributeNS(null, "x", x - 0.5 * width);
rect.setAttributeNS(null, "y", y);
rect.setAttributeNS(null, "width", width);

src/DataSet.js → lib/DataSet.js View File

@ -1,3 +1,5 @@
var util = require('./util');
/**
* DataSet
*
@ -320,7 +322,8 @@ DataSet.prototype.get = function (args) {
// determine the return type
var returnType;
if (options && options.returnType) {
returnType = (options.returnType == 'DataTable') ? 'DataTable' : 'Array';
var allowedValues = ["DataTable", "Array", "Object"];
returnType = allowedValues.indexOf(options.returnType) == -1 ? "Array" : options.returnType;
if (data && (returnType != util.getType(data))) {
throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
@ -399,12 +402,19 @@ DataSet.prototype.get = function (args) {
}
else {
// copy the items to the provided data table
for (i = 0, len = items.length; i < len; i++) {
for (i = 0; i < items.length; i++) {
me._appendRow(data, columns, items[i]);
}
}
return data;
}
else if (returnType == "Object") {
var result = {};
for (i = 0; i < items.length; i++) {
result[items[i].id] = items[i];
}
return result;
}
else {
// return an array
if (id != undefined) {
@ -932,3 +942,5 @@ DataSet.prototype._appendRow = function (dataTable, columns, item) {
dataTable.setValue(row, col, item[field]);
}
};
module.exports = DataSet;

src/DataView.js → lib/DataView.js View File

@ -1,3 +1,6 @@
var util = require('./util');
var DataSet = require('./DataSet');
/**
* DataView
*
@ -294,3 +297,5 @@ DataView.prototype._trigger = DataSet.prototype._trigger;
// TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
DataView.prototype.subscribe = DataView.prototype.on;
DataView.prototype.unsubscribe = DataView.prototype.off;
module.exports = DataView;

+ 135
- 0
lib/graph3d/Camera.js View File

@ -0,0 +1,135 @@
var Point3d = require('./Point3d');
/**
* @class Camera
* The camera is mounted on a (virtual) camera arm. The camera arm can rotate
* The camera is always looking in the direction of the origin of the arm.
* This way, the camera always rotates around one fixed point, the location
* of the camera arm.
*
* Documentation:
* http://en.wikipedia.org/wiki/3D_projection
*/
Camera = function () {
this.armLocation = new Point3d();
this.armRotation = {};
this.armRotation.horizontal = 0;
this.armRotation.vertical = 0;
this.armLength = 1.7;
this.cameraLocation = new Point3d();
this.cameraRotation = new Point3d(0.5*Math.PI, 0, 0);
this.calculateCameraOrientation();
};
/**
* Set the location (origin) of the arm
* @param {Number} x Normalized value of x
* @param {Number} y Normalized value of y
* @param {Number} z Normalized value of z
*/
Camera.prototype.setArmLocation = function(x, y, z) {
this.armLocation.x = x;
this.armLocation.y = y;
this.armLocation.z = z;
this.calculateCameraOrientation();
};
/**
* Set the rotation of the camera arm
* @param {Number} horizontal The horizontal rotation, between 0 and 2*PI.
* Optional, can be left undefined.
* @param {Number} vertical The vertical rotation, between 0 and 0.5*PI
* if vertical=0.5*PI, the graph is shown from the
* top. Optional, can be left undefined.
*/
Camera.prototype.setArmRotation = function(horizontal, vertical) {
if (horizontal !== undefined) {
this.armRotation.horizontal = horizontal;
}
if (vertical !== undefined) {
this.armRotation.vertical = vertical;
if (this.armRotation.vertical < 0) this.armRotation.vertical = 0;
if (this.armRotation.vertical > 0.5*Math.PI) this.armRotation.vertical = 0.5*Math.PI;
}
if (horizontal !== undefined || vertical !== undefined) {
this.calculateCameraOrientation();
}
};
/**
* Retrieve the current arm rotation
* @return {object} An object with parameters horizontal and vertical
*/
Camera.prototype.getArmRotation = function() {
var rot = {};
rot.horizontal = this.armRotation.horizontal;
rot.vertical = this.armRotation.vertical;
return rot;
};
/**
* Set the (normalized) length of the camera arm.
* @param {Number} length A length between 0.71 and 5.0
*/
Camera.prototype.setArmLength = function(length) {
if (length === undefined)
return;
this.armLength = length;
// Radius must be larger than the corner of the graph,
// which has a distance of sqrt(0.5^2+0.5^2) = 0.71 from the center of the
// graph
if (this.armLength < 0.71) this.armLength = 0.71;
if (this.armLength > 5.0) this.armLength = 5.0;
this.calculateCameraOrientation();
};
/**
* Retrieve the arm length
* @return {Number} length
*/
Camera.prototype.getArmLength = function() {
return this.armLength;
};
/**
* Retrieve the camera location
* @return {Point3d} cameraLocation
*/
Camera.prototype.getCameraLocation = function() {
return this.cameraLocation;
};
/**
* Retrieve the camera rotation
* @return {Point3d} cameraRotation
*/
Camera.prototype.getCameraRotation = function() {
return this.cameraRotation;
};
/**
* Calculate the location and rotation of the camera based on the
* position and orientation of the camera arm
*/
Camera.prototype.calculateCameraOrientation = function() {
// calculate location of the camera
this.cameraLocation.x = this.armLocation.x - this.armLength * Math.sin(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
this.cameraLocation.y = this.armLocation.y - this.armLength * Math.cos(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
this.cameraLocation.z = this.armLocation.z + this.armLength * Math.sin(this.armRotation.vertical);
// calculate rotation of the camera
this.cameraRotation.x = Math.PI/2 - this.armRotation.vertical;
this.cameraRotation.y = 0;
this.cameraRotation.z = -this.armRotation.horizontal;
};
module.exports = Camera;

+ 218
- 0
lib/graph3d/Filter.js View File

@ -0,0 +1,218 @@
var DataView = require('../DataView');
/**
* @class Filter
*
* @param {DataSet} data The google data table
* @param {Number} column The index of the column to be filtered
* @param {Graph} graph The graph
*/
function Filter (data, column, graph) {
this.data = data;
this.column = column;
this.graph = graph; // the parent graph
this.index = undefined;
this.value = undefined;
// read all distinct values and select the first one
this.values = graph.getDistinctValues(data.get(), this.column);
// sort both numeric and string values correctly
this.values.sort(function (a, b) {
return a > b ? 1 : a < b ? -1 : 0;
});
if (this.values.length > 0) {
this.selectValue(0);
}
// create an array with the filtered datapoints. this will be loaded afterwards
this.dataPoints = [];
this.loaded = false;
this.onLoadCallback = undefined;
if (graph.animationPreload) {
this.loaded = false;
this.loadInBackground();
}
else {
this.loaded = true;
}
};
/**
* Return the label
* @return {string} label
*/
Filter.prototype.isLoaded = function() {
return this.loaded;
};
/**
* Return the loaded progress
* @return {Number} percentage between 0 and 100
*/
Filter.prototype.getLoadedProgress = function() {
var len = this.values.length;
var i = 0;
while (this.dataPoints[i]) {
i++;
}
return Math.round(i / len * 100);
};
/**
* Return the label
* @return {string} label
*/
Filter.prototype.getLabel = function() {
return this.graph.filterLabel;
};
/**
* Return the columnIndex of the filter
* @return {Number} columnIndex
*/
Filter.prototype.getColumn = function() {
return this.column;
};
/**
* Return the currently selected value. Returns undefined if there is no selection
* @return {*} value
*/
Filter.prototype.getSelectedValue = function() {
if (this.index === undefined)
return undefined;
return this.values[this.index];
};
/**
* Retrieve all values of the filter
* @return {Array} values
*/
Filter.prototype.getValues = function() {
return this.values;
};
/**
* Retrieve one value of the filter
* @param {Number} index
* @return {*} value
*/
Filter.prototype.getValue = function(index) {
if (index >= this.values.length)
throw 'Error: index out of range';
return this.values[index];
};
/**
* Retrieve the (filtered) dataPoints for the currently selected filter index
* @param {Number} [index] (optional)
* @return {Array} dataPoints
*/
Filter.prototype._getDataPoints = function(index) {
if (index === undefined)
index = this.index;
if (index === undefined)
return [];
var dataPoints;
if (this.dataPoints[index]) {
dataPoints = this.dataPoints[index];
}
else {
var f = {};
f.column = this.column;
f.value = this.values[index];
var dataView = new DataView(this.data,{filter: function (item) {return (item[f.column] == f.value);}}).get();
dataPoints = this.graph._getDataPoints(dataView);
this.dataPoints[index] = dataPoints;
}
return dataPoints;
};
/**
* Set a callback function when the filter is fully loaded.
*/
Filter.prototype.setOnLoadCallback = function(callback) {
this.onLoadCallback = callback;
};
/**
* Add a value to the list with available values for this filter
* No double entries will be created.
* @param {Number} index
*/
Filter.prototype.selectValue = function(index) {
if (index >= this.values.length)
throw 'Error: index out of range';
this.index = index;
this.value = this.values[index];
};
/**
* Load all filtered rows in the background one by one
* Start this method without providing an index!
*/
Filter.prototype.loadInBackground = function(index) {
if (index === undefined)
index = 0;
var frame = this.graph.frame;
if (index < this.values.length) {
var dataPointsTemp = this._getDataPoints(index);
//this.graph.redrawInfo(); // TODO: not neat
// create a progress box
if (frame.progress === undefined) {
frame.progress = document.createElement('DIV');
frame.progress.style.position = 'absolute';
frame.progress.style.color = 'gray';
frame.appendChild(frame.progress);
}
var progress = this.getLoadedProgress();
frame.progress.innerHTML = 'Loading animation... ' + progress + '%';
// TODO: this is no nice solution...
frame.progress.style.bottom = 60 + 'px'; // TODO: use height of slider
frame.progress.style.left = 10 + 'px';
var me = this;
setTimeout(function() {me.loadInBackground(index+1);}, 10);
this.loaded = false;
}
else {
this.loaded = true;
// remove the progress box
if (frame.progress !== undefined) {
frame.removeChild(frame.progress);
frame.progress = undefined;
}
if (this.onLoadCallback)
this.onLoadCallback();
}
};
module.exports = Filter;

lib/graph3d/Graph3d.js
File diff suppressed because it is too large
View File


+ 11
- 0
lib/graph3d/Point2d.js View File

@ -0,0 +1,11 @@
/**
* @prototype Point2d
* @param {Number} [x]
* @param {Number} [y]
*/
Point2d = function (x, y) {
this.x = x !== undefined ? x : 0;
this.y = y !== undefined ? y : 0;
};
module.exports = Point2d;

+ 85
- 0
lib/graph3d/Point3d.js View File

@ -0,0 +1,85 @@
/**
* @prototype Point3d
* @param {Number} [x]
* @param {Number} [y]
* @param {Number} [z]
*/
function Point3d(x, y, z) {
this.x = x !== undefined ? x : 0;
this.y = y !== undefined ? y : 0;
this.z = z !== undefined ? z : 0;
};
/**
* Subtract the two provided points, returns a-b
* @param {Point3d} a
* @param {Point3d} b
* @return {Point3d} a-b
*/
Point3d.subtract = function(a, b) {
var sub = new Point3d();
sub.x = a.x - b.x;
sub.y = a.y - b.y;
sub.z = a.z - b.z;
return sub;
};
/**
* Add the two provided points, returns a+b
* @param {Point3d} a
* @param {Point3d} b
* @return {Point3d} a+b
*/
Point3d.add = function(a, b) {
var sum = new Point3d();
sum.x = a.x + b.x;
sum.y = a.y + b.y;
sum.z = a.z + b.z;
return sum;
};
/**
* Calculate the average of two 3d points
* @param {Point3d} a
* @param {Point3d} b
* @return {Point3d} The average, (a+b)/2
*/
Point3d.avg = function(a, b) {
return new Point3d(
(a.x + b.x) / 2,
(a.y + b.y) / 2,
(a.z + b.z) / 2
);
};
/**
* Calculate the cross product of the two provided points, returns axb
* Documentation: http://en.wikipedia.org/wiki/Cross_product
* @param {Point3d} a
* @param {Point3d} b
* @return {Point3d} cross product axb
*/
Point3d.crossProduct = function(a, b) {
var crossproduct = new Point3d();
crossproduct.x = a.y * b.z - a.z * b.y;
crossproduct.y = a.z * b.x - a.x * b.z;
crossproduct.z = a.x * b.y - a.y * b.x;
return crossproduct;
};
/**
* Rtrieve the length of the vector (or the distance from this point to the origin
* @return {Number} length
*/
Point3d.prototype.length = function() {
return Math.sqrt(
this.x * this.x +
this.y * this.y +
this.z * this.z
);
};
module.exports = Point3d;

+ 346
- 0
lib/graph3d/Slider.js View File

@ -0,0 +1,346 @@
var util = require('../util');
/**
* @constructor Slider
*
* An html slider control with start/stop/prev/next buttons
* @param {Element} container The element where the slider will be created
* @param {Object} options Available options:
* {boolean} visible If true (default) the
* slider is visible.
*/
function Slider(container, options) {
if (container === undefined) {
throw 'Error: No container element defined';
}
this.container = container;
this.visible = (options && options.visible != undefined) ? options.visible : true;
if (this.visible) {
this.frame = document.createElement('DIV');
//this.frame.style.backgroundColor = '#E5E5E5';
this.frame.style.width = '100%';
this.frame.style.position = 'relative';
this.container.appendChild(this.frame);
this.frame.prev = document.createElement('INPUT');
this.frame.prev.type = 'BUTTON';
this.frame.prev.value = 'Prev';
this.frame.appendChild(this.frame.prev);
this.frame.play = document.createElement('INPUT');
this.frame.play.type = 'BUTTON';
this.frame.play.value = 'Play';
this.frame.appendChild(this.frame.play);
this.frame.next = document.createElement('INPUT');
this.frame.next.type = 'BUTTON';
this.frame.next.value = 'Next';
this.frame.appendChild(this.frame.next);
this.frame.bar = document.createElement('INPUT');
this.frame.bar.type = 'BUTTON';
this.frame.bar.style.position = 'absolute';
this.frame.bar.style.border = '1px solid red';
this.frame.bar.style.width = '100px';
this.frame.bar.style.height = '6px';
this.frame.bar.style.borderRadius = '2px';
this.frame.bar.style.MozBorderRadius = '2px';
this.frame.bar.style.border = '1px solid #7F7F7F';
this.frame.bar.style.backgroundColor = '#E5E5E5';
this.frame.appendChild(this.frame.bar);
this.frame.slide = document.createElement('INPUT');
this.frame.slide.type = 'BUTTON';
this.frame.slide.style.margin = '0px';
this.frame.slide.value = ' ';
this.frame.slide.style.position = 'relative';
this.frame.slide.style.left = '-100px';
this.frame.appendChild(this.frame.slide);
// create events
var me = this;
this.frame.slide.onmousedown = function (event) {me._onMouseDown(event);};
this.frame.prev.onclick = function (event) {me.prev(event);};
this.frame.play.onclick = function (event) {me.togglePlay(event);};
this.frame.next.onclick = function (event) {me.next(event);};
}
this.onChangeCallback = undefined;
this.values = [];
this.index = undefined;
this.playTimeout = undefined;
this.playInterval = 1000; // milliseconds
this.playLoop = true;
}
/**
* Select the previous index
*/
Slider.prototype.prev = function() {
var index = this.getIndex();
if (index > 0) {
index--;
this.setIndex(index);
}
};
/**
* Select the next index
*/
Slider.prototype.next = function() {
var index = this.getIndex();
if (index < this.values.length - 1) {
index++;
this.setIndex(index);
}
};
/**
* Select the next index
*/
Slider.prototype.playNext = function() {
var start = new Date();
var index = this.getIndex();
if (index < this.values.length - 1) {
index++;
this.setIndex(index);
}
else if (this.playLoop) {
// jump to the start
index = 0;
this.setIndex(index);
}
var end = new Date();
var diff = (end - start);
// calculate how much time it to to set the index and to execute the callback
// function.
var interval = Math.max(this.playInterval - diff, 0);
// document.title = diff // TODO: cleanup
var me = this;
this.playTimeout = setTimeout(function() {me.playNext();}, interval);
};
/**
* Toggle start or stop playing
*/
Slider.prototype.togglePlay = function() {
if (this.playTimeout === undefined) {
this.play();
} else {
this.stop();
}
};
/**
* Start playing
*/
Slider.prototype.play = function() {
// Test whether already playing
if (this.playTimeout) return;
this.playNext();
if (this.frame) {
this.frame.play.value = 'Stop';
}
};
/**
* Stop playing
*/
Slider.prototype.stop = function() {
clearInterval(this.playTimeout);
this.playTimeout = undefined;
if (this.frame) {
this.frame.play.value = 'Play';
}
};
/**
* Set a callback function which will be triggered when the value of the
* slider bar has changed.
*/
Slider.prototype.setOnChangeCallback = function(callback) {
this.onChangeCallback = callback;
};
/**
* Set the interval for playing the list
* @param {Number} interval The interval in milliseconds
*/
Slider.prototype.setPlayInterval = function(interval) {
this.playInterval = interval;
};
/**
* Retrieve the current play interval
* @return {Number} interval The interval in milliseconds
*/
Slider.prototype.getPlayInterval = function(interval) {
return this.playInterval;
};
/**
* Set looping on or off
* @pararm {boolean} doLoop If true, the slider will jump to the start when
* the end is passed, and will jump to the end
* when the start is passed.
*/
Slider.prototype.setPlayLoop = function(doLoop) {
this.playLoop = doLoop;
};
/**
* Execute the onchange callback function
*/
Slider.prototype.onChange = function() {
if (this.onChangeCallback !== undefined) {
this.onChangeCallback();
}
};
/**
* redraw the slider on the correct place
*/
Slider.prototype.redraw = function() {
if (this.frame) {
// resize the bar
this.frame.bar.style.top = (this.frame.clientHeight/2 -
this.frame.bar.offsetHeight/2) + 'px';
this.frame.bar.style.width = (this.frame.clientWidth -
this.frame.prev.clientWidth -
this.frame.play.clientWidth -
this.frame.next.clientWidth - 30) + 'px';
// position the slider button
var left = this.indexToLeft(this.index);
this.frame.slide.style.left = (left) + 'px';
}
};
/**
* Set the list with values for the slider
* @param {Array} values A javascript array with values (any type)
*/
Slider.prototype.setValues = function(values) {
this.values = values;
if (this.values.length > 0)
this.setIndex(0);
else
this.index = undefined;
};
/**
* Select a value by its index
* @param {Number} index
*/
Slider.prototype.setIndex = function(index) {
if (index < this.values.length) {
this.index = index;
this.redraw();
this.onChange();
}
else {
throw 'Error: index out of range';
}
};
/**
* retrieve the index of the currently selected vaue
* @return {Number} index
*/
Slider.prototype.getIndex = function() {
return this.index;
};
/**
* retrieve the currently selected value
* @return {*} value
*/
Slider.prototype.get = function() {
return this.values[this.index];
};
Slider.prototype._onMouseDown = function(event) {
// only react on left mouse button down
var leftButtonDown = event.which ? (event.which === 1) : (event.button === 1);
if (!leftButtonDown) return;
this.startClientX = event.clientX;
this.startSlideX = parseFloat(this.frame.slide.style.left);
this.frame.style.cursor = 'move';
// add event listeners to handle moving the contents
// we store the function onmousemove and onmouseup in the graph, so we can
// remove the eventlisteners lateron in the function mouseUp()
var me = this;
this.onmousemove = function (event) {me._onMouseMove(event);};
this.onmouseup = function (event) {me._onMouseUp(event);};
util.addEventListener(document, 'mousemove', this.onmousemove);
util.addEventListener(document, 'mouseup', this.onmouseup);
util.preventDefault(event);
};
Slider.prototype.leftToIndex = function (left) {
var width = parseFloat(this.frame.bar.style.width) -
this.frame.slide.clientWidth - 10;
var x = left - 3;
var index = Math.round(x / width * (this.values.length-1));
if (index < 0) index = 0;
if (index > this.values.length-1) index = this.values.length-1;
return index;
};
Slider.prototype.indexToLeft = function (index) {
var width = parseFloat(this.frame.bar.style.width) -
this.frame.slide.clientWidth - 10;
var x = index / (this.values.length-1) * width;
var left = x + 3;
return left;
};
Slider.prototype._onMouseMove = function (event) {
var diff = event.clientX - this.startClientX;
var x = this.startSlideX + diff;
var index = this.leftToIndex(x);
this.setIndex(index);
util.preventDefault();
};
Slider.prototype._onMouseUp = function (event) {
this.frame.style.cursor = 'auto';
// remove event listeners
util.removeEventListener(document, 'mousemove', this.onmousemove);
util.removeEventListener(document, 'mouseup', this.onmouseup);
util.preventDefault();
};
module.exports = Slider;

+ 140
- 0
lib/graph3d/StepNumber.js View File

@ -0,0 +1,140 @@
/**
* @prototype StepNumber
* The class StepNumber is an iterator for Numbers. You provide a start and end
* value, and a best step size. StepNumber itself rounds to fixed values and
* a finds the step that best fits the provided step.
*
* If prettyStep is true, the step size is chosen as close as possible to the
* provided step, but being a round value like 1, 2, 5, 10, 20, 50, ....
*
* Example usage:
* var step = new StepNumber(0, 10, 2.5, true);
* step.start();
* while (!step.end()) {
* alert(step.getCurrent());
* step.next();
* }
*
* Version: 1.0
*
* @param {Number} start The start value
* @param {Number} end The end value
* @param {Number} step Optional. Step size. Must be a positive value.
* @param {boolean} prettyStep Optional. If true, the step size is rounded
* To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
*/
function StepNumber(start, end, step, prettyStep) {
// set default values
this._start = 0;
this._end = 0;
this._step = 1;
this.prettyStep = true;
this.precision = 5;
this._current = 0;
this.setRange(start, end, step, prettyStep);
};
/**
* Set a new range: start, end and step.
*
* @param {Number} start The start value
* @param {Number} end The end value
* @param {Number} step Optional. Step size. Must be a positive value.
* @param {boolean} prettyStep Optional. If true, the step size is rounded
* To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
*/
StepNumber.prototype.setRange = function(start, end, step, prettyStep) {
this._start = start ? start : 0;
this._end = end ? end : 0;
this.setStep(step, prettyStep);
};
/**
* Set a new step size
* @param {Number} step New step size. Must be a positive value
* @param {boolean} prettyStep Optional. If true, the provided step is rounded
* to a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
*/
StepNumber.prototype.setStep = function(step, prettyStep) {
if (step === undefined || step <= 0)
return;
if (prettyStep !== undefined)
this.prettyStep = prettyStep;
if (this.prettyStep === true)
this._step = StepNumber.calculatePrettyStep(step);
else
this._step = step;
};
/**
* Calculate a nice step size, closest to the desired step size.
* Returns a value in one of the ranges 1*10^n, 2*10^n, or 5*10^n, where n is an
* integer Number. For example 1, 2, 5, 10, 20, 50, etc...
* @param {Number} step Desired step size
* @return {Number} Nice step size
*/
StepNumber.calculatePrettyStep = function (step) {
var log10 = function (x) {return Math.log(x) / Math.LN10;};
// try three steps (multiple of 1, 2, or 5
var step1 = Math.pow(10, Math.round(log10(step))),
step2 = 2 * Math.pow(10, Math.round(log10(step / 2))),
step5 = 5 * Math.pow(10, Math.round(log10(step / 5)));
// choose the best step (closest to minimum step)
var prettyStep = step1;
if (Math.abs(step2 - step) <= Math.abs(prettyStep - step)) prettyStep = step2;
if (Math.abs(step5 - step) <= Math.abs(prettyStep - step)) prettyStep = step5;
// for safety
if (prettyStep <= 0) {
prettyStep = 1;
}
return prettyStep;
};
/**
* returns the current value of the step
* @return {Number} current value
*/
StepNumber.prototype.getCurrent = function () {
return parseFloat(this._current.toPrecision(this.precision));
};
/**
* returns the current step size
* @return {Number} current step size
*/
StepNumber.prototype.getStep = function () {
return this._step;
};
/**
* Set the current value to the largest value smaller than start, which
* is a multiple of the step size
*/
StepNumber.prototype.start = function() {
this._current = this._start - this._start % this._step;
};
/**
* Do a step, add the step size to the current value
*/
StepNumber.prototype.next = function () {
this._current += this._step;
};
/**
* Returns true whether the end is reached
* @return {boolean} True if the current value has passed the end value.
*/
StepNumber.prototype.end = function () {
return (this._current > this._end);
};
module.exports = StepNumber;

+ 28
- 0
lib/hammerUtil.js View File

@ -0,0 +1,28 @@
var Hammer = require('./module/hammer');
/**
* Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent
* @param {Element} element
* @param {Event} event
*/
exports.fakeGesture = function(element, event) {
var eventType = null;
// for hammer.js 1.0.5
// var gesture = Hammer.event.collectEventData(this, eventType, event);
// for hammer.js 1.0.6+
var touches = Hammer.event.getTouchList(event, eventType);
var gesture = Hammer.event.collectEventData(this, eventType, touches, event);
// on IE in standards mode, no touches are recognized by hammer.js,
// resulting in NaN values for center.pageX and center.pageY
if (isNaN(gesture.center.pageX)) {
gesture.center.pageX = event.pageX;
}
if (isNaN(gesture.center.pageY)) {
gesture.center.pageY = event.pageY;
}
return gesture;
};

src/module/header.js → lib/header.js View File


+ 10
- 0
lib/module/hammer.js View File

@ -0,0 +1,10 @@
// Only load hammer.js when in a browser environment
// (loading hammer.js in a node.js environment gives errors)
if (typeof window !== 'undefined') {
module.exports = window['Hammer'] || require('hammerjs');
}
else {
module.exports = function () {
throw Error('hammer.js is only available in a browser, not in node.js.');
}
}

+ 3
- 0
lib/module/moment.js View File

@ -0,0 +1,3 @@
// first check if moment.js is already loaded in the browser window, if so,
// use this instance. Else, load via commonjs.
module.exports = (typeof window !== 'undefined') && window['moment'] || require('moment');

src/network/Edge.js → lib/network/Edge.js View File

@ -1,3 +1,6 @@
var util = require('../util');
var Node = require('./Node');
/**
* @class Edge
*
@ -38,8 +41,10 @@ function Edge (properties, network, constants) {
this.customLength = false;
this.selected = false;
this.hover = false;
this.smooth = constants.smoothCurves;
this.smoothCurves = constants.smoothCurves;
this.dynamicSmoothCurves = constants.dynamicSmoothCurves;
this.arrowScaleFactor = constants.edges.arrowScaleFactor;
this.inheritColor = constants.edges.inheritColor;
this.from = null; // a node
this.to = null; // a node
@ -111,6 +116,8 @@ Edge.prototype.setProperties = function(properties, constants) {
// scale the arrow
if (properties.arrowScaleFactor !== undefined) {this.arrowScaleFactor = properties.arrowScaleFactor;}
if (properties.inheritColor !== undefined) {this.inheritColor = properties.inheritColor;}
// Added to support dashed lines
// David Jordan
// 2012-08-08
@ -218,6 +225,7 @@ Edge.prototype.setValueRange = function(min, max) {
if (!this.widthFixed && this.value !== undefined) {
var scale = (this.widthMax - this.widthMin) / (max - min);
this.width = (this.value - min) * scale + this.widthMin;
this.widthSelected = this.width * this.widthSelectionMultiplier;
}
};
@ -255,6 +263,28 @@ Edge.prototype.isOverlappingWith = function(obj) {
}
};
Edge.prototype._getColor = function() {
var colorObj = this.color;
if (this.inheritColor == "to") {
colorObj = {
highlight: this.to.color.highlight.border,
hover: this.to.color.hover.border,
color: this.to.color.border
};
}
else if (this.inheritColor == "from" || this.inheritColor == true) {
colorObj = {
highlight: this.from.color.highlight.border,
hover: this.from.color.hover.border,
color: this.from.color.border
};
}
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
@ -265,21 +295,19 @@ Edge.prototype.isOverlappingWith = function(obj) {
*/
Edge.prototype._drawLine = function(ctx) {
// set style
if (this.selected == true) {ctx.strokeStyle = this.color.highlight;}
else if (this.hover == true) {ctx.strokeStyle = this.color.hover;}
else {ctx.strokeStyle = this.color.color;}
ctx.lineWidth = this._getLineWidth();
ctx.strokeStyle = this._getColor();
ctx.lineWidth = this._getLineWidth();
if (this.from != this.to) {
// draw line
this._line(ctx);
var via = this._line(ctx);
// draw label
var point;
if (this.label) {
if (this.smooth == true) {
var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
if (this.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 {
@ -329,6 +357,171 @@ Edge.prototype._getLineWidth = function() {
}
};
Edge.prototype._getViaCoordinates = function () {
var xVia = null;
var yVia = null;
var factor = this.smoothCurves.roundness;
var type = this.smoothCurves.type;
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;
}
}
}
}
return {x:xVia, y:yVia};
}
/**
* Draw a line between two nodes
* @param {CanvasRenderingContext2D} ctx
@ -338,13 +531,33 @@ Edge.prototype._line = function (ctx) {
// draw a straight line
ctx.beginPath();
ctx.moveTo(this.from.x, this.from.y);
if (this.smooth == true) {
if (this.smoothCurves.enabled == true) {
if (this.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;
}
ctx.stroke();
};
/**
@ -408,11 +621,9 @@ Edge.prototype._drawDashLine = function(ctx) {
ctx.lineWidth = this._getLineWidth();
var via = null;
// only firefox and chrome support this method, else we use the legacy one.
if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
ctx.beginPath();
ctx.moveTo(this.from.x, this.from.y);
// configure the dash pattern
var pattern = [0];
if (this.dash.length !== undefined && this.dash.gap !== undefined) {
@ -433,13 +644,7 @@ Edge.prototype._drawDashLine = function(ctx) {
}
// draw the line
if (this.smooth == true) {
ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
}
else {
ctx.lineTo(this.to.x, this.to.y);
}
ctx.stroke();
via = this._line(ctx);
// restore the dash settings.
if (typeof ctx.setLineDash !== 'undefined') { //Chrome
@ -476,9 +681,9 @@ Edge.prototype._drawDashLine = function(ctx) {
// draw label
if (this.label) {
var point;
if (this.smooth == true) {
var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
if (this.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 {
@ -535,14 +740,14 @@ Edge.prototype._drawArrowCenter = function(ctx) {
if (this.from != this.to) {
// draw line
this._line(ctx);
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.width) * this.arrowScaleFactor;
// draw an arrow halfway the line
if (this.smooth == true) {
var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
if (this.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 {
@ -622,20 +827,27 @@ Edge.prototype._drawArrow = function(ctx) {
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.smoothCurves.dynamic == true && this.smoothCurves.enabled == true ) {
via = this.via;
}
else if (this.smoothCurves.enabled == true) {
via = this._getViaCoordinates();
}
if (this.smooth == true) {
angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
dx = (this.to.x - this.via.x);
dy = (this.to.y - this.via.y);
if (this.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;
var xTo,yTo;
if (this.smooth == true) {
xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
if (this.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;
@ -644,8 +856,8 @@ Edge.prototype._drawArrow = function(ctx) {
ctx.beginPath();
ctx.moveTo(xFrom,yFrom);
if (this.smooth == true) {
ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo);
if (this.smoothCurves.enabled == true && via.x != null) {
ctx.quadraticCurveTo(via.x,via.y,xTo, yTo);
}
else {
ctx.lineTo(xTo, yTo);
@ -661,9 +873,9 @@ Edge.prototype._drawArrow = function(ctx) {
// draw label
if (this.label) {
var point;
if (this.smooth == true) {
var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x));
var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y));
if (this.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 {
@ -733,44 +945,34 @@ Edge.prototype._drawArrow = function(ctx) {
*/
Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
if (this.from != this.to) {
if (this.smooth == true) {
if (this.smoothCurves.enabled == true) {
var xVia, yVia;
if (this.smoothCurves.enabled == true && this.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 i,t,x,y,dx,dy;
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))*this.via.x + Math.pow(t,2)*x2;
y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2;
dx = Math.abs(x3-x);
dy = Math.abs(y3-y);
minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy));
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;
}
return minDistance
}
else {
var px = x2-x1,
py = y2-y1,
something = px*px + py*py,
u = ((x3 - x1) * px + (y3 - y1) * py) / something;
if (u > 1) {
u = 1;
}
else if (u < 0) {
u = 0;
}
var x = x1 + u * px,
y = y1 + u * py,
dx = x - x3,
dy = y - y3;
//# 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
return Math.sqrt(dx*dx + dy*dy);
return this._getDistanceToLine(x1,y1,x2,y2,x3,y3);
}
}
else {
@ -794,7 +996,32 @@ Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is
}
};
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 (u > 1) {
u = 1;
}
else if (u < 0) {
u = 0;
}
var x = x1 + u * px,
y = y1 + u * py,
dx = x - x3,
dy = y - y3;
//# 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
return Math.sqrt(dx*dx + dy*dy);
}
/**
* This allows the zoom level of the network to influence the rendering
@ -861,7 +1088,7 @@ Edge.prototype._drawControlNodes = function(ctx) {
else {
this.controlNodes = {from:null, to:null, positions:{}};
}
}
};
/**
* Enable control nodes.
@ -869,7 +1096,7 @@ Edge.prototype._drawControlNodes = function(ctx) {
*/
Edge.prototype._enableControlNodes = function() {
this.controlNodesEnabled = true;
}
};
/**
* disable control nodes
@ -877,7 +1104,7 @@ Edge.prototype._enableControlNodes = function() {
*/
Edge.prototype._disableControlNodes = function() {
this.controlNodesEnabled = false;
}
};
/**
* This checks if one of the control nodes is selected and if so, returns the control node object. Else it returns null.
@ -904,7 +1131,7 @@ Edge.prototype._getSelectedControlNode = function(x,y) {
else {
return null;
}
}
};
/**
@ -922,7 +1149,7 @@ Edge.prototype._restoreControlNodes = function() {
this.connectedNode = null;
this.controlNodes.to.unselect();
}
}
};
/**
* this calculates the position of the control nodes on the edges of the parent nodes.
@ -940,20 +1167,27 @@ Edge.prototype.getControlNodePositions = function(ctx) {
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.smoothCurves.dynamic == true && this.smoothCurves.enabled == true) {
via = this.via;
}
else if (this.smoothCurves.enabled == true) {
via = this._getViaCoordinates();
}
if (this.smooth == true) {
angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x));
dx = (this.to.x - this.via.x);
dy = (this.to.y - this.via.y);
if (this.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;
var xTo,yTo;
if (this.smooth == true) {
xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x;
yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y;
if (this.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;
@ -961,4 +1195,6 @@ Edge.prototype.getControlNodePositions = function(ctx) {
}
return {from:{x:xFrom,y:yFrom},to:{x:xTo,y:yTo}};
}
};
module.exports = Edge;

src/network/Groups.js → lib/network/Groups.js View File

@ -1,3 +1,5 @@
var util = require('../util');
/**
* @class Groups
* This class can store groups and properties specific for groups.
@ -12,16 +14,16 @@ function Groups() {
* default constants for group colors
*/
Groups.DEFAULT = [
{border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
{border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
{border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
{border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
{border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
{border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
{border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
{border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
{border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
{border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
{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
];
@ -51,7 +53,6 @@ Groups.prototype.clear = function () {
*/
Groups.prototype.get = function (groupname) {
var group = this.groups[groupname];
if (group == undefined) {
// create new group
var index = this.defaultIndex % Groups.DEFAULT.length;
@ -78,3 +79,5 @@ Groups.prototype.add = function (groupname, style) {
}
return style;
};
module.exports = Groups;

src/network/Images.js → lib/network/Images.js View File

@ -39,3 +39,5 @@ Images.prototype.load = function(url) {
return img;
};
module.exports = Images;

src/network/Network.js → lib/network/Network.js View File

@ -1,3 +1,22 @@
var Emitter = require('emitter-component');
var Hammer = require('../module/hammer');
var mousetrap = require('mousetrap');
var util = require('../util');
var hammerUtil = require('../hammerUtil');
var DataSet = require('../DataSet');
var DataView = require('../DataView');
var dotparser = require('./dotparser');
var gephiParser = require('./gephiParser');
var Groups = require('./Groups');
var Images = require('./Images');
var Node = require('./Node');
var Edge = require('./Edge');
var Popup = require('./Popup');
var MixinLoader = require('./mixins/MixinLoader');
// Load custom shapes into CanvasRenderingContext2D
require('./shapes');
/**
* @constructor Network
* Create a network visualization, displaying nodes and edges.
@ -39,9 +58,9 @@ function Network (container, data, options) {
// set constant values
this.constants = {
nodes: {
radiusMin: 5,
radiusMax: 20,
radius: 5,
radiusMin: 10,
radiusMax: 30,
radius: 10,
shape: 'ellipse',
image: undefined,
widthMin: 16, // px
@ -66,7 +85,8 @@ function Network (container, data, options) {
borderColor: '#2B7CE9',
backgroundColor: '#97C2FC',
highlightColor: '#D2E5FF',
group: undefined
group: undefined,
borderWidth: 1
},
edges: {
widthMin: 1,
@ -89,7 +109,8 @@ function Network (container, data, options) {
length: 10,
gap: 5,
altLength: undefined
}
},
inheritColor: "from" // to, from, false, true (== from)
},
configurePhysics:false,
physics: {
@ -103,7 +124,7 @@ function Network (container, data, options) {
damping: 0.09
},
repulsion: {
centralGravity: 0.1,
centralGravity: 0.0,
springLength: 200,
springConstant: 0.05,
nodeDistance: 100,
@ -111,10 +132,10 @@ function Network (container, data, options) {
},
hierarchicalRepulsion: {
enabled: false,
centralGravity: 0.5,
springLength: 150,
centralGravity: 0.0,
springLength: 100,
springConstant: 0.01,
nodeDistance: 60,
nodeDistance: 150,
damping: 0.09
},
damping: null,
@ -161,8 +182,14 @@ function Network (container, data, options) {
direction: "UD" // UD, DU, LR, RL
},
freezeForStabilization: false,
smoothCurves: true,
maxVelocity: 10,
smoothCurves: {
enabled: true,
dynamic: true,
type: "continuous",
roundness: 0.5
},
dynamicSmoothCurves: true,
maxVelocity: 30,
minVelocity: 0.1, // px/s
stabilizationIterations: 1000, // maximum number of iteration to stabilize
labels:{
@ -196,10 +223,12 @@ function Network (container, data, options) {
dragNetwork: true,
dragNodes: true,
zoomable: true,
hover: false
hover: false,
hideEdgesOnDrag: false,
hideNodesOnDrag: false
};
this.hoverObj = {nodes:{},edges:{}};
this.controlNodesActive = false;
// Node variables
var network = this;
@ -475,6 +504,7 @@ Network.prototype._updateNodeIndexList = function() {
* {Array | DataSet | DataView} [nodes] Array with nodes
* {Array | DataSet | DataView} [edges] Array with edges
* {String} [dot] String containing data in DOT format
* {String} [gephi] String containing data in gephi JSON format
* {Options} [options] Object with options
* @param {Boolean} [disableStart] | optional: disable the calling of the start function.
*/
@ -495,18 +525,25 @@ Network.prototype.setData = function(data, disableStart) {
if (data && data.dot) {
// parse DOT file
if(data && data.dot) {
var dotData = vis.util.DOTToGraph(data.dot);
var dotData = dotparser.DOTToGraph(data.dot);
this.setData(dotData);
return;
}
}
else if (data && data.gephi) {
// parse DOT file
if(data && data.gephi) {
var gephiData = gephiParser.parseGephi(data.gephi);
this.setData(gephiData);
return;
}
}
else {
this._setNodes(data && data.nodes);
this._setEdges(data && data.edges);
}
this._putDataInSector();
if (!disableStart) {
// find a stable position or start animating to a stable position
if (this.stabilize) {
@ -532,7 +569,6 @@ Network.prototype.setOptions = function (options) {
if (options.height !== undefined) {this.height = options.height;}
if (options.stabilize !== undefined) {this.stabilize = options.stabilize;}
if (options.selectable !== undefined) {this.selectable = options.selectable;}
if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;}
if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;}
if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;}
if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;}
@ -540,6 +576,8 @@ Network.prototype.setOptions = function (options) {
if (options.dragNodes !== undefined) {this.constants.dragNodes = options.dragNodes;}
if (options.zoomable !== undefined) {this.constants.zoomable = options.zoomable;}
if (options.hover !== undefined) {this.constants.hover = options.hover;}
if (options.hideEdgesOnDrag !== undefined) {this.constants.hideEdgesOnDrag = options.hideEdgesOnDrag;}
if (options.hideNodesOnDrag !== undefined) {this.constants.hideNodesOnDrag = options.hideNodesOnDrag;}
// TODO: deprecated since version 3.0.0. Cleanup some day
if (options.dragGraph !== undefined) {
@ -605,6 +643,20 @@ Network.prototype.setOptions = function (options) {
}
}
if (options.smoothCurves !== undefined) {
if (typeof options.smoothCurves == 'boolean') {
this.constants.smoothCurves.enabled = options.smoothCurves;
}
else {
this.constants.smoothCurves.enabled = true;
for (prop in options.smoothCurves) {
if (options.smoothCurves.hasOwnProperty(prop)) {
this.constants.smoothCurves[prop] = options.smoothCurves[prop];
}
}
}
}
if (options.hierarchicalLayout) {
this.constants.hierarchicalLayout.enabled = true;
for (prop in options.hierarchicalLayout) {
@ -676,7 +728,6 @@ Network.prototype.setOptions = function (options) {
}
}
if (options.edges.color !== undefined) {
if (util.isString(options.edges.color)) {
this.constants.edges.color = {};
@ -874,8 +925,8 @@ Network.prototype._createKeyBinds = function() {
*/
Network.prototype._getPointer = function (touch) {
return {
x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas),
y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas)
x: touch.pageX - util.getAbsoluteLeft(this.frame.canvas),
y: touch.pageY - util.getAbsoluteTop(this.frame.canvas)
};
};
@ -971,13 +1022,13 @@ Network.prototype._handleOnDrag = function(event) {
var pointer = this._getPointer(event.gesture.center);
var me = this,
drag = this.drag,
selection = drag.selection;
var me = this;
var drag = this.drag;
var selection = drag.selection;
if (selection && selection.length && this.constants.dragNodes == true) {
// calculate delta's and new location
var deltaX = pointer.x - drag.pointer.x,
deltaY = pointer.y - drag.pointer.y;
var deltaX = pointer.x - drag.pointer.x;
var deltaY = pointer.y - drag.pointer.y;
// update position of all selected nodes
selection.forEach(function (s) {
@ -992,6 +1043,7 @@ Network.prototype._handleOnDrag = function(event) {
}
});
// start _animationStep if not yet running
if (!this.moving) {
this.moving = true;
@ -1006,10 +1058,11 @@ Network.prototype._handleOnDrag = function(event) {
this._setTranslation(
this.drag.translation.x + diffX,
this.drag.translation.y + diffY);
this.drag.translation.y + diffY
);
this._redraw();
this.moving = true;
this.start();
// this.moving = true;
// this.start();
}
}
};
@ -1021,13 +1074,19 @@ Network.prototype._handleOnDrag = function(event) {
Network.prototype._onDragEnd = function () {
this.drag.dragging = false;
var selection = this.drag.selection;
if (selection) {
if (selection && selection.length) {
selection.forEach(function (s) {
// restore original xFixed and yFixed
s.node.xFixed = s.xFixed;
s.node.yFixed = s.yFixed;
});
this.moving = true;
this.start();
}
else {
this._redraw();
}
};
/**
@ -1106,6 +1165,13 @@ Network.prototype._zoom = function(scale, pointer) {
if (scale > 10) {
scale = 10;
}
var preScaleDragPointer = null;
if (this.drag !== undefined) {
if (this.drag.dragging == true) {
preScaleDragPointer = this.DOMtoCanvas(this.drag.pointer);
}
}
// + this.frame.canvas.clientHeight / 2
var translation = this._getTranslation();
@ -1119,6 +1185,13 @@ Network.prototype._zoom = function(scale, pointer) {
this._setScale(scale);
this._setTranslation(tx, ty);
this.updateClustersDefault();
if (preScaleDragPointer != null) {
var postScaleDragPointer = this.canvasToDOM(preScaleDragPointer);
this.drag.pointer.x = postScaleDragPointer.x;
this.drag.pointer.y = postScaleDragPointer.y;
}
this._redraw();
if (scaleOld < scale) {
@ -1165,7 +1238,7 @@ Network.prototype._onMouseWheel = function(event) {
scale *= (1 + zoom);
// calculate the pointer location
var gesture = util.fakeGesture(this, event);
var gesture = hammerUtil.fakeGesture(this, event);
var pointer = this._getPointer(gesture.center);
// apply the new scale
@ -1183,7 +1256,7 @@ Network.prototype._onMouseWheel = function(event) {
* @private
*/
Network.prototype._onMouseMoveTitle = function (event) {
var gesture = util.fakeGesture(this, event);
var gesture = hammerUtil.fakeGesture(this, event);
var pointer = this._getPointer(gesture.center);
// check if the previously selected node is still selected
@ -1723,10 +1796,19 @@ Network.prototype._redraw = function() {
"y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight)
};
this._doInAllSectors("_drawAllSectorNodes",ctx);
this._doInAllSectors("_drawEdges",ctx);
this._doInAllSectors("_drawNodes",ctx,false);
this._doInAllSectors("_drawControlNodes",ctx);
if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideEdgesOnDrag == false) {
this._doInAllSectors("_drawEdges",ctx);
}
if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideNodesOnDrag == false) {
this._doInAllSectors("_drawNodes",ctx,false);
}
if (this.controlNodesActive == true) {
this._doInAllSectors("_drawControlNodes",ctx);
}
// this._doInSupportSector("_drawNodes",ctx,true);
// this._drawTree(ctx,"#F00F0F");
@ -2039,6 +2121,11 @@ Network.prototype._discreteStepNodes = function() {
}
else {
this.moving = this._isMoving(vminCorrected);
if (this.moving == false) {
this.emit("stabilized",{iterations:null});
}
this.moving = this.moving || this.configurePhysics;
}
}
};
@ -2050,10 +2137,10 @@ Network.prototype._discreteStepNodes = function() {
*/
Network.prototype._physicsTick = function() {
if (!this.freezeSimulation) {
if (this.moving) {
if (this.moving == true) {
this._doInAllActiveSectors("_initializeForceCalculation");
this._doInAllActiveSectors("_discreteStepNodes");
if (this.constants.smoothCurves) {
if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
this._doInSupportSector("_discreteStepNodes");
}
this._findCenter(this._getRange())
@ -2091,6 +2178,7 @@ Network.prototype._animationStep = function() {
var renderTime = Date.now();
this._redraw();
this.renderTime = Date.now() - renderTime;
};
if (typeof window !== 'undefined') {
@ -2102,7 +2190,7 @@ if (typeof window !== 'undefined') {
* Schedule a animation step with the refreshrate interval.
*/
Network.prototype.start = function() {
if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
if (this.moving == true || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) {
if (!this.timer) {
var ua = navigator.userAgent.toLowerCase();
@ -2174,9 +2262,16 @@ Network.prototype._configureSmoothCurves = function(disableStart) {
if (disableStart === undefined) {
disableStart = true;
}
if (this.constants.smoothCurves == true) {
if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
this._createBezierNodes();
// cleanup unused support nodes
for (var nodeId in this.sectors['support']['nodes']) {
if (this.sectors['support']['nodes'].hasOwnProperty(nodeId)) {
if (this.edges[this.sectors['support']['nodes'][nodeId]] === undefined) {
delete this.sectors['support']['nodes'][nodeId];
}
}
}
}
else {
// delete the support nodes
@ -2188,6 +2283,8 @@ Network.prototype._configureSmoothCurves = function(disableStart) {
}
}
}
this._updateCalculationNodes();
if (!disableStart) {
this.moving = true;
@ -2203,7 +2300,7 @@ Network.prototype._configureSmoothCurves = function(disableStart) {
* @private
*/
Network.prototype._createBezierNodes = function() {
if (this.constants.smoothCurves == true) {
if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
for (var edgeId in this.edges) {
if (this.edges.hasOwnProperty(edgeId)) {
var edge = this.edges[edgeId];
@ -2232,9 +2329,9 @@ Network.prototype._createBezierNodes = function() {
* @private
*/
Network.prototype._initializeMixinLoaders = function () {
for (var mixinFunction in networkMixinLoaders) {
if (networkMixinLoaders.hasOwnProperty(mixinFunction)) {
Network.prototype[mixinFunction] = networkMixinLoaders[mixinFunction];
for (var mixin in MixinLoader) {
if (MixinLoader.hasOwnProperty(mixin)) {
Network.prototype[mixin] = MixinLoader[mixin];
}
}
};
@ -2289,11 +2386,4 @@ Network.prototype.focusOnNode = function (nodeId, zoomLevel) {
}
};
module.exports = Network;

src/network/Node.js → lib/network/Node.js View File

@ -1,3 +1,5 @@
var util = require('../util');
/**
* @class Node
* A node. A node can be connected to other nodes via one or multiple edges.
@ -56,6 +58,8 @@ function Node(properties, imagelist, grouplist, constants) {
this.radiusMax = constants.nodes.radiusMax;
this.level = -1;
this.preassignedLevel = false;
this.borderWidth = constants.nodes.borderWidth;
this.borderWidthSelected = constants.nodes.borderWidthSelected;
this.imagelist = imagelist;
@ -71,6 +75,7 @@ function Node(properties, imagelist, grouplist, constants) {
this.mass = 1; // kg
this.fixedData = {x:null,y:null};
this.setProperties(properties, constants);
// creating the variables for clustering
@ -150,7 +155,8 @@ Node.prototype.setProperties = function(properties, constants) {
if (properties.y !== undefined) {this.y = properties.y;}
if (properties.value !== undefined) {this.value = properties.value;}
if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;}
if (properties.borderWidth !== undefined) {this.borderWidth = properties.borderWidth;}
if (properties.borderWidthSelected !== undefined) {this.borderWidthSelected = properties.borderWidthSelected;}
// physics
if (properties.mass !== undefined) {this.mass = properties.mass;}
@ -165,7 +171,7 @@ Node.prototype.setProperties = function(properties, constants) {
}
// copy group properties
if (this.group) {
if (this.group !== undefined && this.group != "") {
var groupObj = this.grouplist.get(this.group);
for (var prop in groupObj) {
if (groupObj.hasOwnProperty(prop)) {
@ -177,7 +183,7 @@ Node.prototype.setProperties = function(properties, constants) {
// individual shape properties
if (properties.shape !== undefined) {this.shape = properties.shape;}
if (properties.image !== undefined) {this.image = properties.image;}
if (properties.radius !== undefined) {this.radius = properties.radius;}
if (properties.radius !== undefined) {this.radius = properties.radius; this.baseRadiusValue = this.radius;}
if (properties.color !== undefined) {this.color = util.parseColor(properties.color);}
if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;}
@ -568,22 +574,23 @@ Node.prototype._drawBox = function (ctx) {
this.top = this.y - this.height / 2;
var clusterLineWidth = 2.5;
var selectionLineWidth = 2;
var borderWidth = this.borderWidth;
var selectionLineWidth = this.borderWidthSelected || 2 * this.borderWidth;
ctx.strokeStyle = this.selected ? this.color.highlight.border : this.hover ? this.color.hover.border : this.color.border;
// draw the outer border
if (this.clusterSize > 1) {
ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth *= this.networkScaleInv;
ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius);
ctx.stroke();
}
ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth *= this.networkScaleInv;
ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
@ -617,22 +624,23 @@ Node.prototype._drawDatabase = function (ctx) {
this.top = this.y - this.height / 2;
var clusterLineWidth = 2.5;
var selectionLineWidth = 2;
var borderWidth = this.borderWidth;
var selectionLineWidth = this.borderWidthSelected || 2 * this.borderWidth;
ctx.strokeStyle = this.selected ? this.color.highlight.border : this.hover ? this.color.hover.border : this.color.border;
// draw the outer border
if (this.clusterSize > 1) {
ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth *= this.networkScaleInv;
ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
ctx.database(this.x - this.width/2 - 2*ctx.lineWidth, this.y - this.height*0.5 - 2*ctx.lineWidth, this.width + 4*ctx.lineWidth, this.height + 4*ctx.lineWidth);
ctx.stroke();
}
ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth *= this.networkScaleInv;
ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
ctx.fillStyle = this.selected ? this.color.highlight.background : this.hover ? this.color.hover.background : this.color.background;
ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
@ -667,22 +675,23 @@ Node.prototype._drawCircle = function (ctx) {
this.top = this.y - this.height / 2;
var clusterLineWidth = 2.5;
var selectionLineWidth = 2;
var borderWidth = this.borderWidth;
var selectionLineWidth = this.borderWidthSelected || 2 * this.borderWidth;
ctx.strokeStyle = this.selected ? this.color.highlight.border : this.hover ? this.color.hover.border : this.color.border;
// draw the outer border
if (this.clusterSize > 1) {
ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth *= this.networkScaleInv;
ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth);
ctx.stroke();
}
ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth *= this.networkScaleInv;
ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
ctx.fillStyle = this.selected ? this.color.highlight.background : this.hover ? this.color.hover.background : this.color.background;
ctx.circle(this.x, this.y, this.radius);
@ -717,22 +726,23 @@ Node.prototype._drawEllipse = function (ctx) {
this.top = this.y - this.height / 2;
var clusterLineWidth = 2.5;
var selectionLineWidth = 2;
var borderWidth = this.borderWidth;
var selectionLineWidth = this.borderWidthSelected || 2 * this.borderWidth;
ctx.strokeStyle = this.selected ? this.color.highlight.border : this.hover ? this.color.hover.border : this.color.border;
// draw the outer border
if (this.clusterSize > 1) {
ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth *= this.networkScaleInv;
ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth);
ctx.stroke();
}
ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth *= this.networkScaleInv;
ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
ctx.fillStyle = this.selected ? this.color.highlight.background : this.hover ? this.color.hover.background : this.color.background;
@ -784,7 +794,8 @@ Node.prototype._drawShape = function (ctx, shape) {
this.top = this.y - this.height / 2;
var clusterLineWidth = 2.5;
var selectionLineWidth = 2;
var borderWidth = this.borderWidth;
var selectionLineWidth = this.borderWidthSelected || 2 * this.borderWidth;
var radiusMultiplier = 2;
// choose draw method depending on the shape
@ -800,16 +811,16 @@ Node.prototype._drawShape = function (ctx, shape) {
// draw the outer border
if (this.clusterSize > 1) {
ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth *= this.networkScaleInv;
ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth);
ctx.stroke();
}
ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0);
ctx.lineWidth *= this.networkScaleInv;
ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth);
ctx.lineWidth = Math.min(this.width,ctx.lineWidth);
ctx.fillStyle = this.selected ? this.color.highlight.background : this.hover ? this.color.hover.background : this.color.background;
ctx[shape](this.x, this.y, this.radius);
@ -967,3 +978,4 @@ Node.prototype.updateVelocity = function(massBeforeClustering) {
this.vy = Math.sqrt(energyBefore/this.mass);
};
module.exports = Node;

src/network/Popup.js → lib/network/Popup.js View File

@ -130,3 +130,5 @@ Popup.prototype.show = function (show) {
Popup.prototype.hide = function () {
this.frame.style.visibility = "hidden";
};
module.exports = Popup;

src/network/css/network-manipulation.css → lib/network/css/network-manipulation.css View File


src/network/css/network-navigation.css → lib/network/css/network-navigation.css View File


+ 826
- 0
lib/network/dotparser.js View File

@ -0,0 +1,826 @@
/**
* 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();
}
// 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,
'->': 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 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);
}
/**
* 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);
}
/**
* Preview the next character from the dot file.
* @return {String} cNext
*/
function nextPreview() {
return dot.charAt(index + 1);
}
/**
* 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);
}
/**
* 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 {
// this is the end point
o[key] = value;
}
}
}
/**
* 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;
// 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;
}
}
}
if (!current) {
// this is a new node
current = {
id: node.id
};
if (graph.node) {
// clone default attributes
current.attr = merge(current.attr, graph.node);
}
}
// 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 = [];
}
if (g.nodes.indexOf(current) == -1) {
g.nodes.push(current);
}
}
// merge attributes
if (node.attr) {
current.attr = merge(current.attr, node.attr);
}
}
/**
* 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;
}
/**
* Get next token in the current dot file.
* The token and token type are available as token and tokenType
*/
function getToken() {
tokenType = TOKENTYPE.NULL;
token = '';
// skip over whitespaces
while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
next();
}
do {
var isComment = false;
// 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;
}
}
if (c == '/' && nextPreview() == '/') {
// skip line comment
while (c != '' && c != '\n') {
next();
}
isComment = true;
}
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;
}
// skip over whitespaces
while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
next();
}
}
while (isComment);
// check for end of dot file
if (c == '') {
// token is still empty
tokenType = TOKENTYPE.DELIMITER;
return;
}
// 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;
}
// 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 (token == 'false') {
token = false; // convert to boolean
}
else if (token == 'true') {
token = true; // convert to boolean
}
else if (!isNaN(Number(token))) {
token = Number(token); // convert to number
}
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();
}
next();
}
if (c != '"') {
throw newSyntaxError('End of string " expected');
}
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) + '"');
}
/**
* Parse a graph.
* @returns {Object} graph
*/
function parseGraph() {
var graph = {};
first();
getToken();
// optional strict keyword
if (token == 'strict') {
graph.strict = true;
getToken();
}
// graph or digraph keyword
if (token == 'graph' || token == 'digraph') {
graph.type = token;
getToken();
}
// optional graph id
if (tokenType == TOKENTYPE.IDENTIFIER) {
graph.id = token;
getToken();
}
// open angle bracket
if (token != '{') {
throw newSyntaxError('Angle bracket { expected');
}
getToken();
// statements
parseStatements(graph);
// close angle bracket
if (token != '}') {
throw newSyntaxError('Angle bracket } expected');
}
getToken();
// end of file
if (token !== '') {
throw newSyntaxError('End of file expected');
}
getToken();
// remove temporary default properties
delete graph.node;
delete graph.edge;
delete graph.graph;
return graph;
}
/**
* Parse a list with statements.
* @param {Object} graph
*/
function parseStatements (graph) {
while (token !== '' && token != '}') {
parseStatement(graph);
if (token == ';') {
getToken();
}
}
}
/**
* 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);
return;
}
// parse an attribute statement
var attr = parseAttributeStatement(graph);
if (attr) {
return;
}
// parse node
if (tokenType != TOKENTYPE.IDENTIFIER) {
throw newSyntaxError('Identifier expected');
}
var id = token; // id can be a string or a number
getToken();
if (token == '=') {
// id statement
getToken();
if (tokenType != TOKENTYPE.IDENTIFIER) {
throw newSyntaxError('Identifier expected');
}
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;
// 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);
}
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.
*/
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';
}
return null;
}
/**
* parse a node statement
* @param {Object} graph
* @param {String | Number} id
*/
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);
}
/**
* Parse an edge or a series of edges
* @param {Object} graph
* @param {String | Number} from Id of the from node
*/
function parseEdge(graph, from) {
while (token == '->' || token == '--') {
var to;
var type = token;
getToken();
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();
}
// parse edge attributes
var attr = parseAttributeList();
// create edge
var edge = createEdge(graph, from, to, type, attr);
addEdge(graph, edge);
from = to;
}
}
/**
* Parse a set with attributes,
* for example [label="1.000", shape=solid]
* @return {Object | null} attr
*/
function parseAttributeList() {
var attr = null;
while (token == '[') {
getToken();
attr = {};
while (token !== '' && token != ']') {
if (tokenType != TOKENTYPE.IDENTIFIER) {
throw newSyntaxError('Attribute name expected');
}
var name = token;
getToken();
if (token != '=') {
throw newSyntaxError('Equal sign = expected');
}
getToken();
if (tokenType != TOKENTYPE.IDENTIFIER) {
throw newSyntaxError('Attribute value expected');
}
var value = token;
setValue(attr, name, value); // name can be a path
getToken();
if (token ==',') {
getToken();
}
}
if (token != ']') {
throw newSyntaxError('Bracket ] expected');
}
getToken();
}
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 + ')');
}
/**
* 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) + '...');
}
/**
* 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 (array1 instanceof Array) {
array1.forEach(function (elem1) {
if (array2 instanceof Array) {
array2.forEach(function (elem2) {
fn(elem1, elem2);
});
}
else {
fn(elem1, array2);
}
});
}
else {
if (array2 instanceof Array) {
array2.forEach(function (elem2) {
fn(array1, elem2);
});
}
else {
fn(array1, array2);
}
}
}
/**
* 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: {}
};
// 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);
});
}
// 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;
}
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;

+ 60
- 0
lib/network/gephiParser.js View File

@ -0,0 +1,60 @@
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};
}
exports.parseGephi = parseGephi;

src/network/img/acceptDeleteIcon.png → lib/network/img/acceptDeleteIcon.png View File


src/network/img/addNodeIcon.png → lib/network/img/addNodeIcon.png View File


src/network/img/backIcon.png → lib/network/img/backIcon.png View File


src/network/img/connectIcon.png → lib/network/img/connectIcon.png View File


src/network/img/cross.png → lib/network/img/cross.png View File


src/network/img/cross2.png → lib/network/img/cross2.png View File


src/network/img/deleteIcon.png → lib/network/img/deleteIcon.png View File


src/network/img/downArrow.png → lib/network/img/downArrow.png View File


src/network/img/editIcon.png → lib/network/img/editIcon.png View File


src/network/img/leftArrow.png → lib/network/img/leftArrow.png View File


src/network/img/minus.png → lib/network/img/minus.png View File


src/network/img/plus.png → lib/network/img/plus.png View File


src/network/img/rightArrow.png → lib/network/img/rightArrow.png View File


src/network/img/upArrow.png → lib/network/img/upArrow.png View File


src/network/img/zoomExtends.png → lib/network/img/zoomExtends.png View File


+ 1137
- 0
lib/network/mixins/ClusterMixin.js
File diff suppressed because it is too large
View File


+ 322
- 0
lib/network/mixins/HierarchicalLayoutMixin.js View File

@ -0,0 +1,322 @@
exports._resetLevels = function() {
for (var nodeId in this.nodes) {
if (this.nodes.hasOwnProperty(nodeId)) {
var node = this.nodes[nodeId];
if (node.preassignedLevel == false) {
node.level = -1;
}
}
}
};
/**
* This is the main function to layout the nodes in a hierarchical way.
* It checks if the node details are supplied correctly
*
* @private
*/
exports._setupHierarchicalLayout = function() {
if (this.constants.hierarchicalLayout.enabled == true && this.nodeIndices.length > 0) {
if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") {
this.constants.hierarchicalLayout.levelSeparation *= -1;
}
else {
this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation);
}
if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "LR") {
if (this.constants.smoothCurves.enabled == true) {
this.constants.smoothCurves.type = "vertical";
}
}
else {
if (this.constants.smoothCurves.enabled == true) {
this.constants.smoothCurves.type = "horizontal";
}
}
// get the size of the largest hubs and check if the user has defined a level for a node.
var hubsize = 0;
var node, nodeId;
var definedLevel = false;
var undefinedLevel = false;
for (nodeId in this.nodes) {
if (this.nodes.hasOwnProperty(nodeId)) {
node = this.nodes[nodeId];
if (node.level != -1) {
definedLevel = true;
}
else {
undefinedLevel = true;
}
if (hubsize < node.edges.length) {
hubsize = node.edges.length;
}
}
}
// if the user defined some levels but not all, alert and run without hierarchical layout
if (undefinedLevel == true && definedLevel == true) {
alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.");
this.zoomExtent(true,this.constants.clustering.enabled);
if (!this.constants.clustering.enabled) {
this.start();
}
}
else {
// setup the system to use hierarchical method.
this._changeConstants();
// define levels if undefined by the users. Based on hubsize
if (undefinedLevel == true) {
this._determineLevels(hubsize);
}
// check the distribution of the nodes per level.
var distribution = this._getDistribution();
// place the nodes on the canvas. This also stablilizes the system.
this._placeNodesByHierarchy(distribution);
// start the simulation.
this.start();
}
}
};
/**
* This function places the nodes on the canvas based on the hierarchial distribution.
*
* @param {Object} distribution | obtained by the function this._getDistribution()
* @private
*/
exports._placeNodesByHierarchy = function(distribution) {
var nodeId, node;
// start placing all the level 0 nodes first. Then recursively position their branches.
for (var level in distribution) {
if (distribution.hasOwnProperty(level)) {
for (nodeId in distribution[level].nodes) {
if (distribution[level].nodes.hasOwnProperty(nodeId)) {
node = distribution[level].nodes[nodeId];
if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
if (node.xFixed) {
node.x = distribution[level].minPos;
node.xFixed = false;
distribution[level].minPos += distribution[level].nodeSpacing;
}
}
else {
if (node.yFixed) {
node.y = distribution[level].minPos;
node.yFixed = false;
distribution[level].minPos += distribution[level].nodeSpacing;
}
}
this._placeBranchNodes(node.edges,node.id,distribution,node.level);
}
}
}
}
// stabilize the system after positioning. This function calls zoomExtent.
this._stabilize();
};
/**
* This function get the distribution of levels based on hubsize
*
* @returns {Object}
* @private
*/
exports._getDistribution = function() {
var distribution = {};
var nodeId, node, level;
// we fix Y because the hierarchy is vertical, we fix X so we do not give a node an x position for a second time.
// the fix of X is removed after the x value has been set.
for (nodeId in this.nodes) {
if (this.nodes.hasOwnProperty(nodeId)) {
node = this.nodes[nodeId];
node.xFixed = true;
node.yFixed = true;
if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
node.y = this.constants.hierarchicalLayout.levelSeparation*node.level;
}
else {
node.x = this.constants.hierarchicalLayout.levelSeparation*node.level;
}
if (distribution[node.level] === undefined) {
distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0};
}
distribution[node.level].amount += 1;
distribution[node.level].nodes[nodeId] = node;
}
}
// determine the largest amount of nodes of all levels
var maxCount = 0;
for (level in distribution) {
if (distribution.hasOwnProperty(level)) {
if (maxCount < distribution[level].amount) {
maxCount = distribution[level].amount;
}
}
}
// set the initial position and spacing of each nodes accordingly
for (level in distribution) {
if (distribution.hasOwnProperty(level)) {
distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing;
distribution[level].nodeSpacing /= (distribution[level].amount + 1);
distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing);
}
}
return distribution;
};
/**
* this function allocates nodes in levels based on the recursive branching from the largest hubs.
*
* @param hubsize
* @private
*/
exports._determineLevels = function(hubsize) {
var nodeId, node;
// determine hubs
for (nodeId in this.nodes) {
if (this.nodes.hasOwnProperty(nodeId)) {
node = this.nodes[nodeId];
if (node.edges.length == hubsize) {
node.level = 0;
}
}
}
// branch from hubs
for (nodeId in this.nodes) {
if (this.nodes.hasOwnProperty(nodeId)) {
node = this.nodes[nodeId];
if (node.level == 0) {
this._setLevel(1,node.edges,node.id);
}
}
}
};
/**
* Since hierarchical layout does not support:
* - smooth curves (based on the physics),
* - clustering (based on dynamic node counts)
*
* We disable both features so there will be no problems.
*
* @private
*/
exports._changeConstants = function() {
this.constants.clustering.enabled = false;
this.constants.physics.barnesHut.enabled = false;
this.constants.physics.hierarchicalRepulsion.enabled = true;
this._loadSelectedForceSolver();
if (this.constants.smoothCurves.enabled == true) {
this.constants.smoothCurves.dynamic = false;
}
this._configureSmoothCurves();
};
/**
* This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
* on a X position that ensures there will be no overlap.
*
* @param edges
* @param parentId
* @param distribution
* @param parentLevel
* @private
*/
exports._placeBranchNodes = function(edges, parentId, distribution, parentLevel) {
for (var i = 0; i < edges.length; i++) {
var childNode = null;
if (edges[i].toId == parentId) {
childNode = edges[i].from;
}
else {
childNode = edges[i].to;
}
// if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
var nodeMoved = false;
if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") {
if (childNode.xFixed && childNode.level > parentLevel) {
childNode.xFixed = false;
childNode.x = distribution[childNode.level].minPos;
nodeMoved = true;
}
}
else {
if (childNode.yFixed && childNode.level > parentLevel) {
childNode.yFixed = false;
childNode.y = distribution[childNode.level].minPos;
nodeMoved = true;
}
}
if (nodeMoved == true) {
distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing;
if (childNode.edges.length > 1) {
this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level);
}
}
}
};
/**
* this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
*
* @param level
* @param edges
* @param parentId
* @private
*/
exports._setLevel = function(level, edges, parentId) {
for (var i = 0; i < edges.length; i++) {
var childNode = null;
if (edges[i].toId == parentId) {
childNode = edges[i].from;
}
else {
childNode = edges[i].to;
}
if (childNode.level == -1 || childNode.level > level) {
childNode.level = level;
if (edges.length > 1) {
this._setLevel(level+1, childNode.edges, childNode.id);
}
}
}
};
/**
* Unfix nodes
*
* @private
*/
exports._restoreNodes = function() {
for (var nodeId in this.nodes) {
if (this.nodes.hasOwnProperty(nodeId)) {
this.nodes[nodeId].xFixed = false;
this.nodes[nodeId].yFixed = false;
}
}
};

+ 576
- 0
lib/network/mixins/ManipulationMixin.js View File

@ -0,0 +1,576 @@
var util = require('../../util');
var Node = require('../Node');
var Edge = require('../Edge');
/**
* clears the toolbar div element of children
*
* @private
*/
exports._clearManipulatorBar = function() {
while (this.manipulationDiv.hasChildNodes()) {
this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
}
};
/**
* Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore
* these functions to their original functionality, we saved them in this.cachedFunctions.
* This function restores these functions to their original function.
*
* @private
*/
exports._restoreOverloadedFunctions = function() {
for (var functionName in this.cachedFunctions) {
if (this.cachedFunctions.hasOwnProperty(functionName)) {
this[functionName] = this.cachedFunctions[functionName];
}
}
};
/**
* Enable or disable edit-mode.
*
* @private
*/
exports._toggleEditMode = function() {
this.editMode = !this.editMode;
var toolbar = document.getElementById("network-manipulationDiv");
var closeDiv = document.getElementById("network-manipulation-closeDiv");
var editModeDiv = document.getElementById("network-manipulation-editMode");
if (this.editMode == true) {
toolbar.style.display="block";
closeDiv.style.display="block";
editModeDiv.style.display="none";
closeDiv.onclick = this._toggleEditMode.bind(this);
}
else {
toolbar.style.display="none";
closeDiv.style.display="none";
editModeDiv.style.display="block";
closeDiv.onclick = null;
}
this._createManipulatorBar()
};
/**
* main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
*
* @private
*/
exports._createManipulatorBar = function() {
// remove bound functions
if (this.boundFunction) {
this.off('select', this.boundFunction);
}
if (this.edgeBeingEdited !== undefined) {
this.edgeBeingEdited._disableControlNodes();
this.edgeBeingEdited = undefined;
this.selectedControlNode = null;
this.controlNodesActive = false;
}
// restore overloaded functions
this._restoreOverloadedFunctions();
// resume calculation
this.freezeSimulation = false;
// reset global variables
this.blockConnectingEdgeSelection = false;
this.forceAppendSelection = false;
if (this.editMode == true) {
while (this.manipulationDiv.hasChildNodes()) {
this.manipulationDiv.removeChild(this.manipulationDiv.firstChild);
}
// add the icons to the manipulator div
this.manipulationDiv.innerHTML = "" +
"<span class='network-manipulationUI add' id='network-manipulate-addNode'>" +
"<span class='network-manipulationLabel'>"+this.constants.labels['add'] +"</span></span>" +
"<div class='network-seperatorLine'></div>" +
"<span class='network-manipulationUI connect' id='network-manipulate-connectNode'>" +
"<span class='network-manipulationLabel'>"+this.constants.labels['link'] +"</span></span>";
if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
this.manipulationDiv.innerHTML += "" +
"<div class='network-seperatorLine'></div>" +
"<span class='network-manipulationUI edit' id='network-manipulate-editNode'>" +
"<span class='network-manipulationLabel'>"+this.constants.labels['editNode'] +"</span></span>";
}
else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) {
this.manipulationDiv.innerHTML += "" +
"<div class='network-seperatorLine'></div>" +
"<span class='network-manipulationUI edit' id='network-manipulate-editEdge'>" +
"<span class='network-manipulationLabel'>"+this.constants.labels['editEdge'] +"</span></span>";
}
if (this._selectionIsEmpty() == false) {
this.manipulationDiv.innerHTML += "" +
"<div class='network-seperatorLine'></div>" +
"<span class='network-manipulationUI delete' id='network-manipulate-delete'>" +
"<span class='network-manipulationLabel'>"+this.constants.labels['del'] +"</span></span>";
}
// bind the icons
var addNodeButton = document.getElementById("network-manipulate-addNode");
addNodeButton.onclick = this._createAddNodeToolbar.bind(this);
var addEdgeButton = document.getElementById("network-manipulate-connectNode");
addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this);
if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) {
var editButton = document.getElementById("network-manipulate-editNode");
editButton.onclick = this._editNode.bind(this);
}
else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) {
var editButton = document.getElementById("network-manipulate-editEdge");
editButton.onclick = this._createEditEdgeToolbar.bind(this);
}
if (this._selectionIsEmpty() == false) {
var deleteButton = document.getElementById("network-manipulate-delete");
deleteButton.onclick = this._deleteSelected.bind(this);
}
var closeDiv = document.getElementById("network-manipulation-closeDiv");
closeDiv.onclick = this._toggleEditMode.bind(this);
this.boundFunction = this._createManipulatorBar.bind(this);
this.on('select', this.boundFunction);
}
else {
this.editModeDiv.innerHTML = "" +
"<span class='network-manipulationUI edit editmode' id='network-manipulate-editModeButton'>" +
"<span class='network-manipulationLabel'>" + this.constants.labels['edit'] + "</span></span>";
var editModeButton = document.getElementById("network-manipulate-editModeButton");
editModeButton.onclick = this._toggleEditMode.bind(this);
}
};
/**
* Create the toolbar for adding Nodes
*
* @private
*/
exports._createAddNodeToolbar = function() {
// clear the toolbar
this._clearManipulatorBar();
if (this.boundFunction) {
this.off('select', this.boundFunction);
}
// create the toolbar contents
this.manipulationDiv.innerHTML = "" +
"<span class='network-manipulationUI back' id='network-manipulate-back'>" +
"<span class='network-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
"<div class='network-seperatorLine'></div>" +
"<span class='network-manipulationUI none' id='network-manipulate-back'>" +
"<span id='network-manipulatorLabel' class='network-manipulationLabel'>" + this.constants.labels['addDescription'] + "</span></span>";
// bind the icon
var backButton = document.getElementById("network-manipulate-back");
backButton.onclick = this._createManipulatorBar.bind(this);
// we use the boundFunction so we can reference it when we unbind it from the "select" event.
this.boundFunction = this._addNode.bind(this);
this.on('select', this.boundFunction);
};
/**
* create the toolbar to connect nodes
*
* @private
*/
exports._createAddEdgeToolbar = function() {
// clear the toolbar
this._clearManipulatorBar();
this._unselectAll(true);
this.freezeSimulation = true;
if (this.boundFunction) {
this.off('select', this.boundFunction);
}
this._unselectAll();
this.forceAppendSelection = false;
this.blockConnectingEdgeSelection = true;
this.manipulationDiv.innerHTML = "" +
"<span class='network-manipulationUI back' id='network-manipulate-back'>" +
"<span class='network-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
"<div class='network-seperatorLine'></div>" +
"<span class='network-manipulationUI none' id='network-manipulate-back'>" +
"<span id='network-manipulatorLabel' class='network-manipulationLabel'>" + this.constants.labels['linkDescription'] + "</span></span>";
// bind the icon
var backButton = document.getElementById("network-manipulate-back");
backButton.onclick = this._createManipulatorBar.bind(this);
// we use the boundFunction so we can reference it when we unbind it from the "select" event.
this.boundFunction = this._handleConnect.bind(this);
this.on('select', this.boundFunction);
// temporarily overload functions
this.cachedFunctions["_handleTouch"] = this._handleTouch;
this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
this._handleTouch = this._handleConnect;
this._handleOnRelease = this._finishConnect;
// redraw to show the unselect
this._redraw();
};
/**
* create the toolbar to edit edges
*
* @private
*/
exports._createEditEdgeToolbar = function() {
// clear the toolbar
this._clearManipulatorBar();
this.controlNodesActive = true;
if (this.boundFunction) {
this.off('select', this.boundFunction);
}
this.edgeBeingEdited = this._getSelectedEdge();
this.edgeBeingEdited._enableControlNodes();
this.manipulationDiv.innerHTML = "" +
"<span class='network-manipulationUI back' id='network-manipulate-back'>" +
"<span class='network-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" +
"<div class='network-seperatorLine'></div>" +
"<span class='network-manipulationUI none' id='network-manipulate-back'>" +
"<span id='network-manipulatorLabel' class='network-manipulationLabel'>" + this.constants.labels['editEdgeDescription'] + "</span></span>";
// bind the icon
var backButton = document.getElementById("network-manipulate-back");
backButton.onclick = this._createManipulatorBar.bind(this);
// temporarily overload functions
this.cachedFunctions["_handleTouch"] = this._handleTouch;
this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease;
this.cachedFunctions["_handleTap"] = this._handleTap;
this.cachedFunctions["_handleDragStart"] = this._handleDragStart;
this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
this._handleTouch = this._selectControlNode;
this._handleTap = function () {};
this._handleOnDrag = this._controlNodeDrag;
this._handleDragStart = function () {}
this._handleOnRelease = this._releaseControlNode;
// redraw to show the unselect
this._redraw();
};
/**
* the function bound to the selection event. It checks if you want to connect a cluster and changes the description
* to walk the user through the process.
*
* @private
*/
exports._selectControlNode = function(pointer) {
this.edgeBeingEdited.controlNodes.from.unselect();
this.edgeBeingEdited.controlNodes.to.unselect();
this.selectedControlNode = this.edgeBeingEdited._getSelectedControlNode(this._XconvertDOMtoCanvas(pointer.x),this._YconvertDOMtoCanvas(pointer.y));
if (this.selectedControlNode !== null) {
this.selectedControlNode.select();
this.freezeSimulation = true;
}
this._redraw();
};
/**
* the function bound to the selection event. It checks if you want to connect a cluster and changes the description
* to walk the user through the process.
*
* @private
*/
exports._controlNodeDrag = function(event) {
var pointer = this._getPointer(event.gesture.center);
if (this.selectedControlNode !== null && this.selectedControlNode !== undefined) {
this.selectedControlNode.x = this._XconvertDOMtoCanvas(pointer.x);
this.selectedControlNode.y = this._YconvertDOMtoCanvas(pointer.y);
}
this._redraw();
};
exports._releaseControlNode = function(pointer) {
var newNode = this._getNodeAt(pointer);
if (newNode != null) {
if (this.edgeBeingEdited.controlNodes.from.selected == true) {
this._editEdge(newNode.id, this.edgeBeingEdited.to.id);
this.edgeBeingEdited.controlNodes.from.unselect();
}
if (this.edgeBeingEdited.controlNodes.to.selected == true) {
this._editEdge(this.edgeBeingEdited.from.id, newNode.id);
this.edgeBeingEdited.controlNodes.to.unselect();
}
}
else {
this.edgeBeingEdited._restoreControlNodes();
}
this.freezeSimulation = false;
this._redraw();
};
/**
* the function bound to the selection event. It checks if you want to connect a cluster and changes the description
* to walk the user through the process.
*
* @private
*/
exports._handleConnect = function(pointer) {
if (this._getSelectedNodeCount() == 0) {
var node = this._getNodeAt(pointer);
if (node != null) {
if (node.clusterSize > 1) {
alert("Cannot create edges to a cluster.")
}
else {
this._selectObject(node,false);
// create a node the temporary line can look at
this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants);
this.sectors['support']['nodes']['targetNode'].x = node.x;
this.sectors['support']['nodes']['targetNode'].y = node.y;
this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants);
this.sectors['support']['nodes']['targetViaNode'].x = node.x;
this.sectors['support']['nodes']['targetViaNode'].y = node.y;
this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge";
// create a temporary edge
this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants);
this.edges['connectionEdge'].from = node;
this.edges['connectionEdge'].connected = true;
this.edges['connectionEdge'].smooth = true;
this.edges['connectionEdge'].selected = true;
this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode'];
this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode'];
this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag;
this._handleOnDrag = function(event) {
var pointer = this._getPointer(event.gesture.center);
this.sectors['support']['nodes']['targetNode'].x = this._XconvertDOMtoCanvas(pointer.x);
this.sectors['support']['nodes']['targetNode'].y = this._YconvertDOMtoCanvas(pointer.y);
this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._XconvertDOMtoCanvas(pointer.x) + this.edges['connectionEdge'].from.x);
this.sectors['support']['nodes']['targetViaNode'].y = this._YconvertDOMtoCanvas(pointer.y);
};
this.moving = true;
this.start();
}
}
}
};
exports._finishConnect = function(pointer) {
if (this._getSelectedNodeCount() == 1) {
// restore the drag function
this._handleOnDrag = this.cachedFunctions["_handleOnDrag"];
delete this.cachedFunctions["_handleOnDrag"];
// remember the edge id
var connectFromId = this.edges['connectionEdge'].fromId;
// remove the temporary nodes and edge
delete this.edges['connectionEdge'];
delete this.sectors['support']['nodes']['targetNode'];
delete this.sectors['support']['nodes']['targetViaNode'];
var node = this._getNodeAt(pointer);
if (node != null) {
if (node.clusterSize > 1) {
alert("Cannot create edges to a cluster.")
}
else {
this._createEdge(connectFromId,node.id);
this._createManipulatorBar();
}
}
this._unselectAll();
}
};
/**
* Adds a node on the specified location
*/
exports._addNode = function() {
if (this._selectionIsEmpty() && this.editMode == true) {
var positionObject = this._pointerToPositionObject(this.pointerPosition);
var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true};
if (this.triggerFunctions.add) {
if (this.triggerFunctions.add.length == 2) {
var me = this;
this.triggerFunctions.add(defaultData, function(finalizedData) {
me.nodesData.add(finalizedData);
me._createManipulatorBar();
me.moving = true;
me.start();
});
}
else {
alert(this.constants.labels['addError']);
this._createManipulatorBar();
this.moving = true;
this.start();
}
}
else {
this.nodesData.add(defaultData);
this._createManipulatorBar();
this.moving = true;
this.start();
}
}
};
/**
* connect two nodes with a new edge.
*
* @private
*/
exports._createEdge = function(sourceNodeId,targetNodeId) {
if (this.editMode == true) {
var defaultData = {from:sourceNodeId, to:targetNodeId};
if (this.triggerFunctions.connect) {
if (this.triggerFunctions.connect.length == 2) {
var me = this;
this.triggerFunctions.connect(defaultData, function(finalizedData) {
me.edgesData.add(finalizedData);
me.moving = true;
me.start();
});
}
else {
alert(this.constants.labels["linkError"]);
this.moving = true;
this.start();
}
}
else {
this.edgesData.add(defaultData);
this.moving = true;
this.start();
}
}
};
/**
* connect two nodes with a new edge.
*
* @private
*/
exports._editEdge = function(sourceNodeId,targetNodeId) {
if (this.editMode == true) {
var defaultData = {id: this.edgeBeingEdited.id, from:sourceNodeId, to:targetNodeId};
if (this.triggerFunctions.editEdge) {
if (this.triggerFunctions.editEdge.length == 2) {
var me = this;
this.triggerFunctions.editEdge(defaultData, function(finalizedData) {
me.edgesData.update(finalizedData);
me.moving = true;
me.start();
});
}
else {
alert(this.constants.labels["linkError"]);
this.moving = true;
this.start();
}
}
else {
this.edgesData.update(defaultData);
this.moving = true;
this.start();
}
}
};
/**
* Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color.
*
* @private
*/
exports._editNode = function() {
if (this.triggerFunctions.edit && this.editMode == true) {
var node = this._getSelectedNode();
var data = {id:node.id,
label: node.label,
group: node.group,
shape: node.shape,
color: {
background:node.color.background,
border:node.color.border,
highlight: {
background:node.color.highlight.background,
border:node.color.highlight.border
}
}};
if (this.triggerFunctions.edit.length == 2) {
var me = this;
this.triggerFunctions.edit(data, function (finalizedData) {
me.nodesData.update(finalizedData);
me._createManipulatorBar();
me.moving = true;
me.start();
});
}
else {
alert(this.constants.labels["editError"]);
}
}
else {
alert(this.constants.labels["editBoundError"]);
}
};
/**
* delete everything in the selection
*
* @private
*/
exports._deleteSelected = function() {
if (!this._selectionIsEmpty() && this.editMode == true) {
if (!this._clusterInSelection()) {
var selectedNodes = this.getSelectedNodes();
var selectedEdges = this.getSelectedEdges();
if (this.triggerFunctions.del) {
var me = this;
var data = {nodes: selectedNodes, edges: selectedEdges};
if (this.triggerFunctions.del.length = 2) {
this.triggerFunctions.del(data, function (finalizedData) {
me.edgesData.remove(finalizedData.edges);
me.nodesData.remove(finalizedData.nodes);
me._unselectAll();
me.moving = true;
me.start();
});
}
else {
alert(this.constants.labels["deleteError"])
}
}
else {
this.edgesData.remove(selectedEdges);
this.nodesData.remove(selectedNodes);
this._unselectAll();
this.moving = true;
this.start();
}
}
else {
alert(this.constants.labels["deleteClusterError"]);
}
}
};

+ 198
- 0
lib/network/mixins/MixinLoader.js View File

@ -0,0 +1,198 @@
var PhysicsMixin = require('./physics/PhysicsMixin');
var ClusterMixin = require('./ClusterMixin');
var SectorsMixin = require('./SectorsMixin');
var SelectionMixin = require('./SelectionMixin');
var ManipulationMixin = require('./ManipulationMixin');
var NavigationMixin = require('./NavigationMixin');
var HierarchicalLayoutMixin = require('./HierarchicalLayoutMixin');
/**
* Load a mixin into the network object
*
* @param {Object} sourceVariable | this object has to contain functions.
* @private
*/
exports._loadMixin = function (sourceVariable) {
for (var mixinFunction in sourceVariable) {
if (sourceVariable.hasOwnProperty(mixinFunction)) {
this[mixinFunction] = sourceVariable[mixinFunction];
}
}
};
/**
* removes a mixin from the network object.
*
* @param {Object} sourceVariable | this object has to contain functions.
* @private
*/
exports._clearMixin = function (sourceVariable) {
for (var mixinFunction in sourceVariable) {
if (sourceVariable.hasOwnProperty(mixinFunction)) {
this[mixinFunction] = undefined;
}
}
};
/**
* Mixin the physics system and initialize the parameters required.
*
* @private
*/
exports._loadPhysicsSystem = function () {
this._loadMixin(PhysicsMixin);
this._loadSelectedForceSolver();
if (this.constants.configurePhysics == true) {
this._loadPhysicsConfiguration();
}
};
/**
* Mixin the cluster system and initialize the parameters required.
*
* @private
*/
exports._loadClusterSystem = function () {
this.clusterSession = 0;
this.hubThreshold = 5;
this._loadMixin(ClusterMixin);
};
/**
* Mixin the sector system and initialize the parameters required
*
* @private
*/
exports._loadSectorSystem = function () {
this.sectors = {};
this.activeSector = ["default"];
this.sectors["active"] = {};
this.sectors["active"]["default"] = {"nodes": {},
"edges": {},
"nodeIndices": [],
"formationScale": 1.0,
"drawingNode": undefined };
this.sectors["frozen"] = {};
this.sectors["support"] = {"nodes": {},
"edges": {},
"nodeIndices": [],
"formationScale": 1.0,
"drawingNode": undefined };
this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields
this._loadMixin(SectorsMixin);
};
/**
* Mixin the selection system and initialize the parameters required
*
* @private
*/
exports._loadSelectionSystem = function () {
this.selectionObj = {nodes: {}, edges: {}};
this._loadMixin(SelectionMixin);
};
/**
* Mixin the navigationUI (User Interface) system and initialize the parameters required
*
* @private
*/
exports._loadManipulationSystem = function () {
// reset global variables -- these are used by the selection of nodes and edges.
this.blockConnectingEdgeSelection = false;
this.forceAppendSelection = false;
if (this.constants.dataManipulation.enabled == true) {
// load the manipulator HTML elements. All styling done in css.
if (this.manipulationDiv === undefined) {
this.manipulationDiv = document.createElement('div');
this.manipulationDiv.className = 'network-manipulationDiv';
this.manipulationDiv.id = 'network-manipulationDiv';
if (this.editMode == true) {
this.manipulationDiv.style.display = "block";
}
else {
this.manipulationDiv.style.display = "none";
}
this.containerElement.insertBefore(this.manipulationDiv, this.frame);
}
if (this.editModeDiv === undefined) {
this.editModeDiv = document.createElement('div');
this.editModeDiv.className = 'network-manipulation-editMode';
this.editModeDiv.id = 'network-manipulation-editMode';
if (this.editMode == true) {
this.editModeDiv.style.display = "none";
}
else {
this.editModeDiv.style.display = "block";
}
this.containerElement.insertBefore(this.editModeDiv, this.frame);
}
if (this.closeDiv === undefined) {
this.closeDiv = document.createElement('div');
this.closeDiv.className = 'network-manipulation-closeDiv';
this.closeDiv.id = 'network-manipulation-closeDiv';
this.closeDiv.style.display = this.manipulationDiv.style.display;
this.containerElement.insertBefore(this.closeDiv, this.frame);
}
// load the manipulation functions
this._loadMixin(ManipulationMixin);
// create the manipulator toolbar
this._createManipulatorBar();
}
else {
if (this.manipulationDiv !== undefined) {
// removes all the bindings and overloads
this._createManipulatorBar();
// remove the manipulation divs
this.containerElement.removeChild(this.manipulationDiv);
this.containerElement.removeChild(this.editModeDiv);
this.containerElement.removeChild(this.closeDiv);
this.manipulationDiv = undefined;
this.editModeDiv = undefined;
this.closeDiv = undefined;
// remove the mixin functions
this._clearMixin(ManipulationMixin);
}
}
};
/**
* Mixin the navigation (User Interface) system and initialize the parameters required
*
* @private
*/
exports._loadNavigationControls = function () {
this._loadMixin(NavigationMixin);
// the clean function removes the button divs, this is done to remove the bindings.
this._cleanNavigation();
if (this.constants.navigation.enabled == true) {
this._loadNavigationElements();
}
};
/**
* Mixin the hierarchical layout system.
*
* @private
*/
exports._loadHierarchySystem = function () {
this._loadMixin(HierarchicalLayoutMixin);
};

+ 181
- 0
lib/network/mixins/NavigationMixin.js View File

@ -0,0 +1,181 @@
var util = require('../../util');
exports._cleanNavigation = function() {
// clean up previous navigation items
var wrapper = document.getElementById('network-navigation_wrapper');
if (wrapper != null) {
this.containerElement.removeChild(wrapper);
}
document.onmouseup = null;
};
/**
* Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
* they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
* on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
* This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
*
* @private
*/
exports._loadNavigationElements = function() {
this._cleanNavigation();
this.navigationDivs = {};
var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends'];
var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent'];
this.navigationDivs['wrapper'] = document.createElement('div');
this.navigationDivs['wrapper'].id = "network-navigation_wrapper";
this.navigationDivs['wrapper'].style.position = "absolute";
this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px";
this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px";
this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame);
for (var i = 0; i < navigationDivs.length; i++) {
this.navigationDivs[navigationDivs[i]] = document.createElement('div');
this.navigationDivs[navigationDivs[i]].id = "network-navigation_" + navigationDivs[i];
this.navigationDivs[navigationDivs[i]].className = "network-navigation " + navigationDivs[i];
this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]);
this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this);
}
document.onmouseup = this._stopMovement.bind(this);
};
/**
* this stops all movement induced by the navigation buttons
*
* @private
*/
exports._stopMovement = function() {
this._xStopMoving();
this._yStopMoving();
this._stopZoom();
};
/**
* move the screen up
* By using the increments, instead of adding a fixed number to the translation, we keep fluent and
* instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently
* To avoid this behaviour, we do the translation in the start loop.
*
* @private
*/
exports._moveUp = function(event) {
this.yIncrement = this.constants.keyboard.speed.y;
this.start(); // if there is no node movement, the calculation wont be done
util.preventDefault(event);
if (this.navigationDivs) {
this.navigationDivs['up'].className += " active";
}
};
/**
* move the screen down
* @private
*/
exports._moveDown = function(event) {
this.yIncrement = -this.constants.keyboard.speed.y;
this.start(); // if there is no node movement, the calculation wont be done
util.preventDefault(event);
if (this.navigationDivs) {
this.navigationDivs['down'].className += " active";
}
};
/**
* move the screen left
* @private
*/
exports._moveLeft = function(event) {
this.xIncrement = this.constants.keyboard.speed.x;
this.start(); // if there is no node movement, the calculation wont be done
util.preventDefault(event);
if (this.navigationDivs) {
this.navigationDivs['left'].className += " active";
}
};
/**
* move the screen right
* @private
*/
exports._moveRight = function(event) {
this.xIncrement = -this.constants.keyboard.speed.y;
this.start(); // if there is no node movement, the calculation wont be done
util.preventDefault(event);
if (this.navigationDivs) {
this.navigationDivs['right'].className += " active";
}
};
/**
* Zoom in, using the same method as the movement.
* @private
*/
exports._zoomIn = function(event) {
this.zoomIncrement = this.constants.keyboard.speed.zoom;
this.start(); // if there is no node movement, the calculation wont be done
util.preventDefault(event);
if (this.navigationDivs) {
this.navigationDivs['zoomIn'].className += " active";
}
};
/**
* Zoom out
* @private
*/
exports._zoomOut = function() {
this.zoomIncrement = -this.constants.keyboard.speed.zoom;
this.start(); // if there is no node movement, the calculation wont be done
util.preventDefault(event);
if (this.navigationDivs) {
this.navigationDivs['zoomOut'].className += " active";
}
};
/**
* Stop zooming and unhighlight the zoom controls
* @private
*/
exports._stopZoom = function() {
this.zoomIncrement = 0;
if (this.navigationDivs) {
this.navigationDivs['zoomIn'].className = this.navigationDivs['zoomIn'].className.replace(" active","");
this.navigationDivs['zoomOut'].className = this.navigationDivs['zoomOut'].className.replace(" active","");
}
};
/**
* Stop moving in the Y direction and unHighlight the up and down
* @private
*/
exports._yStopMoving = function() {
this.yIncrement = 0;
if (this.navigationDivs) {
this.navigationDivs['up'].className = this.navigationDivs['up'].className.replace(" active","");
this.navigationDivs['down'].className = this.navigationDivs['down'].className.replace(" active","");
}
};
/**
* Stop moving in the X direction and unHighlight left and right.
* @private
*/
exports._xStopMoving = function() {
this.xIncrement = 0;
if (this.navigationDivs) {
this.navigationDivs['left'].className = this.navigationDivs['left'].className.replace(" active","");
this.navigationDivs['right'].className = this.navigationDivs['right'].className.replace(" active","");
}
};

+ 548
- 0
lib/network/mixins/SectorsMixin.js View File

@ -0,0 +1,548 @@
var util = require('../../util');
/**
* Creation of the SectorMixin var.
*
* This contains all the functions the Network object can use to employ the sector system.
* The sector system is always used by Network, though the benefits only apply to the use of clustering.
* If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges.
*/
/**
* This function is only called by the setData function of the Network object.
* This loads the global references into the active sector. This initializes the sector.
*
* @private
*/
exports._putDataInSector = function() {
this.sectors["active"][this._sector()].nodes = this.nodes;
this.sectors["active"][this._sector()].edges = this.edges;
this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices;
};
/**
* /**
* This function sets the global references to nodes, edges and nodeIndices back to
* those of the supplied (active) sector. If a type is defined, do the specific type
*
* @param {String} sectorId
* @param {String} [sectorType] | "active" or "frozen"
* @private
*/
exports._switchToSector = function(sectorId, sectorType) {
if (sectorType === undefined || sectorType == "active") {
this._switchToActiveSector(sectorId);
}
else {
this._switchToFrozenSector(sectorId);
}
};
/**
* This function sets the global references to nodes, edges and nodeIndices back to
* those of the supplied active sector.
*
* @param sectorId
* @private
*/
exports._switchToActiveSector = function(sectorId) {
this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"];
this.nodes = this.sectors["active"][sectorId]["nodes"];
this.edges = this.sectors["active"][sectorId]["edges"];
};
/**
* This function sets the global references to nodes, edges and nodeIndices back to
* those of the supplied active sector.
*
* @private
*/
exports._switchToSupportSector = function() {
this.nodeIndices = this.sectors["support"]["nodeIndices"];
this.nodes = this.sectors["support"]["nodes"];
this.edges = this.sectors["support"]["edges"];
};
/**
* This function sets the global references to nodes, edges and nodeIndices back to
* those of the supplied frozen sector.
*
* @param sectorId
* @private
*/
exports._switchToFrozenSector = function(sectorId) {
this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"];
this.nodes = this.sectors["frozen"][sectorId]["nodes"];
this.edges = this.sectors["frozen"][sectorId]["edges"];
};
/**
* This function sets the global references to nodes, edges and nodeIndices back to
* those of the currently active sector.
*
* @private
*/
exports._loadLatestSector = function() {
this._switchToSector(this._sector());
};
/**
* This function returns the currently active sector Id
*
* @returns {String}
* @private
*/
exports._sector = function() {
return this.activeSector[this.activeSector.length-1];
};
/**
* This function returns the previously active sector Id
*
* @returns {String}
* @private
*/
exports._previousSector = function() {
if (this.activeSector.length > 1) {
return this.activeSector[this.activeSector.length-2];
}
else {
throw new TypeError('there are not enough sectors in the this.activeSector array.');
}
};
/**
* We add the active sector at the end of the this.activeSector array
* This ensures it is the currently active sector returned by _sector() and it reaches the top
* of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack.
*
* @param newId
* @private
*/
exports._setActiveSector = function(newId) {
this.activeSector.push(newId);
};
/**
* We remove the currently active sector id from the active sector stack. This happens when
* we reactivate the previously active sector
*
* @private
*/
exports._forgetLastSector = function() {
this.activeSector.pop();
};
/**
* This function creates a new active sector with the supplied newId. This newId
* is the expanding node id.
*
* @param {String} newId | Id of the new active sector
* @private
*/
exports._createNewSector = function(newId) {
// create the new sector
this.sectors["active"][newId] = {"nodes":{},
"edges":{},
"nodeIndices":[],
"formationScale": this.scale,
"drawingNode": undefined};
// create the new sector render node. This gives visual feedback that you are in a new sector.
this.sectors["active"][newId]['drawingNode'] = new Node(
{id:newId,
color: {
background: "#eaefef",
border: "495c5e"
}
},{},{},this.constants);
this.sectors["active"][newId]['drawingNode'].clusterSize = 2;
};
/**
* This function removes the currently active sector. This is called when we create a new
* active sector.
*
* @param {String} sectorId | Id of the active sector that will be removed
* @private
*/
exports._deleteActiveSector = function(sectorId) {
delete this.sectors["active"][sectorId];
};
/**
* This function removes the currently active sector. This is called when we reactivate
* the previously active sector.
*
* @param {String} sectorId | Id of the active sector that will be removed
* @private
*/
exports._deleteFrozenSector = function(sectorId) {
delete this.sectors["frozen"][sectorId];
};
/**
* Freezing an active sector means moving it from the "active" object to the "frozen" object.
* We copy the references, then delete the active entree.
*
* @param sectorId
* @private
*/
exports._freezeSector = function(sectorId) {
// we move the set references from the active to the frozen stack.
this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId];
// we have moved the sector data into the frozen set, we now remove it from the active set
this._deleteActiveSector(sectorId);
};
/**
* This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen"
* object to the "active" object.
*
* @param sectorId
* @private
*/
exports._activateSector = function(sectorId) {
// we move the set references from the frozen to the active stack.
this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId];
// we have moved the sector data into the active set, we now remove it from the frozen stack
this._deleteFrozenSector(sectorId);
};
/**
* This function merges the data from the currently active sector with a frozen sector. This is used
* in the process of reverting back to the previously active sector.
* The data that is placed in the frozen (the previously active) sector is the node that has been removed from it
* upon the creation of a new active sector.
*
* @param sectorId
* @private
*/
exports._mergeThisWithFrozen = function(sectorId) {
// copy all nodes
for (var nodeId in this.nodes) {
if (this.nodes.hasOwnProperty(nodeId)) {
this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId];
}
}
// copy all edges (if not fully clustered, else there are no edges)
for (var edgeId in this.edges) {
if (this.edges.hasOwnProperty(edgeId)) {
this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId];
}
}
// merge the nodeIndices
for (var i = 0; i < this.nodeIndices.length; i++) {
this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]);
}
};
/**
* This clusters the sector to one cluster. It was a single cluster before this process started so
* we revert to that state. The clusterToFit function with a maximum size of 1 node does this.
*
* @private
*/
exports._collapseThisToSingleCluster = function() {
this.clusterToFit(1,false);
};
/**
* We create a new active sector from the node that we want to open.
*
* @param node
* @private
*/
exports._addSector = function(node) {
// this is the currently active sector
var sector = this._sector();
// // this should allow me to select nodes from a frozen set.
// if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) {
// console.log("the node is part of the active sector");
// }
// else {
// console.log("I dont know what the fuck happened!!");
// }
// when we switch to a new sector, we remove the node that will be expanded from the current nodes list.
delete this.nodes[node.id];
var unqiueIdentifier = util.randomUUID();
// we fully freeze the currently active sector
this._freezeSector(sector);
// we create a new active sector. This sector has the Id of the node to ensure uniqueness
this._createNewSector(unqiueIdentifier);
// we add the active sector to the sectors array to be able to revert these steps later on
this._setActiveSector(unqiueIdentifier);
// we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier
this._switchToSector(this._sector());
// finally we add the node we removed from our previous active sector to the new active sector
this.nodes[node.id] = node;
};
/**
* We close the sector that is currently open and revert back to the one before.
* If the active sector is the "default" sector, nothing happens.
*
* @private
*/
exports._collapseSector = function() {
// the currently active sector
var sector = this._sector();
// we cannot collapse the default sector
if (sector != "default") {
if ((this.nodeIndices.length == 1) ||
(this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) ||
(this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) {
var previousSector = this._previousSector();
// we collapse the sector back to a single cluster
this._collapseThisToSingleCluster();
// we move the remaining nodes, edges and nodeIndices to the previous sector.
// This previous sector is the one we will reactivate
this._mergeThisWithFrozen(previousSector);
// the previously active (frozen) sector now has all the data from the currently active sector.
// we can now delete the active sector.
this._deleteActiveSector(sector);
// we activate the previously active (and currently frozen) sector.
this._activateSector(previousSector);
// we load the references from the newly active sector into the global references
this._switchToSector(previousSector);
// we forget the previously active sector because we reverted to the one before
this._forgetLastSector();
// finally, we update the node index list.
this._updateNodeIndexList();
// we refresh the list with calulation nodes and calculation node indices.
this._updateCalculationNodes();
}
}
};
/**
* This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
*
* @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
* | we dont pass the function itself because then the "this" is the window object
* | instead of the Network object
* @param {*} [argument] | Optional: arguments to pass to the runFunction
* @private
*/
exports._doInAllActiveSectors = function(runFunction,argument) {
if (argument === undefined) {
for (var sector in this.sectors["active"]) {
if (this.sectors["active"].hasOwnProperty(sector)) {
// switch the global references to those of this sector
this._switchToActiveSector(sector);
this[runFunction]();
}
}
}
else {
for (var sector in this.sectors["active"]) {
if (this.sectors["active"].hasOwnProperty(sector)) {
// switch the global references to those of this sector
this._switchToActiveSector(sector);
var args = Array.prototype.splice.call(arguments, 1);
if (args.length > 1) {
this[runFunction](args[0],args[1]);
}
else {
this[runFunction](argument);
}
}
}
}
// we revert the global references back to our active sector
this._loadLatestSector();
};
/**
* This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation().
*
* @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
* | we dont pass the function itself because then the "this" is the window object
* | instead of the Network object
* @param {*} [argument] | Optional: arguments to pass to the runFunction
* @private
*/
exports._doInSupportSector = function(runFunction,argument) {
if (argument === undefined) {
this._switchToSupportSector();
this[runFunction]();
}
else {
this._switchToSupportSector();
var args = Array.prototype.splice.call(arguments, 1);
if (args.length > 1) {
this[runFunction](args[0],args[1]);
}
else {
this[runFunction](argument);
}
}
// we revert the global references back to our active sector
this._loadLatestSector();
};
/**
* This runs a function in all frozen sectors. This is used in the _redraw().
*
* @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
* | we don't pass the function itself because then the "this" is the window object
* | instead of the Network object
* @param {*} [argument] | Optional: arguments to pass to the runFunction
* @private
*/
exports._doInAllFrozenSectors = function(runFunction,argument) {
if (argument === undefined) {
for (var sector in this.sectors["frozen"]) {
if (this.sectors["frozen"].hasOwnProperty(sector)) {
// switch the global references to those of this sector
this._switchToFrozenSector(sector);
this[runFunction]();
}
}
}
else {
for (var sector in this.sectors["frozen"]) {
if (this.sectors["frozen"].hasOwnProperty(sector)) {
// switch the global references to those of this sector
this._switchToFrozenSector(sector);
var args = Array.prototype.splice.call(arguments, 1);
if (args.length > 1) {
this[runFunction](args[0],args[1]);
}
else {
this[runFunction](argument);
}
}
}
}
this._loadLatestSector();
};
/**
* This runs a function in all sectors. This is used in the _redraw().
*
* @param {String} runFunction | This is the NAME of a function we want to call in all active sectors
* | we don't pass the function itself because then the "this" is the window object
* | instead of the Network object
* @param {*} [argument] | Optional: arguments to pass to the runFunction
* @private
*/
exports._doInAllSectors = function(runFunction,argument) {
var args = Array.prototype.splice.call(arguments, 1);
if (argument === undefined) {
this._doInAllActiveSectors(runFunction);
this._doInAllFrozenSectors(runFunction);
}
else {
if (args.length > 1) {
this._doInAllActiveSectors(runFunction,args[0],args[1]);
this._doInAllFrozenSectors(runFunction,args[0],args[1]);
}
else {
this._doInAllActiveSectors(runFunction,argument);
this._doInAllFrozenSectors(runFunction,argument);
}
}
};
/**
* This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the
* active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it.
*
* @private
*/
exports._clearNodeIndexList = function() {
var sector = this._sector();
this.sectors["active"][sector]["nodeIndices"] = [];
this.nodeIndices = this.sectors["active"][sector]["nodeIndices"];
};
/**
* Draw the encompassing sector node
*
* @param ctx
* @param sectorType
* @private
*/
exports._drawSectorNodes = function(ctx,sectorType) {
var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node;
for (var sector in this.sectors[sectorType]) {
if (this.sectors[sectorType].hasOwnProperty(sector)) {
if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) {
this._switchToSector(sector,sectorType);
minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9;
for (var nodeId in this.nodes) {
if (this.nodes.hasOwnProperty(nodeId)) {
node = this.nodes[nodeId];
node.resize(ctx);
if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;}
if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;}
if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;}
if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;}
}
}
node = this.sectors[sectorType][sector]["drawingNode"];
node.x = 0.5 * (maxX + minX);
node.y = 0.5 * (maxY + minY);
node.width = 2 * (node.x - minX);
node.height = 2 * (node.y - minY);
node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2));
node.setScale(this.scale);
node._drawCircle(ctx);
}
}
}
};
exports._drawAllSectorNodes = function(ctx) {
this._drawSectorNodes(ctx,"frozen");
this._drawSectorNodes(ctx,"active");
this._loadLatestSector();
};

+ 705
- 0
lib/network/mixins/SelectionMixin.js View File

@ -0,0 +1,705 @@
var Node = require('../Node');
/**
* This function can be called from the _doInAllSectors function
*
* @param object
* @param overlappingNodes
* @private
*/
exports._getNodesOverlappingWith = function(object, overlappingNodes) {
var nodes = this.nodes;
for (var nodeId in nodes) {
if (nodes.hasOwnProperty(nodeId)) {
if (nodes[nodeId].isOverlappingWith(object)) {
overlappingNodes.push(nodeId);
}
}
}
};
/**
* retrieve all nodes overlapping with given object
* @param {Object} object An object with parameters left, top, right, bottom
* @return {Number[]} An array with id's of the overlapping nodes
* @private
*/
exports._getAllNodesOverlappingWith = function (object) {
var overlappingNodes = [];
this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes);
return overlappingNodes;
};
/**
* Return a position object in canvasspace from a single point in screenspace
*
* @param pointer
* @returns {{left: number, top: number, right: number, bottom: number}}
* @private
*/
exports._pointerToPositionObject = function(pointer) {
var x = this._XconvertDOMtoCanvas(pointer.x);
var y = this._YconvertDOMtoCanvas(pointer.y);
return {
left: x,
top: y,
right: x,
bottom: y
};
};
/**
* Get the top node at the a specific point (like a click)
*
* @param {{x: Number, y: Number}} pointer
* @return {Node | null} node
* @private
*/
exports._getNodeAt = function (pointer) {
// we first check if this is an navigation controls element
var positionObject = this._pointerToPositionObject(pointer);
var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
// if there are overlapping nodes, select the last one, this is the
// one which is drawn on top of the others
if (overlappingNodes.length > 0) {
return this.nodes[overlappingNodes[overlappingNodes.length - 1]];
}
else {
return null;
}
};
/**
* retrieve all edges overlapping with given object, selector is around center
* @param {Object} object An object with parameters left, top, right, bottom
* @return {Number[]} An array with id's of the overlapping nodes
* @private
*/
exports._getEdgesOverlappingWith = function (object, overlappingEdges) {
var edges = this.edges;
for (var edgeId in edges) {
if (edges.hasOwnProperty(edgeId)) {
if (edges[edgeId].isOverlappingWith(object)) {
overlappingEdges.push(edgeId);
}
}
}
};
/**
* retrieve all nodes overlapping with given object
* @param {Object} object An object with parameters left, top, right, bottom
* @return {Number[]} An array with id's of the overlapping nodes
* @private
*/
exports._getAllEdgesOverlappingWith = function (object) {
var overlappingEdges = [];
this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges);
return overlappingEdges;
};
/**
* Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call
* _getNodeAt and _getEdgesAt, then priortize the selection to user preferences.
*
* @param pointer
* @returns {null}
* @private
*/
exports._getEdgeAt = function(pointer) {
var positionObject = this._pointerToPositionObject(pointer);
var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject);
if (overlappingEdges.length > 0) {
return this.edges[overlappingEdges[overlappingEdges.length - 1]];
}
else {
return null;
}
};
/**
* Add object to the selection array.
*
* @param obj
* @private
*/
exports._addToSelection = function(obj) {
if (obj instanceof Node) {
this.selectionObj.nodes[obj.id] = obj;
}
else {
this.selectionObj.edges[obj.id] = obj;
}
};
/**
* Add object to the selection array.
*
* @param obj
* @private
*/
exports._addToHover = function(obj) {
if (obj instanceof Node) {
this.hoverObj.nodes[obj.id] = obj;
}
else {
this.hoverObj.edges[obj.id] = obj;
}
};
/**
* Remove a single option from selection.
*
* @param {Object} obj
* @private
*/
exports._removeFromSelection = function(obj) {
if (obj instanceof Node) {
delete this.selectionObj.nodes[obj.id];
}
else {
delete this.selectionObj.edges[obj.id];
}
};
/**
* Unselect all. The selectionObj is useful for this.
*
* @param {Boolean} [doNotTrigger] | ignore trigger
* @private
*/
exports._unselectAll = function(doNotTrigger) {
if (doNotTrigger === undefined) {
doNotTrigger = false;
}
for(var nodeId in this.selectionObj.nodes) {
if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
this.selectionObj.nodes[nodeId].unselect();
}
}
for(var edgeId in this.selectionObj.edges) {
if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
this.selectionObj.edges[edgeId].unselect();
}
}
this.selectionObj = {nodes:{},edges:{}};
if (doNotTrigger == false) {
this.emit('select', this.getSelection());
}
};
/**
* Unselect all clusters. The selectionObj is useful for this.
*
* @param {Boolean} [doNotTrigger] | ignore trigger
* @private
*/
exports._unselectClusters = function(doNotTrigger) {
if (doNotTrigger === undefined) {
doNotTrigger = false;
}
for (var nodeId in this.selectionObj.nodes) {
if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
this.selectionObj.nodes[nodeId].unselect();
this._removeFromSelection(this.selectionObj.nodes[nodeId]);
}
}
}
if (doNotTrigger == false) {
this.emit('select', this.getSelection());
}
};
/**
* return the number of selected nodes
*
* @returns {number}
* @private
*/
exports._getSelectedNodeCount = function() {
var count = 0;
for (var nodeId in this.selectionObj.nodes) {
if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
count += 1;
}
}
return count;
};
/**
* return the selected node
*
* @returns {number}
* @private
*/
exports._getSelectedNode = function() {
for (var nodeId in this.selectionObj.nodes) {
if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
return this.selectionObj.nodes[nodeId];
}
}
return null;
};
/**
* return the selected edge
*
* @returns {number}
* @private
*/
exports._getSelectedEdge = function() {
for (var edgeId in this.selectionObj.edges) {
if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
return this.selectionObj.edges[edgeId];
}
}
return null;
};
/**
* return the number of selected edges
*
* @returns {number}
* @private
*/
exports._getSelectedEdgeCount = function() {
var count = 0;
for (var edgeId in this.selectionObj.edges) {
if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
count += 1;
}
}
return count;
};
/**
* return the number of selected objects.
*
* @returns {number}
* @private
*/
exports._getSelectedObjectCount = function() {
var count = 0;
for(var nodeId in this.selectionObj.nodes) {
if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
count += 1;
}
}
for(var edgeId in this.selectionObj.edges) {
if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
count += 1;
}
}
return count;
};
/**
* Check if anything is selected
*
* @returns {boolean}
* @private
*/
exports._selectionIsEmpty = function() {
for(var nodeId in this.selectionObj.nodes) {
if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
return false;
}
}
for(var edgeId in this.selectionObj.edges) {
if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
return false;
}
}
return true;
};
/**
* check if one of the selected nodes is a cluster.
*
* @returns {boolean}
* @private
*/
exports._clusterInSelection = function() {
for(var nodeId in this.selectionObj.nodes) {
if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
return true;
}
}
}
return false;
};
/**
* select the edges connected to the node that is being selected
*
* @param {Node} node
* @private
*/
exports._selectConnectedEdges = function(node) {
for (var i = 0; i < node.dynamicEdges.length; i++) {
var edge = node.dynamicEdges[i];
edge.select();
this._addToSelection(edge);
}
};
/**
* select the edges connected to the node that is being selected
*
* @param {Node} node
* @private
*/
exports._hoverConnectedEdges = function(node) {
for (var i = 0; i < node.dynamicEdges.length; i++) {
var edge = node.dynamicEdges[i];
edge.hover = true;
this._addToHover(edge);
}
};
/**
* unselect the edges connected to the node that is being selected
*
* @param {Node} node
* @private
*/
exports._unselectConnectedEdges = function(node) {
for (var i = 0; i < node.dynamicEdges.length; i++) {
var edge = node.dynamicEdges[i];
edge.unselect();
this._removeFromSelection(edge);
}
};
/**
* This is called when someone clicks on a node. either select or deselect it.
* If there is an existing selection and we don't want to append to it, clear the existing selection
*
* @param {Node || Edge} object
* @param {Boolean} append
* @param {Boolean} [doNotTrigger] | ignore trigger
* @private
*/
exports._selectObject = function(object, append, doNotTrigger, highlightEdges) {
if (doNotTrigger === undefined) {
doNotTrigger = false;
}
if (highlightEdges === undefined) {
highlightEdges = true;
}
if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) {
this._unselectAll(true);
}
if (object.selected == false) {
object.select();
this._addToSelection(object);
if (object instanceof Node && this.blockConnectingEdgeSelection == false && highlightEdges == true) {
this._selectConnectedEdges(object);
}
}
else {
object.unselect();
this._removeFromSelection(object);
}
if (doNotTrigger == false) {
this.emit('select', this.getSelection());
}
};
/**
* This is called when someone clicks on a node. either select or deselect it.
* If there is an existing selection and we don't want to append to it, clear the existing selection
*
* @param {Node || Edge} object
* @private
*/
exports._blurObject = function(object) {
if (object.hover == true) {
object.hover = false;
this.emit("blurNode",{node:object.id});
}
};
/**
* This is called when someone clicks on a node. either select or deselect it.
* If there is an existing selection and we don't want to append to it, clear the existing selection
*
* @param {Node || Edge} object
* @private
*/
exports._hoverObject = function(object) {
if (object.hover == false) {
object.hover = true;
this._addToHover(object);
if (object instanceof Node) {
this.emit("hoverNode",{node:object.id});
}
}
if (object instanceof Node) {
this._hoverConnectedEdges(object);
}
};
/**
* handles the selection part of the touch, only for navigation controls elements;
* Touch is triggered before tap, also before hold. Hold triggers after a while.
* This is the most responsive solution
*
* @param {Object} pointer
* @private
*/
exports._handleTouch = function(pointer) {
};
/**
* handles the selection part of the tap;
*
* @param {Object} pointer
* @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);
}
else {
this._unselectAll();
}
}
this.emit("click", this.getSelection());
this._redraw();
};
/**
* handles the selection part of the double tap and opens a cluster if needed
*
* @param {Object} pointer
* @private
*/
exports._handleDoubleTap = function(pointer) {
var node = this._getNodeAt(pointer);
if (node != null && node !== undefined) {
// we reset the areaCenter here so the opening of the node will occur
this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x),
"y" : this._YconvertDOMtoCanvas(pointer.y)};
this.openCluster(node);
}
this.emit("doubleClick", this.getSelection());
};
/**
* Handle the onHold selection part
*
* @param pointer
* @private
*/
exports._handleOnHold = function(pointer) {
var node = this._getNodeAt(pointer);
if (node != null) {
this._selectObject(node,true);
}
else {
var edge = this._getEdgeAt(pointer);
if (edge != null) {
this._selectObject(edge,true);
}
}
this._redraw();
};
/**
* handle the onRelease event. These functions are here for the navigation controls module.
*
* @private
*/
exports._handleOnRelease = function(pointer) {
};
/**
*
* retrieve the currently selected objects
* @return {{nodes: Array.<String>, edges: Array.<String>}} selection
*/
exports.getSelection = function() {
var nodeIds = this.getSelectedNodes();
var edgeIds = this.getSelectedEdges();
return {nodes:nodeIds, edges:edgeIds};
};
/**
*
* retrieve the currently selected nodes
* @return {String[]} selection An array with the ids of the
* selected nodes.
*/
exports.getSelectedNodes = function() {
var idArray = [];
for(var nodeId in this.selectionObj.nodes) {
if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
idArray.push(nodeId);
}
}
return idArray
};
/**
*
* retrieve the currently selected edges
* @return {Array} selection An array with the ids of the
* selected nodes.
*/
exports.getSelectedEdges = function() {
var idArray = [];
for(var edgeId in this.selectionObj.edges) {
if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
idArray.push(edgeId);
}
}
return idArray;
};
/**
* select zero or more nodes
* @param {Number[] | String[]} selection An array with the ids of the
* selected nodes.
*/
exports.setSelection = function(selection) {
var i, iMax, id;
if (!selection || (selection.length == undefined))
throw 'Selection must be an array with ids';
// first unselect any selected node
this._unselectAll(true);
for (i = 0, iMax = selection.length; i < iMax; i++) {
id = selection[i];
var node = this.nodes[id];
if (!node) {
throw new RangeError('Node with id "' + id + '" not found');
}
this._selectObject(node,true,true);
}
console.log("setSelection is deprecated. Please use selectNodes instead.")
this.redraw();
};
/**
* select zero or more nodes with the option to highlight edges
* @param {Number[] | String[]} selection An array with the ids of the
* selected nodes.
* @param {boolean} [highlightEdges]
*/
exports.selectNodes = function(selection, highlightEdges) {
var i, iMax, id;
if (!selection || (selection.length == undefined))
throw 'Selection must be an array with ids';
// first unselect any selected node
this._unselectAll(true);
for (i = 0, iMax = selection.length; i < iMax; i++) {
id = selection[i];
var node = this.nodes[id];
if (!node) {
throw new RangeError('Node with id "' + id + '" not found');
}
this._selectObject(node,true,true,highlightEdges);
}
this.redraw();
};
/**
* select zero or more edges
* @param {Number[] | String[]} selection An array with the ids of the
* selected nodes.
*/
exports.selectEdges = function(selection) {
var i, iMax, id;
if (!selection || (selection.length == undefined))
throw 'Selection must be an array with ids';
// first unselect any selected node
this._unselectAll(true);
for (i = 0, iMax = selection.length; i < iMax; i++) {
id = selection[i];
var edge = this.edges[id];
if (!edge) {
throw new RangeError('Edge with id "' + id + '" not found');
}
this._selectObject(edge,true,true,highlightEdges);
}
this.redraw();
};
/**
* Validate the selection: remove ids of nodes which no longer exist
* @private
*/
exports._updateSelection = function () {
for(var nodeId in this.selectionObj.nodes) {
if(this.selectionObj.nodes.hasOwnProperty(nodeId)) {
if (!this.nodes.hasOwnProperty(nodeId)) {
delete this.selectionObj.nodes[nodeId];
}
}
}
for(var edgeId in this.selectionObj.edges) {
if(this.selectionObj.edges.hasOwnProperty(edgeId)) {
if (!this.edges.hasOwnProperty(edgeId)) {
delete this.selectionObj.edges[edgeId];
}
}
}
};

+ 393
- 0
lib/network/mixins/physics/BarnesHutMixin.js View File

@ -0,0 +1,393 @@
/**
* This function calculates the forces the nodes apply on eachother based on a gravitational model.
* The Barnes Hut method is used to speed up this N-body simulation.
*
* @private
*/
exports._calculateNodeForces = function() {
if (this.constants.physics.barnesHut.gravitationalConstant != 0) {
var node;
var nodes = this.calculationNodes;
var nodeIndices = this.calculationNodeIndices;
var nodeCount = nodeIndices.length;
this._formBarnesHutTree(nodes,nodeIndices);
var barnesHutTree = this.barnesHutTree;
// place the nodes one by one recursively
for (var i = 0; i < nodeCount; i++) {
node = nodes[nodeIndices[i]];
// starting with root is irrelevant, it never passes the BarnesHut condition
this._getForceContribution(barnesHutTree.root.children.NW,node);
this._getForceContribution(barnesHutTree.root.children.NE,node);
this._getForceContribution(barnesHutTree.root.children.SW,node);
this._getForceContribution(barnesHutTree.root.children.SE,node);
}
}
};
/**
* This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
* If a region contains a single node, we check if it is not itself, then we apply the force.
*
* @param parentBranch
* @param node
* @private
*/
exports._getForceContribution = function(parentBranch,node) {
// we get no force contribution from an empty region
if (parentBranch.childrenCount > 0) {
var dx,dy,distance;
// get the distance from the center of mass to the node.
dx = parentBranch.centerOfMass.x - node.x;
dy = parentBranch.centerOfMass.y - node.y;
distance = Math.sqrt(dx * dx + dy * dy);
// BarnesHut condition
// original condition : s/d < theta = passed === d/s > 1/theta = passed
// calcSize = 1/s --> d * 1/s > 1/theta = passed
if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) {
// duplicate code to reduce function calls to speed up program
if (distance == 0) {
distance = 0.1*Math.random();
dx = distance;
}
var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
var fx = dx * gravityForce;
var fy = dy * gravityForce;
node.fx += fx;
node.fy += fy;
}
else {
// Did not pass the condition, go into children if available
if (parentBranch.childrenCount == 4) {
this._getForceContribution(parentBranch.children.NW,node);
this._getForceContribution(parentBranch.children.NE,node);
this._getForceContribution(parentBranch.children.SW,node);
this._getForceContribution(parentBranch.children.SE,node);
}
else { // parentBranch must have only one node, if it was empty we wouldnt be here
if (parentBranch.children.data.id != node.id) { // if it is not self
// duplicate code to reduce function calls to speed up program
if (distance == 0) {
distance = 0.5*Math.random();
dx = distance;
}
var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance);
var fx = dx * gravityForce;
var fy = dy * gravityForce;
node.fx += fx;
node.fy += fy;
}
}
}
}
};
/**
* This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
*
* @param nodes
* @param nodeIndices
* @private
*/
exports._formBarnesHutTree = function(nodes,nodeIndices) {
var node;
var nodeCount = nodeIndices.length;
var minX = Number.MAX_VALUE,
minY = Number.MAX_VALUE,
maxX =-Number.MAX_VALUE,
maxY =-Number.MAX_VALUE;
// get the range of the nodes
for (var i = 0; i < nodeCount; i++) {
var x = nodes[nodeIndices[i]].x;
var y = nodes[nodeIndices[i]].y;
if (x < minX) { minX = x; }
if (x > maxX) { maxX = x; }
if (y < minY) { minY = y; }
if (y > maxY) { maxY = y; }
}
// make the range a square
var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize
else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize
var minimumTreeSize = 1e-5;
var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX));
var halfRootSize = 0.5 * rootSize;
var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY);
// construct the barnesHutTree
var barnesHutTree = {
root:{
centerOfMass: {x:0, y:0},
mass:0,
range: {
minX: centerX-halfRootSize,maxX:centerX+halfRootSize,
minY: centerY-halfRootSize,maxY:centerY+halfRootSize
},
size: rootSize,
calcSize: 1 / rootSize,
children: { data:null},
maxWidth: 0,
level: 0,
childrenCount: 4
}
};
this._splitBranch(barnesHutTree.root);
// place the nodes one by one recursively
for (i = 0; i < nodeCount; i++) {
node = nodes[nodeIndices[i]];
this._placeInTree(barnesHutTree.root,node);
}
// make global
this.barnesHutTree = barnesHutTree
};
/**
* this updates the mass of a branch. this is increased by adding a node.
*
* @param parentBranch
* @param node
* @private
*/
exports._updateBranchMass = function(parentBranch, node) {
var totalMass = parentBranch.mass + node.mass;
var totalMassInv = 1/totalMass;
parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass;
parentBranch.centerOfMass.x *= totalMassInv;
parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass;
parentBranch.centerOfMass.y *= totalMassInv;
parentBranch.mass = totalMass;
var biggestSize = Math.max(Math.max(node.height,node.radius),node.width);
parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth;
};
/**
* determine in which branch the node will be placed.
*
* @param parentBranch
* @param node
* @param skipMassUpdate
* @private
*/
exports._placeInTree = function(parentBranch,node,skipMassUpdate) {
if (skipMassUpdate != true || skipMassUpdate === undefined) {
// update the mass of the branch.
this._updateBranchMass(parentBranch,node);
}
if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW
if (parentBranch.children.NW.range.maxY > node.y) { // in NW
this._placeInRegion(parentBranch,node,"NW");
}
else { // in SW
this._placeInRegion(parentBranch,node,"SW");
}
}
else { // in NE or SE
if (parentBranch.children.NW.range.maxY > node.y) { // in NE
this._placeInRegion(parentBranch,node,"NE");
}
else { // in SE
this._placeInRegion(parentBranch,node,"SE");
}
}
};
/**
* actually place the node in a region (or branch)
*
* @param parentBranch
* @param node
* @param region
* @private
*/
exports._placeInRegion = function(parentBranch,node,region) {
switch (parentBranch.children[region].childrenCount) {
case 0: // place node here
parentBranch.children[region].children.data = node;
parentBranch.children[region].childrenCount = 1;
this._updateBranchMass(parentBranch.children[region],node);
break;
case 1: // convert into children
// if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
// we move one node a pixel and we do not put it in the tree.
if (parentBranch.children[region].children.data.x == node.x &&
parentBranch.children[region].children.data.y == node.y) {
node.x += Math.random();
node.y += Math.random();
}
else {
this._splitBranch(parentBranch.children[region]);
this._placeInTree(parentBranch.children[region],node);
}
break;
case 4: // place in branch
this._placeInTree(parentBranch.children[region],node);
break;
}
};
/**
* this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
* after the split is complete.
*
* @param parentBranch
* @private
*/
exports._splitBranch = function(parentBranch) {
// if the branch is shaded with a node, replace the node in the new subset.
var containedNode = null;
if (parentBranch.childrenCount == 1) {
containedNode = parentBranch.children.data;
parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0;
}
parentBranch.childrenCount = 4;
parentBranch.children.data = null;
this._insertRegion(parentBranch,"NW");
this._insertRegion(parentBranch,"NE");
this._insertRegion(parentBranch,"SW");
this._insertRegion(parentBranch,"SE");
if (containedNode != null) {
this._placeInTree(parentBranch,containedNode);
}
};
/**
* This function subdivides the region into four new segments.
* Specifically, this inserts a single new segment.
* It fills the children section of the parentBranch
*
* @param parentBranch
* @param region
* @param parentRange
* @private
*/
exports._insertRegion = function(parentBranch, region) {
var minX,maxX,minY,maxY;
var childSize = 0.5 * parentBranch.size;
switch (region) {
case "NW":
minX = parentBranch.range.minX;
maxX = parentBranch.range.minX + childSize;
minY = parentBranch.range.minY;
maxY = parentBranch.range.minY + childSize;
break;
case "NE":
minX = parentBranch.range.minX + childSize;
maxX = parentBranch.range.maxX;
minY = parentBranch.range.minY;
maxY = parentBranch.range.minY + childSize;
break;
case "SW":
minX = parentBranch.range.minX;
maxX = parentBranch.range.minX + childSize;
minY = parentBranch.range.minY + childSize;
maxY = parentBranch.range.maxY;
break;
case "SE":
minX = parentBranch.range.minX + childSize;
maxX = parentBranch.range.maxX;
minY = parentBranch.range.minY + childSize;
maxY = parentBranch.range.maxY;
break;
}
parentBranch.children[region] = {
centerOfMass:{x:0,y:0},
mass:0,
range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},
size: 0.5 * parentBranch.size,
calcSize: 2 * parentBranch.calcSize,
children: {data:null},
maxWidth: 0,
level: parentBranch.level+1,
childrenCount: 0
};
};
/**
* This function is for debugging purposed, it draws the tree.
*
* @param ctx
* @param color
* @private
*/
exports._drawTree = function(ctx,color) {
if (this.barnesHutTree !== undefined) {
ctx.lineWidth = 1;
this._drawBranch(this.barnesHutTree.root,ctx,color);
}
};
/**
* This function is for debugging purposes. It draws the branches recursively.
*
* @param branch
* @param ctx
* @param color
* @private
*/
exports._drawBranch = function(branch,ctx,color) {
if (color === undefined) {
color = "#FF0000";
}
if (branch.childrenCount == 4) {
this._drawBranch(branch.children.NW,ctx);
this._drawBranch(branch.children.NE,ctx);
this._drawBranch(branch.children.SE,ctx);
this._drawBranch(branch.children.SW,ctx);
}
ctx.strokeStyle = color;
ctx.beginPath();
ctx.moveTo(branch.range.minX,branch.range.minY);
ctx.lineTo(branch.range.maxX,branch.range.minY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(branch.range.maxX,branch.range.minY);
ctx.lineTo(branch.range.maxX,branch.range.maxY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(branch.range.maxX,branch.range.maxY);
ctx.lineTo(branch.range.minX,branch.range.maxY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(branch.range.minX,branch.range.maxY);
ctx.lineTo(branch.range.minX,branch.range.minY);
ctx.stroke();
/*
if (branch.mass > 0) {
ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
ctx.stroke();
}
*/
};

+ 154
- 0
lib/network/mixins/physics/HierarchialRepulsionMixin.js View File

@ -0,0 +1,154 @@
/**
* Calculate the forces the nodes apply on eachother based on a repulsion field.
* This field is linearly approximated.
*
* @private
*/
exports._calculateNodeForces = function () {
var dx, dy, distance, fx, fy,
repulsingForce, node1, node2, i, j;
var nodes = this.calculationNodes;
var nodeIndices = this.calculationNodeIndices;
// repulsing forces between nodes
var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance;
// we loop from i over all but the last entree in the array
// j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
for (i = 0; i < nodeIndices.length - 1; i++) {
node1 = nodes[nodeIndices[i]];
for (j = i + 1; j < nodeIndices.length; j++) {
node2 = nodes[nodeIndices[j]];
// nodes only affect nodes on their level
if (node1.level == node2.level) {
dx = node2.x - node1.x;
dy = node2.y - node1.y;
distance = Math.sqrt(dx * dx + dy * dy);
var steepness = 0.05;
if (distance < nodeDistance) {
repulsingForce = -Math.pow(steepness*distance,2) + Math.pow(steepness*nodeDistance,2);
}
else {
repulsingForce = 0;
}
// normalize force with
if (distance == 0) {
distance = 0.01;
}
else {
repulsingForce = repulsingForce / distance;
}
fx = dx * repulsingForce;
fy = dy * repulsingForce;
node1.fx -= fx;
node1.fy -= fy;
node2.fx += fx;
node2.fy += fy;
}
}
}
};
/**
* this function calculates the effects of the springs in the case of unsmooth curves.
*
* @private
*/
exports._calculateHierarchicalSpringForces = function () {
var edgeLength, edge, edgeId;
var dx, dy, fx, fy, springForce, distance;
var edges = this.edges;
var nodes = this.calculationNodes;
var nodeIndices = this.calculationNodeIndices;
for (var i = 0; i < nodeIndices.length; i++) {
var node1 = nodes[nodeIndices[i]];
node1.springFx = 0;
node1.springFy = 0;
}
// forces caused by the edges, modelled as springs
for (edgeId in edges) {
if (edges.hasOwnProperty(edgeId)) {
edge = edges[edgeId];
if (edge.connected) {
// only calculate forces if nodes are in the same sector
if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
// this implies that the edges between big clusters are longer
edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
dx = (edge.from.x - edge.to.x);
dy = (edge.from.y - edge.to.y);
distance = Math.sqrt(dx * dx + dy * dy);
if (distance == 0) {
distance = 0.01;
}
// the 1/distance is so the fx and fy can be calculated without sine or cosine.
springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
fx = dx * springForce;
fy = dy * springForce;
if (edge.to.level != edge.from.level) {
edge.to.springFx -= fx;
edge.to.springFy -= fy;
edge.from.springFx += fx;
edge.from.springFy += fy;
}
else {
var factor = 0.5;
edge.to.fx -= factor*fx;
edge.to.fy -= factor*fy;
edge.from.fx += factor*fx;
edge.from.fy += factor*fy;
}
}
}
}
}
// normalize spring forces
var springForce = 1;
var springFx, springFy;
for (i = 0; i < nodeIndices.length; i++) {
var node = nodes[nodeIndices[i]];
springFx = Math.min(springForce,Math.max(-springForce,node.springFx));
springFy = Math.min(springForce,Math.max(-springForce,node.springFy));
node.fx += springFx;
node.fy += springFy;
}
// retain energy balance
var totalFx = 0;
var totalFy = 0;
for (i = 0; i < nodeIndices.length; i++) {
var node = nodes[nodeIndices[i]];
totalFx += node.fx;
totalFy += node.fy;
}
var correctionFx = totalFx / nodeIndices.length;
var correctionFy = totalFy / nodeIndices.length;
for (i = 0; i < nodeIndices.length; i++) {
var node = nodes[nodeIndices[i]];
node.fx -= correctionFx;
node.fy -= correctionFy;
}
};

+ 708
- 0
lib/network/mixins/physics/PhysicsMixin.js View File

@ -0,0 +1,708 @@
var util = require('../../../util');
var RepulsionMixin = require('./RepulsionMixin');
var HierarchialRepulsionMixin = require('./HierarchialRepulsionMixin');
var BarnesHutMixin = require('./BarnesHutMixin');
/**
* Toggling barnes Hut calculation on and off.
*
* @private
*/
exports._toggleBarnesHut = function () {
this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled;
this._loadSelectedForceSolver();
this.moving = true;
this.start();
};
/**
* This loads the node force solver based on the barnes hut or repulsion algorithm
*
* @private
*/
exports._loadSelectedForceSolver = function () {
// this overloads the this._calculateNodeForces
if (this.constants.physics.barnesHut.enabled == true) {
this._clearMixin(RepulsionMixin);
this._clearMixin(HierarchialRepulsionMixin);
this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity;
this.constants.physics.springLength = this.constants.physics.barnesHut.springLength;
this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant;
this.constants.physics.damping = this.constants.physics.barnesHut.damping;
this._loadMixin(BarnesHutMixin);
}
else if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
this._clearMixin(BarnesHutMixin);
this._clearMixin(RepulsionMixin);
this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity;
this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength;
this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant;
this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping;
this._loadMixin(HierarchialRepulsionMixin);
}
else {
this._clearMixin(BarnesHutMixin);
this._clearMixin(HierarchialRepulsionMixin);
this.barnesHutTree = undefined;
this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity;
this.constants.physics.springLength = this.constants.physics.repulsion.springLength;
this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant;
this.constants.physics.damping = this.constants.physics.repulsion.damping;
this._loadMixin(RepulsionMixin);
}
};
/**
* Before calculating the forces, we check if we need to cluster to keep up performance and we check
* if there is more than one node. If it is just one node, we dont calculate anything.
*
* @private
*/
exports._initializeForceCalculation = function () {
// stop calculation if there is only one node
if (this.nodeIndices.length == 1) {
this.nodes[this.nodeIndices[0]]._setForce(0, 0);
}
else {
// if there are too many nodes on screen, we cluster without repositioning
if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) {
this.clusterToFit(this.constants.clustering.reduceToNodes, false);
}
// we now start the force calculation
this._calculateForces();
}
};
/**
* Calculate the external forces acting on the nodes
* Forces are caused by: edges, repulsing forces between nodes, gravity
* @private
*/
exports._calculateForces = function () {
// Gravity is required to keep separated groups from floating off
// the forces are reset to zero in this loop by using _setForce instead
// of _addForce
this._calculateGravitationalForces();
this._calculateNodeForces();
if (this.constants.physics.springConstant > 0) {
if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
this._calculateSpringForcesWithSupport();
}
else {
if (this.constants.physics.hierarchicalRepulsion.enabled == true) {
this._calculateHierarchicalSpringForces();
}
else {
this._calculateSpringForces();
}
}
}
};
/**
* Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
* handled in the calculateForces function. We then use a quadratic curve with the center node as control.
* This function joins the datanodes and invisible (called support) nodes into one object.
* We do this so we do not contaminate this.nodes with the support nodes.
*
* @private
*/
exports._updateCalculationNodes = function () {
if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) {
this.calculationNodes = {};
this.calculationNodeIndices = [];
for (var nodeId in this.nodes) {
if (this.nodes.hasOwnProperty(nodeId)) {
this.calculationNodes[nodeId] = this.nodes[nodeId];
}
}
var supportNodes = this.sectors['support']['nodes'];
for (var supportNodeId in supportNodes) {
if (supportNodes.hasOwnProperty(supportNodeId)) {
if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) {
this.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
}
else {
supportNodes[supportNodeId]._setForce(0, 0);
}
}
}
for (var idx in this.calculationNodes) {
if (this.calculationNodes.hasOwnProperty(idx)) {
this.calculationNodeIndices.push(idx);
}
}
}
else {
this.calculationNodes = this.nodes;
this.calculationNodeIndices = this.nodeIndices;
}
};
/**
* this function applies the central gravity effect to keep groups from floating off
*
* @private
*/
exports._calculateGravitationalForces = function () {
var dx, dy, distance, node, i;
var nodes = this.calculationNodes;
var gravity = this.constants.physics.centralGravity;
var gravityForce = 0;
for (i = 0; i < this.calculationNodeIndices.length; i++) {
node = nodes[this.calculationNodeIndices[i]];
node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters.
// gravity does not apply when we are in a pocket sector
if (this._sector() == "default" && gravity != 0) {
dx = -node.x;
dy = -node.y;
distance = Math.sqrt(dx * dx + dy * dy);
gravityForce = (distance == 0) ? 0 : (gravity / distance);
node.fx = dx * gravityForce;
node.fy = dy * gravityForce;
}
else {
node.fx = 0;
node.fy = 0;
}
}
};
/**
* this function calculates the effects of the springs in the case of unsmooth curves.
*
* @private
*/
exports._calculateSpringForces = function () {
var edgeLength, edge, edgeId;
var dx, dy, fx, fy, springForce, distance;
var edges = this.edges;
// forces caused by the edges, modelled as springs
for (edgeId in edges) {
if (edges.hasOwnProperty(edgeId)) {
edge = edges[edgeId];
if (edge.connected) {
// only calculate forces if nodes are in the same sector
if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
// this implies that the edges between big clusters are longer
edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth;
dx = (edge.from.x - edge.to.x);
dy = (edge.from.y - edge.to.y);
distance = Math.sqrt(dx * dx + dy * dy);
if (distance == 0) {
distance = 0.01;
}
// the 1/distance is so the fx and fy can be calculated without sine or cosine.
springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
fx = dx * springForce;
fy = dy * springForce;
edge.from.fx += fx;
edge.from.fy += fy;
edge.to.fx -= fx;
edge.to.fy -= fy;
}
}
}
}
};
/**
* This function calculates the springforces on the nodes, accounting for the support nodes.
*
* @private
*/
exports._calculateSpringForcesWithSupport = function () {
var edgeLength, edge, edgeId, combinedClusterSize;
var edges = this.edges;
// forces caused by the edges, modelled as springs
for (edgeId in edges) {
if (edges.hasOwnProperty(edgeId)) {
edge = edges[edgeId];
if (edge.connected) {
// only calculate forces if nodes are in the same sector
if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) {
if (edge.via != null) {
var node1 = edge.to;
var node2 = edge.via;
var node3 = edge.from;
edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength;
combinedClusterSize = node1.clusterSize + node3.clusterSize - 2;
// this implies that the edges between big clusters are longer
edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth;
this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
}
}
}
}
}
};
/**
* This is the code actually performing the calculation for the function above. It is split out to avoid repetition.
*
* @param node1
* @param node2
* @param edgeLength
* @private
*/
exports._calculateSpringForce = function (node1, node2, edgeLength) {
var dx, dy, fx, fy, springForce, distance;
dx = (node1.x - node2.x);
dy = (node1.y - node2.y);
distance = Math.sqrt(dx * dx + dy * dy);
if (distance == 0) {
distance = 0.01;
}
// the 1/distance is so the fx and fy can be calculated without sine or cosine.
springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance;
fx = dx * springForce;
fy = dy * springForce;
node1.fx += fx;
node1.fy += fy;
node2.fx -= fx;
node2.fy -= fy;
};
/**
* Load the HTML for the physics config and bind it
* @private
*/
exports._loadPhysicsConfiguration = function () {
if (this.physicsConfiguration === undefined) {
this.backupConstants = {};
util.deepExtend(this.backupConstants,this.constants);
var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"];
this.physicsConfiguration = document.createElement('div');
this.physicsConfiguration.className = "PhysicsConfiguration";
this.physicsConfiguration.innerHTML = '' +
'<table><tr><td><b>Simulation Mode:</b></td></tr>' +
'<tr>' +
'<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' +
'<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' +
'<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' +
'</tr>' +
'</table>' +
'<table id="graph_BH_table" style="display:none">' +
'<tr><td><b>Barnes Hut</b></td></tr>' +
'<tr>' +
'<td width="150px">gravitationalConstant</td><td>0</td><td><input type="range" min="0" max="20000" value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" step="25" style="width:300px" id="graph_BH_gc"></td><td width="50px">-20000</td><td><input value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" id="graph_BH_gc_value" style="width:60px"></td>' +
'</tr>' +
'<tr>' +
'<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.barnesHut.centralGravity + '" step="0.05" style="width:300px" id="graph_BH_cg"></td><td>3</td><td><input value="' + this.constants.physics.barnesHut.centralGravity + '" id="graph_BH_cg_value" style="width:60px"></td>' +
'</tr>' +
'<tr>' +
'<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.barnesHut.springLength + '" step="1" style="width:300px" id="graph_BH_sl"></td><td>500</td><td><input value="' + this.constants.physics.barnesHut.springLength + '" id="graph_BH_sl_value" style="width:60px"></td>' +
'</tr>' +
'<tr>' +
'<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.barnesHut.springConstant + '" step="0.001" style="width:300px" id="graph_BH_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.barnesHut.springConstant + '" id="graph_BH_sc_value" style="width:60px"></td>' +
'</tr>' +
'<tr>' +
'<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.barnesHut.damping + '" step="0.005" style="width:300px" id="graph_BH_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.barnesHut.damping + '" id="graph_BH_damp_value" style="width:60px"></td>' +
'</tr>' +
'</table>' +
'<table id="graph_R_table" style="display:none">' +
'<tr><td><b>Repulsion</b></td></tr>' +
'<tr>' +
'<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.repulsion.nodeDistance + '" step="1" style="width:300px" id="graph_R_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.repulsion.nodeDistance + '" id="graph_R_nd_value" style="width:60px"></td>' +
'</tr>' +
'<tr>' +
'<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.repulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_R_cg"></td><td>3</td><td><input value="' + this.constants.physics.repulsion.centralGravity + '" id="graph_R_cg_value" style="width:60px"></td>' +
'</tr>' +
'<tr>' +
'<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.repulsion.springLength + '" step="1" style="width:300px" id="graph_R_sl"></td><td>500</td><td><input value="' + this.constants.physics.repulsion.springLength + '" id="graph_R_sl_value" style="width:60px"></td>' +
'</tr>' +
'<tr>' +
'<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.repulsion.springConstant + '" step="0.001" style="width:300px" id="graph_R_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.repulsion.springConstant + '" id="graph_R_sc_value" style="width:60px"></td>' +
'</tr>' +
'<tr>' +
'<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.repulsion.damping + '" step="0.005" style="width:300px" id="graph_R_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.repulsion.damping + '" id="graph_R_damp_value" style="width:60px"></td>' +
'</tr>' +
'</table>' +
'<table id="graph_H_table" style="display:none">' +
'<tr><td width="150"><b>Hierarchical</b></td></tr>' +
'<tr>' +
'<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" step="1" style="width:300px" id="graph_H_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" id="graph_H_nd_value" style="width:60px"></td>' +
'</tr>' +
'<tr>' +
'<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_H_cg"></td><td>3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" id="graph_H_cg_value" style="width:60px"></td>' +
'</tr>' +
'<tr>' +
'<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" step="1" style="width:300px" id="graph_H_sl"></td><td>500</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" id="graph_H_sl_value" style="width:60px"></td>' +
'</tr>' +
'<tr>' +
'<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" step="0.001" style="width:300px" id="graph_H_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" id="graph_H_sc_value" style="width:60px"></td>' +
'</tr>' +
'<tr>' +
'<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.hierarchicalRepulsion.damping + '" step="0.005" style="width:300px" id="graph_H_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.damping + '" id="graph_H_damp_value" style="width:60px"></td>' +
'</tr>' +
'<tr>' +
'<td width="150px">direction</td><td>1</td><td><input type="range" min="0" max="3" value="' + hierarchicalLayoutDirections.indexOf(this.constants.hierarchicalLayout.direction) + '" step="1" style="width:300px" id="graph_H_direction"></td><td>4</td><td><input value="' + this.constants.hierarchicalLayout.direction + '" id="graph_H_direction_value" style="width:60px"></td>' +
'</tr>' +
'<tr>' +
'<td width="150px">levelSeparation</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.levelSeparation + '" step="1" style="width:300px" id="graph_H_levsep"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.levelSeparation + '" id="graph_H_levsep_value" style="width:60px"></td>' +
'</tr>' +
'<tr>' +
'<td width="150px">nodeSpacing</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.nodeSpacing + '" step="1" style="width:300px" id="graph_H_nspac"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.nodeSpacing + '" id="graph_H_nspac_value" style="width:60px"></td>' +
'</tr>' +
'</table>' +
'<table><tr><td><b>Options:</b></td></tr>' +
'<tr>' +
'<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' +
'<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' +
'<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' +
'</tr>' +
'</table>'
this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement);
this.optionsDiv = document.createElement("div");
this.optionsDiv.style.fontSize = "14px";
this.optionsDiv.style.fontFamily = "verdana";
this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement);
var rangeElement;
rangeElement = document.getElementById('graph_BH_gc');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant");
rangeElement = document.getElementById('graph_BH_cg');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity");
rangeElement = document.getElementById('graph_BH_sc');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant");
rangeElement = document.getElementById('graph_BH_sl');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength");
rangeElement = document.getElementById('graph_BH_damp');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping");
rangeElement = document.getElementById('graph_R_nd');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance");
rangeElement = document.getElementById('graph_R_cg');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity");
rangeElement = document.getElementById('graph_R_sc');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant");
rangeElement = document.getElementById('graph_R_sl');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength");
rangeElement = document.getElementById('graph_R_damp');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping");
rangeElement = document.getElementById('graph_H_nd');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
rangeElement = document.getElementById('graph_H_cg');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity");
rangeElement = document.getElementById('graph_H_sc');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant");
rangeElement = document.getElementById('graph_H_sl');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength");
rangeElement = document.getElementById('graph_H_damp');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping");
rangeElement = document.getElementById('graph_H_direction');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction");
rangeElement = document.getElementById('graph_H_levsep');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation");
rangeElement = document.getElementById('graph_H_nspac');
rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing");
var radioButton1 = document.getElementById("graph_physicsMethod1");
var radioButton2 = document.getElementById("graph_physicsMethod2");
var radioButton3 = document.getElementById("graph_physicsMethod3");
radioButton2.checked = true;
if (this.constants.physics.barnesHut.enabled) {
radioButton1.checked = true;
}
if (this.constants.hierarchicalLayout.enabled) {
radioButton3.checked = true;
}
var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
var graph_repositionNodes = document.getElementById("graph_repositionNodes");
var graph_generateOptions = document.getElementById("graph_generateOptions");
graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this);
graph_repositionNodes.onclick = graphRepositionNodes.bind(this);
graph_generateOptions.onclick = graphGenerateOptions.bind(this);
if (this.constants.smoothCurves == true && this.constants.dynamicSmoothCurves == false) {
graph_toggleSmooth.style.background = "#A4FF56";
}
else {
graph_toggleSmooth.style.background = "#FF8532";
}
switchConfigurations.apply(this);
radioButton1.onchange = switchConfigurations.bind(this);
radioButton2.onchange = switchConfigurations.bind(this);
radioButton3.onchange = switchConfigurations.bind(this);
}
};
/**
* This overwrites the this.constants.
*
* @param constantsVariableName
* @param value
* @private
*/
exports._overWriteGraphConstants = function (constantsVariableName, value) {
var nameArray = constantsVariableName.split("_");
if (nameArray.length == 1) {
this.constants[nameArray[0]] = value;
}
else if (nameArray.length == 2) {
this.constants[nameArray[0]][nameArray[1]] = value;
}
else if (nameArray.length == 3) {
this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value;
}
};
/**
* this function is bound to the toggle smooth curves button. That is also why it is not in the prototype.
*/
function graphToggleSmoothCurves () {
this.constants.smoothCurves.enabled = !this.constants.smoothCurves.enabled;
var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";}
else {graph_toggleSmooth.style.background = "#FF8532";}
this._configureSmoothCurves(false);
}
/**
* this function is used to scramble the nodes
*
*/
function graphRepositionNodes () {
for (var nodeId in this.calculationNodes) {
if (this.calculationNodes.hasOwnProperty(nodeId)) {
this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0;
this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0;
}
}
if (this.constants.hierarchicalLayout.enabled == true) {
this._setupHierarchicalLayout();
showValueOfRange.call(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance");
showValueOfRange.call(this, 'graph_H_cg', 1, "physics_centralGravity");
showValueOfRange.call(this, 'graph_H_sc', 1, "physics_springConstant");
showValueOfRange.call(this, 'graph_H_sl', 1, "physics_springLength");
showValueOfRange.call(this, 'graph_H_damp', 1, "physics_damping");
}
else {
this.repositionNodes();
}
this.moving = true;
this.start();
}
/**
* this is used to generate an options file from the playing with physics system.
*/
function graphGenerateOptions () {
var options = "No options are required, default values used.";
var optionsSpecific = [];
var radioButton1 = document.getElementById("graph_physicsMethod1");
var radioButton2 = document.getElementById("graph_physicsMethod2");
if (radioButton1.checked == true) {
if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);}
if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
if (optionsSpecific.length != 0) {
options = "var options = {";
options += "physics: {barnesHut: {";
for (var i = 0; i < optionsSpecific.length; i++) {
options += optionsSpecific[i];
if (i < optionsSpecific.length - 1) {
options += ", "
}
}
options += '}}'
}
if (this.constants.smoothCurves.enabled != this.backupConstants.smoothCurves.enabled) {
if (optionsSpecific.length == 0) {options = "var options = {";}
else {options += ", "}
options += "smoothCurves: " + this.constants.smoothCurves.enabled;
}
if (options != "No options are required, default values used.") {
options += '};'
}
}
else if (radioButton2.checked == true) {
options = "var options = {";
options += "physics: {barnesHut: {enabled: false}";
if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);}
if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
if (optionsSpecific.length != 0) {
options += ", repulsion: {";
for (var i = 0; i < optionsSpecific.length; i++) {
options += optionsSpecific[i];
if (i < optionsSpecific.length - 1) {
options += ", "
}
}
options += '}}'
}
if (optionsSpecific.length == 0) {options += "}"}
if (this.constants.smoothCurves != this.backupConstants.smoothCurves) {
options += ", smoothCurves: " + this.constants.smoothCurves;
}
options += '};'
}
else {
options = "var options = {";
if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);}
if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);}
if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);}
if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);}
if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);}
if (optionsSpecific.length != 0) {
options += "physics: {hierarchicalRepulsion: {";
for (var i = 0; i < optionsSpecific.length; i++) {
options += optionsSpecific[i];
if (i < optionsSpecific.length - 1) {
options += ", ";
}
}
options += '}},';
}
options += 'hierarchicalLayout: {';
optionsSpecific = [];
if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);}
if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);}
if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);}
if (optionsSpecific.length != 0) {
for (var i = 0; i < optionsSpecific.length; i++) {
options += optionsSpecific[i];
if (i < optionsSpecific.length - 1) {
options += ", "
}
}
options += '}'
}
else {
options += "enabled:true}";
}
options += '};'
}
this.optionsDiv.innerHTML = options;
}
/**
* this is used to switch between barnesHut, repulsion and hierarchical.
*
*/
function switchConfigurations () {
var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"];
var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value;
var tableId = "graph_" + radioButton + "_table";
var table = document.getElementById(tableId);
table.style.display = "block";
for (var i = 0; i < ids.length; i++) {
if (ids[i] != tableId) {
table = document.getElementById(ids[i]);
table.style.display = "none";
}
}
this._restoreNodes();
if (radioButton == "R") {
this.constants.hierarchicalLayout.enabled = false;
this.constants.physics.hierarchicalRepulsion.enabled = false;
this.constants.physics.barnesHut.enabled = false;
}
else if (radioButton == "H") {
if (this.constants.hierarchicalLayout.enabled == false) {
this.constants.hierarchicalLayout.enabled = true;
this.constants.physics.hierarchicalRepulsion.enabled = true;
this.constants.physics.barnesHut.enabled = false;
this.constants.smoothCurves.enabled = false;
this._setupHierarchicalLayout();
}
}
else {
this.constants.hierarchicalLayout.enabled = false;
this.constants.physics.hierarchicalRepulsion.enabled = false;
this.constants.physics.barnesHut.enabled = true;
}
this._loadSelectedForceSolver();
var graph_toggleSmooth = document.getElementById("graph_toggleSmooth");
if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";}
else {graph_toggleSmooth.style.background = "#FF8532";}
this.moving = true;
this.start();
}
/**
* this generates the ranges depending on the iniital values.
*
* @param id
* @param map
* @param constantsVariableName
*/
function showValueOfRange (id,map,constantsVariableName) {
var valueId = id + "_value";
var rangeValue = document.getElementById(id).value;
if (map instanceof Array) {
document.getElementById(valueId).value = map[parseInt(rangeValue)];
this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]);
}
else {
document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue);
this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue));
}
if (constantsVariableName == "hierarchicalLayout_direction" ||
constantsVariableName == "hierarchicalLayout_levelSeparation" ||
constantsVariableName == "hierarchicalLayout_nodeSpacing") {
this._setupHierarchicalLayout();
}
this.moving = true;
this.start();
}

+ 58
- 0
lib/network/mixins/physics/RepulsionMixin.js View File

@ -0,0 +1,58 @@
/**
* Calculate the forces the nodes apply on each other based on a repulsion field.
* This field is linearly approximated.
*
* @private
*/
exports._calculateNodeForces = function () {
var dx, dy, angle, distance, fx, fy, combinedClusterSize,
repulsingForce, node1, node2, i, j;
var nodes = this.calculationNodes;
var nodeIndices = this.calculationNodeIndices;
// approximation constants
var a_base = -2 / 3;
var b = 4 / 3;
// repulsing forces between nodes
var nodeDistance = this.constants.physics.repulsion.nodeDistance;
var minimumDistance = nodeDistance;
// we loop from i over all but the last entree in the array
// j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
for (i = 0; i < nodeIndices.length - 1; i++) {
node1 = nodes[nodeIndices[i]];
for (j = i + 1; j < nodeIndices.length; j++) {
node2 = nodes[nodeIndices[j]];
combinedClusterSize = node1.clusterSize + node2.clusterSize - 2;
dx = node2.x - node1.x;
dy = node2.y - node1.y;
distance = Math.sqrt(dx * dx + dy * dy);
minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification));
var a = a_base / minimumDistance;
if (distance < 2 * minimumDistance) {
if (distance < 0.5 * minimumDistance) {
repulsingForce = 1.0;
}
else {
repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness))
}
// amplify the repulsion for clusters.
repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification;
repulsingForce = repulsingForce / distance;
fx = dx * repulsingForce;
fy = dy * repulsingForce;
node1.fx -= fx;
node1.fy -= fy;
node2.fx += fx;
node2.fy += fy;
}
}
}
};

src/network/shapes.js → lib/network/shapes.js View File


src/timeline/DataStep.js → lib/timeline/DataStep.js View File

@ -58,6 +58,11 @@ DataStep.prototype.setRange = function(start, end, minimumStep, containerHeight,
this._start = start;
this._end = end;
if (start == end) {
this._start = start - 0.75;
this._end = end + 1;
}
if (this.autoScale) {
this.setMinimumStep(minimumStep, containerHeight, forcedStepSize);
}
@ -172,7 +177,7 @@ DataStep.prototype.previous = function() {
/**
* Get the current datetime
* @return {Number} current The current date
* @return {String} current The current date
*/
DataStep.prototype.getCurrent = function() {
var toPrecision = '' + Number(this.current).toPrecision(5);
@ -189,7 +194,6 @@ DataStep.prototype.getCurrent = function() {
}
}
return toPrecision;
};
@ -213,3 +217,5 @@ DataStep.prototype.snap = function(date) {
DataStep.prototype.isMajor = function() {
return (this.current % (this.scale * this.majorSteps[this.stepIndex]) == 0);
};
module.exports = DataStep;

src/timeline/Graph2d.js → lib/timeline/Graph2d.js View File

@ -1,3 +1,14 @@
var Emitter = require('emitter-component');
var Hammer = require('../module/hammer');
var util = require('../util');
var DataSet = require('../DataSet');
var DataView = require('../DataView');
var Range = require('./Range');
var TimeAxis = require('./component/TimeAxis');
var CurrentTime = require('./component/CurrentTime');
var CustomTime = require('./component/CustomTime');
var LineGraph = require('./component/LineGraph');
/**
* Create a timeline visualization
* @param {HTMLElement} container
@ -868,3 +879,5 @@ Graph2d.prototype._updateScrollTop = function () {
Graph2d.prototype._getScrollTop = function () {
return this.props.scrollTop;
};
module.exports = Graph2d;

src/timeline/Range.js → lib/timeline/Range.js View File

@ -1,3 +1,8 @@
var util = require('../util');
var hammerUtil = require('../hammerUtil');
var moment = require('../module/moment');
var Component = require('./component/Component');
/**
* @constructor Range
* A Range controls a numeric range with a start and end value.
@ -370,7 +375,7 @@ Range.prototype._onMouseWheel = function(event) {
}
// calculate center, the date to zoom around
var gesture = util.fakeGesture(this, event),
var gesture = hammerUtil.fakeGesture(this, event),
pointer = getPointer(gesture.center, this.body.dom.center),
pointerDate = this._pointerToDate(pointer);
@ -462,8 +467,8 @@ Range.prototype._pointerToDate = function (pointer) {
*/
function getPointer (touch, element) {
return {
x: touch.pageX - vis.util.getAbsoluteLeft(element),
y: touch.pageY - vis.util.getAbsoluteTop(element)
x: touch.pageX - util.getAbsoluteLeft(element),
y: touch.pageY - util.getAbsoluteTop(element)
};
}
@ -525,3 +530,5 @@ Range.prototype.moveTo = function(moveTo) {
this.setRange(newStart, newEnd);
};
module.exports = Range;

src/timeline/Stack.js → lib/timeline/Stack.js View File

@ -1,13 +1,11 @@
/**
* Utility functions for ordering and stacking of items
*/
var stack = {};
// Utility functions for ordering and stacking of items
var EPSILON = 0.001; // used when checking collisions, to prevent round-off errors
/**
* Order items by their start data
* @param {Item[]} items
*/
stack.orderByStart = function(items) {
exports.orderByStart = function(items) {
items.sort(function (a, b) {
return a.data.start - b.data.start;
});
@ -18,7 +16,7 @@ stack.orderByStart = function(items) {
* is used.
* @param {Item[]} items
*/
stack.orderByEnd = function(items) {
exports.orderByEnd = function(items) {
items.sort(function (a, b) {
var aTime = ('end' in a.data) ? a.data.end : a.data.start,
bTime = ('end' in b.data) ? b.data.end : b.data.start;
@ -32,13 +30,13 @@ stack.orderByEnd = function(items) {
* other.
* @param {Item[]} items
* All visible items
* @param {{item: number, axis: number}} margin
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* Margins between items and between items and the axis.
* @param {boolean} [force=false]
* If true, all items will be repositioned. If false (default), only
* items having a top===null will be re-stacked
*/
stack.stack = function(items, margin, force) {
exports.stack = function(items, margin, force) {
var i, iMax;
if (force) {
@ -61,7 +59,7 @@ stack.stack = function(items, margin, force) {
var collidingItem = null;
for (var j = 0, jj = items.length; j < jj; j++) {
var other = items[j];
if (other.top !== null && other !== item && stack.collision(item, other, margin.item)) {
if (other.top !== null && other !== item && exports.collision(item, other, margin.item)) {
collidingItem = other;
break;
}
@ -69,7 +67,7 @@ stack.stack = function(items, margin, force) {
if (collidingItem != null) {
// There is a collision. Reposition the items above the colliding element
item.top = collidingItem.top + collidingItem.height + margin.item;
item.top = collidingItem.top + collidingItem.height + margin.item.vertical;
}
} while (collidingItem);
}
@ -80,10 +78,10 @@ stack.stack = function(items, margin, force) {
* Adjust vertical positions of the items without stacking them
* @param {Item[]} items
* All visible items
* @param {{item: number, axis: number}} margin
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* Margins between items and between items and the axis.
*/
stack.nostack = function(items, margin) {
exports.nostack = function(items, margin) {
var i, iMax;
// reset top position of all items
@ -97,16 +95,14 @@ stack.nostack = function(items, margin) {
* The items must have parameters left, width, top, and height.
* @param {Item} a The first item
* @param {Item} b The second item
* @param {Number} margin A minimum required margin.
* If margin is provided, the two items will be
* marked colliding when they overlap or
* when the margin between the two is smaller than
* the requested margin.
* @param {{horizontal: number, vertical: number}} margin
* An object containing a horizontal and vertical
* minimum required margin.
* @return {boolean} true if a and b collide, else false
*/
stack.collision = function(a, b, margin) {
return ((a.left - margin) < (b.left + b.width) &&
(a.left + a.width + margin) > b.left &&
(a.top - margin) < (b.top + b.height) &&
(a.top + a.height + margin) > b.top);
exports.collision = function(a, b, margin) {
return ((a.left - margin.horizontal + EPSILON) < (b.left + b.width) &&
(a.left + a.width + margin.horizontal - EPSILON) > b.left &&
(a.top - margin.vertical + EPSILON) < (b.top + b.height) &&
(a.top + a.height + margin.vertical - EPSILON) > b.top);
};

src/timeline/TimeStep.js → lib/timeline/TimeStep.js View File

@ -1,3 +1,5 @@
var moment = require('../module/moment');
/**
* @constructor TimeStep
* The class TimeStep is an iterator for dates. You provide a start date and an
@ -464,3 +466,5 @@ TimeStep.prototype.getLabelMajor = function(date) {
default: return '';
}
};
module.exports = TimeStep;

src/timeline/Timeline.js → lib/timeline/Timeline.js View File

@ -1,3 +1,14 @@
var Emitter = require('emitter-component');
var Hammer = require('../module/hammer');
var util = require('../util');
var DataSet = require('../DataSet');
var DataView = require('../DataView');
var Range = require('./Range');
var TimeAxis = require('./component/TimeAxis');
var CurrentTime = require('./component/CurrentTime');
var CustomTime = require('./component/CustomTime');
var ItemSet = require('./component/ItemSet');
/**
* Create a timeline visualization
* @param {HTMLElement} container
@ -359,6 +370,15 @@ Timeline.prototype.setItems = function(items) {
}
};
/**
* Get the id's of the currently visible items.
* @returns {Array} The ids of the visible items
*/
Timeline.prototype.getVisibleItems = function() {
return this.itemSet && this.itemSet.getVisibleItems() || [];
};
/**
* Set groups
* @param {vis.DataSet | Array | google.visualization.DataTable} groups
@ -885,3 +905,5 @@ Timeline.prototype._updateScrollTop = function () {
Timeline.prototype._getScrollTop = function () {
return this.props.scrollTop;
};
module.exports = Timeline;

src/timeline/component/Component.js → lib/timeline/component/Component.js View File

@ -50,3 +50,5 @@ Component.prototype._isResized = function() {
return resized;
};
module.exports = Component;

src/timeline/component/CurrentTime.js → lib/timeline/component/CurrentTime.js View File

@ -1,3 +1,6 @@
var util = require('../../util');
var Component = require('./Component');
/**
* A current time bar
* @param {{range: Range, dom: Object, domProps: Object}} body
@ -6,7 +9,6 @@
* @constructor CurrentTime
* @extends Component
*/
function CurrentTime (body, options) {
this.body = body;
@ -126,3 +128,5 @@ CurrentTime.prototype.stop = function() {
delete this.currentTimeTimer;
}
};
module.exports = CurrentTime;

src/timeline/component/CustomTime.js → lib/timeline/component/CustomTime.js View File

@ -1,3 +1,7 @@
var Hammer = require('../../module/hammer');
var util = require('../../util');
var Component = require('./Component');
/**
* A custom time bar
* @param {{range: Range, dom: Object}} body
@ -180,3 +184,5 @@ CustomTime.prototype._onDragEnd = function (event) {
event.stopPropagation();
event.preventDefault();
};
module.exports = CustomTime;

src/timeline/component/DataAxis.js → lib/timeline/component/DataAxis.js View File

@ -1,3 +1,8 @@
var util = require('../../util');
var DOMutil = require('../../DOMutil');
var Component = require('./Component');
var DataStep = require('../DataStep');
/**
* A horizontal time axis
* @param {Object} [options] See DataAxis.setOptions for the available
@ -466,3 +471,5 @@ DataAxis.prototype._calculateCharSize = function () {
DataAxis.prototype.snap = function(date) {
return this.step.snap(date);
};
module.exports = DataAxis;

src/timeline/component/GraphGroup.js → lib/timeline/component/GraphGroup.js View File

@ -1,3 +1,6 @@
var util = require('../../util');
var DOMutil = require('../../DOMutil');
/**
* @constructor Group
* @param {Number | String} groupId
@ -28,11 +31,11 @@ GraphGroup.prototype.setItems = function(items) {
else {
this.itemsData = [];
}
}
};
GraphGroup.prototype.setZeroPosition = function(pos) {
this.zeroPosition = pos;
}
};
GraphGroup.prototype.setOptions = function(options) {
if (options !== undefined) {
@ -113,4 +116,6 @@ GraphGroup.prototype.drawIcon = function(x, y, JSONcontainer, SVGcontainer, icon
DOMutil.drawBar(x + 0.5*barWidth + offset , y + fillHeight - bar1Height - 1, barWidth, bar1Height, this.className + ' bar', JSONcontainer, SVGcontainer);
DOMutil.drawBar(x + 1.5*barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, this.className + ' bar', JSONcontainer, SVGcontainer);
}
}
};
module.exports = GraphGroup;

src/timeline/component/Group.js → lib/timeline/component/Group.js View File

@ -1,3 +1,7 @@
var util = require('../../util');
var stack = require('../Stack');
var ItemRange = require('./item/ItemRange');
/**
* @constructor Group
* @param {Number | String} groupId
@ -119,7 +123,7 @@ Group.prototype.getLabelWidth = function() {
/**
* Repaint this group
* @param {{start: number, end: number}} range
* @param {{item: number, axis: number}} margin
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* @param {boolean} [restack=false] Force restacking of all items
* @return {boolean} Returns true if the group is resized
*/
@ -168,10 +172,10 @@ Group.prototype.redraw = function(range, margin, restack) {
item.top -= offset;
});
}
height = max + margin.item / 2;
height = max + margin.item.vertical / 2;
}
else {
height = margin.axis + margin.item;
height = margin.axis + margin.item.vertical;
}
height = Math.max(height, this.props.label.height);
@ -389,6 +393,7 @@ Group.prototype._checkIfInvisible = function(item, visibleItems, range) {
return false;
}
else {
if (item.displayed) item.hide();
return true;
}
};
@ -415,3 +420,5 @@ Group.prototype._checkIfVisible = function(item, visibleItems, range) {
if (item.displayed) item.hide();
}
};
module.exports = Group;

src/timeline/component/ItemSet.js → lib/timeline/component/ItemSet.js View File

@ -1,3 +1,14 @@
var Hammer = require('../../module/hammer');
var util = require('../../util');
var DataSet = require('../../DataSet');
var DataView = require('../../DataView');
var Component = require('./Component');
var Group = require('./Group');
var ItemBox = require('./item/ItemBox');
var ItemPoint = require('./item/ItemPoint');
var ItemRange = require('./item/ItemRange');
var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
/**
@ -41,7 +52,10 @@ function ItemSet(body, options) {
},
margin: {
item: 10,
item: {
horizontal: 10,
vertical: 10
},
axis: 20
},
padding: 5
@ -200,8 +214,15 @@ ItemSet.prototype._create = function(){
* {Number} margin.axis
* Margin between the axis and the items in pixels.
* Default is 20.
* {Number} margin.item.horizontal
* Horizontal margin between items in pixels.
* Default is 10.
* {Number} margin.item.vertical
* Vertical Margin between items in pixels.
* Default is 10.
* {Number} margin.item
* Margin between items in pixels. Default is 10.
* Margin between items in pixels in both horizontal
* and vertical direction. Default is 10.
* {Number} margin
* Set margin for both axis and items in pixels.
* {Number} padding
@ -243,10 +264,20 @@ ItemSet.prototype.setOptions = function(options) {
if ('margin' in options) {
if (typeof options.margin === 'number') {
this.options.margin.axis = options.margin;
this.options.margin.item = options.margin;
this.options.margin.item.horizontal = options.margin;
this.options.margin.item.vertical = options.margin;
}
else if (typeof options.margin === 'object'){
util.selectiveExtend(['axis', 'item'], this.options.margin, options.margin);
else if (typeof options.margin === 'object') {
util.selectiveExtend(['axis'], this.options.margin, options.margin);
if ('item' in options.margin) {
if (typeof options.margin.item === 'number') {
this.options.margin.item.horizontal = options.margin.item;
this.options.margin.item.vertical = options.margin.item;
}
else if (typeof options.margin.item === 'object') {
util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item);
}
}
}
}
@ -266,7 +297,7 @@ ItemSet.prototype.setOptions = function(options) {
var addCallback = (function (name) {
if (name in options) {
var fn = options[name];
if (!(fn instanceof Function) || fn.length != 2) {
if (!(fn instanceof Function)) {
throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)');
}
this.options[name] = fn;
@ -385,6 +416,36 @@ ItemSet.prototype.getSelection = function() {
return this.selection.concat([]);
};
/**
* Get the id's of the currently visible items.
* @returns {Array} The ids of the visible items
*/
ItemSet.prototype.getVisibleItems = function() {
var range = this.body.range.getRange();
var left = this.body.util.toScreen(range.start);
var right = this.body.util.toScreen(range.end);
var ids = [];
for (var groupId in this.groups) {
if (this.groups.hasOwnProperty(groupId)) {
var group = this.groups[groupId];
var rawVisibleItems = group.visibleItems;
// filter the "raw" set with visibleItems into a set which is really
// visible by pixels
for (var i = 0; i < rawVisibleItems.length; i++) {
var item = rawVisibleItems[i];
// TODO: also check whether visible vertically
if ((item.left < right) && (item.left + item.width > left)) {
ids.push(item.id);
}
}
}
}
return ids;
};
/**
* Deselect a selected item
* @param {String | Number} id
@ -437,10 +498,10 @@ ItemSet.prototype.redraw = function() {
},
nonFirstMargin = {
item: margin.item,
axis: margin.item / 2
axis: margin.item.vertical / 2
},
height = 0,
minHeight = margin.axis + margin.item;
minHeight = margin.axis + margin.item.vertical;
util.forEach(this.groups, function (group) {
var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
var groupResized = group.redraw(range, groupMargin, restack);
@ -1200,7 +1261,7 @@ ItemSet.prototype._onAddItem = function (event) {
}
else {
// add item
var xAbs = vis.util.getAbsoluteLeft(this.dom.frame);
var xAbs = util.getAbsoluteLeft(this.dom.frame);
var x = event.gesture.center.pageX - xAbs;
var start = this.body.util.toTime(x);
var newItem = {
@ -1318,3 +1379,4 @@ ItemSet.itemSetFromTarget = function(event) {
return null;
};
module.exports = ItemSet;

src/timeline/component/Legend.js → lib/timeline/component/Legend.js View File

@ -1,5 +1,9 @@
var util = require('../../util');
var DOMutil = require('../../DOMutil');
var Component = require('./Component');
/**
* Created by Alex on 6/17/14.
* Legend for Graph2d
*/
function Legend(body, options, side) {
this.body = body;
@ -27,7 +31,7 @@ function Legend(body, options, side) {
this._create();
this.setOptions(options);
};
}
Legend.prototype = new Component();
@ -69,7 +73,7 @@ Legend.prototype._create = function() {
this.dom.frame.appendChild(this.svg);
this.dom.frame.appendChild(this.dom.textArea);
}
};
/**
* Hide the component from the DOM
@ -95,7 +99,7 @@ Legend.prototype.show = function() {
Legend.prototype.setOptions = function(options) {
var fields = ['enabled','orientation','icons','left','right'];
util.selectiveDeepExtend(fields, this.options, options);
}
};
Legend.prototype.redraw = function() {
if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false) {
@ -142,7 +146,7 @@ Legend.prototype.redraw = function() {
this.drawLegendIcons();
}
var content = "";
var content = '';
for (var groupId in this.groups) {
if (this.groups.hasOwnProperty(groupId)) {
content += this.groups[groupId].content + '<br />';
@ -151,13 +155,13 @@ Legend.prototype.redraw = function() {
this.dom.textArea.innerHTML = content;
this.dom.textArea.style.lineHeight = ((0.75 * this.options.iconSize) + this.options.iconSpacing) + 'px';
}
}
};
Legend.prototype.drawLegendIcons = function() {
if (this.dom.frame.parentNode) {
DOMutil.prepareElements(this.svgElements);
var padding = window.getComputedStyle(this.dom.frame).paddingTop;
var iconOffset = Number(padding.replace("px",''));
var iconOffset = Number(padding.replace('px',''));
var x = iconOffset;
var iconWidth = this.options.iconSize;
var iconHeight = 0.75 * this.options.iconSize;
@ -174,4 +178,6 @@ Legend.prototype.drawLegendIcons = function() {
DOMutil.cleanupElements(this.svgElements);
}
}
};
module.exports = Legend;

src/timeline/component/LineGraph.js → lib/timeline/component/LineGraph.js View File

@ -1,3 +1,12 @@
var util = require('../../util');
var DOMutil = require('../../DOMutil');
var DataSet = require('../../DataSet');
var DataView = require('../../DataView');
var Component = require('./Component');
var DataAxis = require('./DataAxis');
var GraphGroup = require('./GraphGroup');
var Legend = require('./Legend');
var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
/**
@ -1059,7 +1068,4 @@ LineGraph.prototype._linear = function(data) {
return d;
};
module.exports = LineGraph;

src/timeline/component/TimeAxis.js → lib/timeline/component/TimeAxis.js View File

@ -1,3 +1,7 @@
var util = require('../../util');
var Component = require('./Component');
var TimeStep = require('../TimeStep');
/**
* A horizontal time axis
* @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
@ -387,3 +391,5 @@ TimeAxis.prototype._calculateCharSize = function () {
TimeAxis.prototype.snap = function(date) {
return this.step.snap(date);
};
module.exports = TimeAxis;

src/timeline/component/css/animation.css → lib/timeline/component/css/animation.css View File


src/timeline/component/css/currenttime.css → lib/timeline/component/css/currenttime.css View File


src/timeline/component/css/customtime.css → lib/timeline/component/css/customtime.css View File


src/timeline/component/css/dataaxis.css → lib/timeline/component/css/dataaxis.css View File


src/timeline/component/css/item.css → lib/timeline/component/css/item.css View File


src/timeline/component/css/itemset.css → lib/timeline/component/css/itemset.css View File


Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save