vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1355 lines
44 KiB

  1. /**
  2. *
  3. * Useful during debugging
  4. * =======================
  5. *
  6. * console.log(JSON.stringify(output, null, 2));
  7. *
  8. * for (let i in network.body.edges) {
  9. * let edge = network.body.edges[i];
  10. * console.log("" + i + ": from: " + edge.fromId + ", to: " + edge.toId);
  11. * }
  12. */
  13. var fs = require('fs');
  14. var assert = require('assert');
  15. var vis = require('../dist/vis');
  16. var Network = vis.network;
  17. var stdout = require('test-console').stdout;
  18. var Validator = require("./../lib/shared/Validator").default;
  19. var jsdom_global = require('jsdom-global');
  20. var canvasMockify = require('./canvas-mock');
  21. var {allOptions, configureOptions} = require('./../lib/network/options.js');
  22. //var {printStyle} = require('./../lib/shared/Validator');
  23. /**
  24. * Merge all options of object b into object b
  25. * @param {Object} a
  26. * @param {Object} b
  27. * @return {Object} a
  28. *
  29. * Adapted merge() in dotparser.js
  30. */
  31. function merge (a, b) {
  32. if (!a) {
  33. a = {};
  34. }
  35. if (b) {
  36. for (var name in b) {
  37. if (b.hasOwnProperty(name)) {
  38. if (typeof b[name] === 'object') {
  39. a[name] = merge(a[name], b[name]);
  40. } else {
  41. a[name] = b[name];
  42. }
  43. }
  44. }
  45. }
  46. return a;
  47. }
  48. /**
  49. * Load legacy-style (i.e. not module) javascript files into the given context.
  50. */
  51. function include(list, context) {
  52. if (!(list instanceof Array)) {
  53. list = [list];
  54. }
  55. for (var n in list) {
  56. var path = list[n];
  57. var arr = [fs.readFileSync(path) + ''];
  58. eval.apply(context, arr);
  59. }
  60. }
  61. /**
  62. * Defined network consists of two sub-networks:
  63. *
  64. * - 1-2-3-4
  65. * - 11-12-13-14
  66. *
  67. * For reference, this is the sample network of issue #1218
  68. */
  69. function createSampleNetwork(options) {
  70. var NumInitialNodes = 8;
  71. var NumInitialEdges = 6;
  72. var nodes = new vis.DataSet([
  73. {id: 1, label: '1'},
  74. {id: 2, label: '2'},
  75. {id: 3, label: '3'},
  76. {id: 4, label: '4'},
  77. {id: 11, label: '11'},
  78. {id: 12, label: '12'},
  79. {id: 13, label: '13'},
  80. {id: 14, label: '14'},
  81. ]);
  82. var edges = new vis.DataSet([
  83. {from: 1, to: 2},
  84. {from: 2, to: 3},
  85. {from: 3, to: 4},
  86. {from: 11, to: 12},
  87. {from: 12, to: 13},
  88. {from: 13, to: 14},
  89. ]);
  90. // create a network
  91. var container = document.getElementById('mynetwork');
  92. var data = {
  93. nodes: nodes,
  94. edges: edges
  95. };
  96. var defaultOptions = {
  97. layout: {
  98. randomSeed: 8
  99. },
  100. edges: {
  101. smooth: {
  102. type: 'continuous' // avoid dynamic here, it adds extra hidden nodes
  103. }
  104. }
  105. };
  106. options = merge(defaultOptions, options);
  107. var network = new vis.Network(container, data, options);
  108. assertNumNodes(network, NumInitialNodes);
  109. assertNumEdges(network, NumInitialEdges);
  110. return [network, data, NumInitialNodes, NumInitialEdges];
  111. };
  112. /**
  113. * Create a cluster for the dynamic data change cases.
  114. *
  115. * Works on the network created by createSampleNetwork().
  116. *
  117. * This is actually a pathological case; there are two separate sub-networks and
  118. * a cluster is made of two nodes, each from one of the sub-networks.
  119. */
  120. function createCluster(network) {
  121. var clusterOptionsByData = {
  122. joinCondition: function(node) {
  123. if (node.id == 1 || node.id == 11) return true;
  124. return false;
  125. },
  126. clusterNodeProperties: {id:"c1", label:'c1'}
  127. }
  128. network.cluster(clusterOptionsByData);
  129. }
  130. /**
  131. * Display node/edge state, useful during debugging
  132. */
  133. function log(network) {
  134. console.log(Object.keys(network.body.nodes));
  135. console.log(network.body.nodeIndices);
  136. console.log(Object.keys(network.body.edges));
  137. console.log(network.body.edgeIndices);
  138. };
  139. /**
  140. * Note that only the node and edges counts are asserted.
  141. * This might be done more thoroughly by explicitly checking the id's
  142. */
  143. function assertNumNodes(network, expectedPresent, expectedVisible) {
  144. if (expectedVisible === undefined) expectedVisible = expectedPresent;
  145. assert.equal(Object.keys(network.body.nodes).length, expectedPresent, "Total number of nodes does not match");
  146. assert.equal(network.body.nodeIndices.length, expectedVisible, "Number of visible nodes does not match");
  147. };
  148. /**
  149. * Comment at assertNumNodes() also applies.
  150. */
  151. function assertNumEdges(network, expectedPresent, expectedVisible) {
  152. if (expectedVisible === undefined) expectedVisible = expectedPresent;
  153. assert.equal(Object.keys(network.body.edges).length, expectedPresent, "Total number of edges does not match");
  154. assert.equal(network.body.edgeIndices.length, expectedVisible, "Number of visible edges does not match");
  155. };
  156. /**
  157. * Check if the font options haven't changed.
  158. *
  159. * This is to guard against future code changes; a lot of the code deals with particular properties of
  160. * the font options.
  161. * If any assertion fails here, all code in Network handling fonts should be checked.
  162. */
  163. function checkFontProperties(fontItem, checkStrict = true) {
  164. var knownProperties = [
  165. 'color',
  166. 'size',
  167. 'face',
  168. 'background',
  169. 'strokeWidth',
  170. 'strokeColor',
  171. 'align',
  172. 'multi',
  173. 'vadjust',
  174. 'bold',
  175. 'boldital',
  176. 'ital',
  177. 'mono',
  178. ];
  179. // All properties in fontItem should be known
  180. for (var prop in fontItem) {
  181. if (prop === '__type__') continue; // Skip special field in options definition
  182. if (!fontItem.hasOwnProperty(prop)) continue;
  183. assert(knownProperties.indexOf(prop) !== -1, "Unknown font option '" + prop + "'");
  184. }
  185. if (!checkStrict) return;
  186. // All known properties should be present
  187. var keys = Object.keys(fontItem);
  188. for (var n in knownProperties) {
  189. var prop = knownProperties[n];
  190. assert(keys.indexOf(prop) !== -1, "Missing known font option '" + prop + "'");
  191. }
  192. }
  193. describe('Network', function () {
  194. before(function() {
  195. this.jsdom_global = jsdom_global(
  196. "<div id='mynetwork'></div>",
  197. { skipWindowCheck: true}
  198. );
  199. canvasMockify(window);
  200. this.container = document.getElementById('mynetwork');
  201. });
  202. after(function() {
  203. try {
  204. this.jsdom_global();
  205. } catch(e) {
  206. if (e.message() === 'window is undefined') {
  207. console.warning("'" + e.message() + "' happened again");
  208. } else {
  209. throw e;
  210. }
  211. }
  212. });
  213. /////////////////////////////////////////////////////
  214. // Local helper methods for Edge and Node testing
  215. /////////////////////////////////////////////////////
  216. /**
  217. * Simplify network creation for local tests
  218. */
  219. function createNetwork(options) {
  220. var [network, data, numNodes, numEdges] = createSampleNetwork(options);
  221. return network;
  222. }
  223. function firstNode(network) {
  224. for (var id in network.body.nodes) {
  225. return network.body.nodes[id];
  226. }
  227. return undefined;
  228. }
  229. function firstEdge(network) {
  230. for (var id in network.body.edges) {
  231. return network.body.edges[id];
  232. }
  233. return undefined;
  234. }
  235. function checkChooserValues(item, chooser, labelChooser) {
  236. if (chooser === 'function') {
  237. assert.equal(typeof item.chooser, 'function');
  238. } else {
  239. assert.equal(item.chooser, chooser);
  240. }
  241. if (labelChooser === 'function') {
  242. assert.equal(typeof item.labelModule.fontOptions.chooser, 'function');
  243. } else {
  244. assert.equal(item.labelModule.fontOptions.chooser, labelChooser);
  245. }
  246. }
  247. /////////////////////////////////////////////////////
  248. // End Local helper methods for Edge and Node testing
  249. /////////////////////////////////////////////////////
  250. /**
  251. * Helper function for clustering
  252. */
  253. function clusterTo(network, clusterId, nodeList, allowSingle) {
  254. var options = {
  255. joinCondition: function(node) {
  256. return nodeList.indexOf(node.id) !== -1;
  257. },
  258. clusterNodeProperties: {
  259. id: clusterId,
  260. label: clusterId
  261. }
  262. }
  263. if (allowSingle === true) {
  264. options.clusterNodeProperties.allowSingleNodeCluster = true
  265. }
  266. network.cluster(options);
  267. }
  268. /**
  269. * At time of writing, this test detected 22 out of 33 'illegal' loops.
  270. * The real deterrent is eslint rule 'guard-for-in`.
  271. */
  272. it('can deal with added fields in Array.prototype', function (done) {
  273. var canvas = window.document.createElement('canvas');
  274. Array.prototype.foo = 1; // Just add anything to the prototype
  275. Object.prototype.bar = 2; // Let's screw up hashes as well
  276. // The network should just run without throwing errors
  277. try {
  278. var [network, data, numNodes, numEdges] = createSampleNetwork({});
  279. // Do some stuff to trigger more errors
  280. clusterTo(network, 'c1', [1,2,3]);
  281. data.nodes.remove(1);
  282. network.openCluster('c1');
  283. clusterTo(network, 'c1', [4], true);
  284. clusterTo(network, 'c2', ['c1'], true);
  285. clusterTo(network, 'c3', ['c2'], true);
  286. data.nodes.remove(4);
  287. } catch(e) {
  288. delete Array.prototype.foo; // Remove it again so as not to confuse other tests.
  289. delete Object.prototype.bar;
  290. assert(false, "Got exception:\n" + e.stack);
  291. }
  292. delete Array.prototype.foo; // Remove it again so as not to confuse other tests.
  293. delete Object.prototype.bar;
  294. done();
  295. });
  296. /**
  297. * This is a fix on one issue (#3543), but in fact **all* options for all API calls should
  298. * remain unchanged.
  299. * TODO: extend test for all API calls with options, see #3548
  300. */
  301. it('does not change the options object passed to fit()', function() {
  302. var [network, data, numNodes, numEdges] = createSampleNetwork({});
  303. var options = {};
  304. network.fit(options);
  305. // options should still be empty
  306. for (var prop in options) {
  307. assert(!options.hasOwnProperty(prop), 'No properties should be present in options, detected property: ' + prop);
  308. }
  309. });
  310. it('does not crash when dataChanged is triggered when setting options on first initialization ', function() {
  311. // The init should succeed without an error thrown.
  312. var options = {
  313. nodes: {
  314. physics: false // any value here triggered the error
  315. }
  316. };
  317. createSampleNetwork(options);
  318. // Do the other values as well that can cause this./
  319. // 'any values' applies here as well, expecting no throw
  320. options = {edges: {physics: false}};
  321. createSampleNetwork(options);
  322. options = {nodes: {hidden: false}};
  323. createSampleNetwork(options);
  324. options = {edges: {hidden: false}};
  325. createSampleNetwork(options);
  326. });
  327. describe('Node', function () {
  328. it('has known font options', function () {
  329. var network = createNetwork({});
  330. checkFontProperties(network.nodesHandler.defaultOptions.font);
  331. checkFontProperties(allOptions.nodes.font);
  332. checkFontProperties(configureOptions.nodes.font, false);
  333. });
  334. /**
  335. * NOTE: choosify tests of Node and Edge are parallel
  336. * TODO: consolidate this is necessary
  337. */
  338. it('properly handles choosify input', function () {
  339. // check defaults
  340. var options = {};
  341. var network = createNetwork(options);
  342. checkChooserValues(firstNode(network), true, true);
  343. // There's no point in checking invalid values here; these are detected by the options parser
  344. // and subsequently handled as missing input, thus assigned defaults
  345. // check various combinations of valid input
  346. options = {nodes: {chosen: false}};
  347. network = createNetwork(options);
  348. checkChooserValues(firstNode(network), false, false);
  349. options = {nodes: {chosen: { node:true, label:false}}};
  350. network = createNetwork(options);
  351. checkChooserValues(firstNode(network), true, false);
  352. options = {nodes: {chosen: {
  353. node:true,
  354. label: function(value, id, selected, hovering) {}
  355. }}};
  356. network = createNetwork(options);
  357. checkChooserValues(firstNode(network), true, 'function');
  358. options = {nodes: {chosen: {
  359. node: function(value, id, selected, hovering) {},
  360. label:false,
  361. }}};
  362. network = createNetwork(options);
  363. checkChooserValues(firstNode(network), 'function', false);
  364. });
  365. }); // Node
  366. describe('Edge', function () {
  367. it('has known font options', function () {
  368. var network = createNetwork({});
  369. checkFontProperties(network.edgesHandler.defaultOptions.font);
  370. checkFontProperties(allOptions.edges.font);
  371. checkFontProperties(configureOptions.edges.font, false);
  372. });
  373. /**
  374. * NOTE: choosify tests of Node and Edge are parallel
  375. * TODO: consolidate this is necessary
  376. */
  377. it('properly handles choosify input', function () {
  378. // check defaults
  379. var options = {};
  380. var network = createNetwork(options);
  381. checkChooserValues(firstEdge(network), true, true);
  382. // There's no point in checking invalid values here; these are detected by the options parser
  383. // and subsequently handled as missing input, thus assigned defaults
  384. // check various combinations of valid input
  385. options = {edges: {chosen: false}};
  386. network = createNetwork(options);
  387. checkChooserValues(firstEdge(network), false, false);
  388. options = {edges: {chosen: { edge:true, label:false}}};
  389. network = createNetwork(options);
  390. checkChooserValues(firstEdge(network), true, false);
  391. options = {edges: {chosen: {
  392. edge:true,
  393. label: function(value, id, selected, hovering) {}
  394. }}};
  395. network = createNetwork(options);
  396. checkChooserValues(firstEdge(network), true, 'function');
  397. options = {edges: {chosen: {
  398. edge: function(value, id, selected, hovering) {},
  399. label:false,
  400. }}};
  401. network = createNetwork(options);
  402. checkChooserValues(firstEdge(network), 'function', false);
  403. });
  404. /**
  405. * Support routine for next unit test
  406. */
  407. function createDataforColorChange() {
  408. var nodes = new vis.DataSet([
  409. {id: 1, label: 'Node 1' }, // group:'Group1'},
  410. {id: 2, label: 'Node 2', group:'Group2'},
  411. {id: 3, label: 'Node 3'},
  412. ]);
  413. // create an array with edges
  414. var edges = new vis.DataSet([
  415. {id: 1, from: 1, to: 2},
  416. {id: 2, from: 1, to: 3, color: { inherit: 'to'}},
  417. {id: 3, from: 3, to: 3, color: { color: '#00FF00'}},
  418. {id: 4, from: 2, to: 3, color: { inherit: 'from'}},
  419. ]);
  420. var data = {
  421. nodes: nodes,
  422. edges: edges
  423. };
  424. return data;
  425. }
  426. /**
  427. * Unit test for fix of #3350
  428. *
  429. * The issue is that changing color options is not registered in the nodes.
  430. * We test the updates the color options in the general edges options here.
  431. */
  432. it('sets inherit color option for edges on call to Network.setOptions()', function () {
  433. var container = document.getElementById('mynetwork');
  434. var data = createDataforColorChange();
  435. var options = {
  436. "edges" : { "color" : { "inherit" : "to" } },
  437. };
  438. // Test passing options on init.
  439. var network = new vis.Network(container, data, options);
  440. var edges = network.body.edges;
  441. assert.equal(edges[1].options.color.inherit, 'to'); // new default
  442. assert.equal(edges[2].options.color.inherit, 'to'); // set in edge
  443. assert.equal(edges[3].options.color.inherit, false); // has explicit color
  444. assert.equal(edges[4].options.color.inherit, 'from'); // set in edge
  445. // Sanity check: colors should still be defaults
  446. assert.equal(edges[1].options.color.color, network.edgesHandler.options.color.color);
  447. // Override the color value - inherit returns to default
  448. network.setOptions({ edges:{color: {}}});
  449. assert.equal(edges[1].options.color.inherit, 'from'); // default
  450. assert.equal(edges[2].options.color.inherit, 'to'); // set in edge
  451. assert.equal(edges[3].options.color.inherit, false); // has explicit color
  452. assert.equal(edges[4].options.color.inherit, 'from'); // set in edge
  453. // Check no options
  454. network = new vis.Network(container, data, {});
  455. edges = network.body.edges;
  456. assert.equal(edges[1].options.color.inherit, 'from'); // default
  457. assert.equal(edges[2].options.color.inherit, 'to'); // set in edge
  458. assert.equal(edges[3].options.color.inherit, false); // has explicit color
  459. assert.equal(edges[4].options.color.inherit, 'from'); // set in edge
  460. // Set new value
  461. network.setOptions(options);
  462. assert.equal(edges[1].options.color.inherit, 'to');
  463. assert.equal(edges[2].options.color.inherit, 'to'); // set in edge
  464. assert.equal(edges[3].options.color.inherit, false); // has explicit color
  465. assert.equal(edges[4].options.color.inherit, 'from'); // set in edge
  466. /*
  467. // Useful for debugging
  468. console.log('===================================');
  469. console.log(edges[1].options.color);
  470. console.log(edges[1].options.color.__proto__);
  471. console.log(edges[1].options);
  472. console.log(edges[1].options.__proto__);
  473. console.log(edges[1].edgeOptions);
  474. */
  475. });
  476. it('sets inherit color option for specific edge', function () {
  477. var container = document.getElementById('mynetwork');
  478. var data = createDataforColorChange();
  479. // Check no options
  480. var network = new vis.Network(container, data, {});
  481. var edges = network.body.edges;
  482. assert.equal(edges[1].options.color.inherit, 'from'); // default
  483. assert.equal(edges[2].options.color.inherit, 'to'); // set in edge
  484. assert.equal(edges[3].options.color.inherit, false); // has explicit color
  485. assert.equal(edges[4].options.color.inherit, 'from'); // set in edge
  486. // Set new value
  487. data.edges.update({id: 1, color: { inherit: 'to'}});
  488. assert.equal(edges[1].options.color.inherit, 'to'); // Only this changed
  489. assert.equal(edges[2].options.color.inherit, 'to');
  490. assert.equal(edges[3].options.color.inherit, false); // has explicit color
  491. assert.equal(edges[4].options.color.inherit, 'from');
  492. });
  493. /**
  494. * Perhaps TODO: add unit test for passing string value for color option
  495. */
  496. it('sets color value for edges on call to Network.setOptions()', function () {
  497. var container = document.getElementById('mynetwork');
  498. var data = createDataforColorChange();
  499. var defaultColor = '#848484'; // From defaults
  500. var color = '#FF0000';
  501. var options = {
  502. "edges" : { "color" : { "color" : color } },
  503. };
  504. // Test passing options on init.
  505. var network = new vis.Network(container, data, options);
  506. var edges = network.body.edges;
  507. assert.equal(edges[1].options.color.color, color);
  508. assert.equal(edges[1].options.color.inherit, false); // Explicit color, so no inherit
  509. assert.equal(edges[2].options.color.color, color);
  510. assert.equal(edges[2].options.color.inherit, 'to'); // Local value overrides! (bug according to docs)
  511. assert.notEqual(edges[3].options.color.color, color); // Has own value
  512. assert.equal(edges[3].options.color.inherit, false); // Explicit color, so no inherit
  513. assert.equal(edges[4].options.color.color, color);
  514. // Override the color value - all should return to default
  515. network.setOptions({ edges:{color: {}}});
  516. assert.equal(edges[1].options.color.color, defaultColor);
  517. assert.equal(edges[1].options.color.inherit, 'from');
  518. assert.equal(edges[2].options.color.color, defaultColor);
  519. assert.notEqual(edges[3].options.color.color, color); // Has own value
  520. assert.equal(edges[4].options.color.color, defaultColor);
  521. // Check no options
  522. network = new vis.Network(container, data, {});
  523. edges = network.body.edges;
  524. // At this point, color has not changed yet
  525. assert.equal(edges[1].options.color.color, defaultColor);
  526. assert.equal(edges[1].options.color.highlight, defaultColor);
  527. assert.equal(edges[1].options.color.inherit, 'from');
  528. assert.notEqual(edges[3].options.color.color, color); // Has own value
  529. // Set new Value
  530. network.setOptions(options);
  531. assert.equal(edges[1].options.color.color, color);
  532. assert.equal(edges[1].options.color.highlight, defaultColor); // Should not be changed
  533. assert.equal(edges[1].options.color.inherit, false); // Explicit color, so no inherit
  534. assert.equal(edges[2].options.color.color, color);
  535. assert.notEqual(edges[3].options.color.color, color); // Has own value
  536. assert.equal(edges[4].options.color.color, color);
  537. });
  538. /**
  539. * Unit test for fix of #3500
  540. * Checking to make sure edges that become unconnected due to node removal get reconnected
  541. */
  542. it('has reconnected edges', function () {
  543. var node1 = {id:1, label:"test1"};
  544. var node2 = {id:2, label:"test2"};
  545. var nodes = new vis.DataSet([node1, node2]);
  546. var edge = {id:1, from: 1, to:2};
  547. var edges = new vis.DataSet([edge]);
  548. var data = {
  549. nodes: nodes,
  550. edges: edges
  551. };
  552. var container = document.getElementById('mynetwork');
  553. var network = new vis.Network(container, data);
  554. //remove node causing edge to become disconnected
  555. nodes.remove(node2.id);
  556. var foundEdge = network.body.edges[edge.id];
  557. assert.ok(foundEdge===undefined, "edge is still in state cache");
  558. //add node back reconnecting edge
  559. nodes.add(node2);
  560. foundEdge = network.body.edges[edge.id];
  561. assert.ok(foundEdge!==undefined, "edge is missing from state cache");
  562. });
  563. }); // Edge
  564. describe('Clustering', function () {
  565. it('properly handles options allowSingleNodeCluster', function() {
  566. var [network, data, numNodes, numEdges] = createSampleNetwork();
  567. data.edges.update({from: 1, to: 11,});
  568. numEdges += 1;
  569. assertNumNodes(network, numNodes);
  570. assertNumEdges(network, numEdges);
  571. clusterTo(network, 'c1', [3,4]);
  572. numNodes += 1; // A clustering node is now hiding two nodes
  573. numEdges += 1; // One clustering edges now hiding two edges
  574. assertNumNodes(network, numNodes, numNodes - 2);
  575. assertNumEdges(network, numEdges, numEdges - 2);
  576. // Cluster of single node should fail, because by default allowSingleNodeCluster == false
  577. clusterTo(network, 'c2', [14]);
  578. assertNumNodes(network, numNodes, numNodes - 2); // Nothing changed
  579. assertNumEdges(network, numEdges, numEdges - 2);
  580. assert(network.body.nodes['c2'] === undefined); // Cluster not created
  581. // Redo with allowSingleNodeCluster == true
  582. clusterTo(network, 'c2', [14], true);
  583. numNodes += 1;
  584. numEdges += 1;
  585. assertNumNodes(network, numNodes, numNodes - 3);
  586. assertNumEdges(network, numEdges, numEdges - 3);
  587. assert(network.body.nodes['c2'] !== undefined); // Cluster created
  588. // allowSingleNodeCluster: true with two nodes
  589. // removing one clustered node should retain cluster
  590. clusterTo(network, 'c3', [11, 12], true);
  591. numNodes += 1; // Added cluster
  592. numEdges += 2;
  593. assertNumNodes(network, numNodes, 6);
  594. assertNumEdges(network, numEdges, 5);
  595. data.nodes.remove(12);
  596. assert(network.body.nodes['c3'] !== undefined); // Cluster should still be present
  597. numNodes -= 1; // removed node
  598. numEdges -= 3; // cluster edge C3-13 should be removed
  599. assertNumNodes(network, numNodes, 6);
  600. assertNumEdges(network, numEdges, 4);
  601. });
  602. it('removes nested clusters with allowSingleNodeCluster === true', function() {
  603. var [network, data, numNodes, numEdges] = createSampleNetwork();
  604. // Create a chain of nested clusters, three deep
  605. clusterTo(network, 'c1', [4], true);
  606. clusterTo(network, 'c2', ['c1'], true);
  607. clusterTo(network, 'c3', ['c2'], true);
  608. numNodes += 3;
  609. numEdges += 3;
  610. assertNumNodes(network, numNodes, numNodes - 3);
  611. assertNumEdges(network, numEdges, numEdges - 3);
  612. assert(network.body.nodes['c1'] !== undefined);
  613. assert(network.body.nodes['c2'] !== undefined);
  614. assert(network.body.nodes['c3'] !== undefined);
  615. // The whole chain should be removed when the bottom-most node is deleted
  616. data.nodes.remove(4);
  617. numNodes -= 4;
  618. numEdges -= 4;
  619. assertNumNodes(network, numNodes);
  620. assertNumEdges(network, numEdges);
  621. assert(network.body.nodes['c1'] === undefined);
  622. assert(network.body.nodes['c2'] === undefined);
  623. assert(network.body.nodes['c3'] === undefined);
  624. });
  625. /**
  626. * Check on fix for #1218
  627. */
  628. it('connects a new edge to a clustering node instead of the clustered node', function () {
  629. var [network, data, numNodes, numEdges] = createSampleNetwork();
  630. createCluster(network);
  631. numNodes += 1; // A clustering node is now hiding two nodes
  632. numEdges += 2; // Two clustering edges now hide two edges
  633. assertNumNodes(network, numNodes, numNodes - 2);
  634. assertNumEdges(network, numEdges, numEdges - 2);
  635. //console.log("Creating node 21")
  636. data.nodes.update([{id: 21, label: '21'}]);
  637. numNodes += 1; // New unconnected node added
  638. assertNumNodes(network, numNodes, numNodes - 2);
  639. assertNumEdges(network, numEdges, numEdges - 2); // edges unchanged
  640. //console.log("Creating edge 21 pointing to 1");
  641. // '1' is part of the cluster so should
  642. // connect to cluster instead
  643. data.edges.update([{from: 21, to: 1}]);
  644. numEdges += 2; // A new clustering edge is hiding a new edge
  645. assertNumNodes(network, numNodes, numNodes - 2); // nodes unchanged
  646. assertNumEdges(network, numEdges, numEdges - 3);
  647. });
  648. /**
  649. * Check on fix for #1315
  650. */
  651. it('can uncluster a clustered node when a node is removed that has an edge to that cluster', function () {
  652. // NOTE: this block is same as previous test
  653. var [network, data, numNodes, numEdges] = createSampleNetwork();
  654. createCluster(network);
  655. numNodes += 1; // A clustering node is now hiding two nodes
  656. numEdges += 2; // Two clustering edges now hide two edges
  657. assertNumNodes(network, numNodes, numNodes - 2);
  658. assertNumEdges(network, numEdges, numEdges - 2);
  659. // End block same as previous test
  660. //console.log("removing 12");
  661. data.nodes.remove(12);
  662. // NOTE:
  663. // At this particular point, there are still the two edges for node 12 in the edges DataSet.
  664. // If you want to do the delete correctly, these should also be deleted explictly from
  665. // the edges DataSet. In the Network instance, however, this.body.nodes and this.body.edges
  666. // should be correct, with the edges of 12 all cleared out.
  667. // 12 was connected to 11, which is clustered
  668. numNodes -= 1; // 12 removed, one less node
  669. numEdges -= 3; // clustering edge c1-12 and 2 edges of 12 gone
  670. assertNumNodes(network, numNodes, numNodes - 2);
  671. assertNumEdges(network, numEdges, numEdges - 1);
  672. //console.log("Unclustering c1");
  673. network.openCluster("c1");
  674. numNodes -= 1; // cluster node removed, one less node
  675. numEdges -= 1; // clustering edge gone, regular edge visible
  676. assertNumNodes(network, numNodes, numNodes); // all are visible again
  677. assertNumEdges(network, numEdges, numEdges); // all are visible again
  678. });
  679. /**
  680. * Check on fix for #1291
  681. */
  682. it('can remove a node inside a cluster and then open that cluster', function () {
  683. var [network, data, numNodes, numEdges] = createSampleNetwork();
  684. var clusterOptionsByData = {
  685. joinCondition: function(node) {
  686. if (node.id == 1 || node.id == 2 || node.id == 3) return true;
  687. return false;
  688. },
  689. clusterNodeProperties: {id:"c1", label:'c1'}
  690. }
  691. network.cluster(clusterOptionsByData);
  692. numNodes += 1; // new cluster node
  693. numEdges += 1; // 1 cluster edge expected
  694. assertNumNodes(network, numNodes, numNodes - 3); // 3 clustered nodes
  695. assertNumEdges(network, numEdges, numEdges - 3); // 3 edges hidden
  696. //console.log("removing node 2, which is inside the cluster");
  697. data.nodes.remove(2);
  698. numNodes -= 1; // clustered node removed
  699. numEdges -= 2; // edges removed hidden in cluster
  700. assertNumNodes(network, numNodes, numNodes - 2); // view doesn't change
  701. assertNumEdges(network, numEdges, numEdges - 1); // view doesn't change
  702. //console.log("Unclustering c1");
  703. network.openCluster("c1")
  704. numNodes -= 1; // cluster node gone
  705. numEdges -= 1; // cluster edge gone
  706. assertNumNodes(network, numNodes, numNodes); // all visible
  707. assertNumEdges(network, numEdges, numEdges); // all visible
  708. //log(network);
  709. });
  710. /**
  711. * Helper function for setting up a graph for testing clusterByEdgeCount()
  712. */
  713. function createOutlierGraph() {
  714. // create an array with nodes
  715. var nodes = new vis.DataSet([
  716. {id: 1, label: '1', group:'Group1'},
  717. {id: 2, label: '2', group:'Group2'},
  718. {id: 3, label: '3', group:'Group3'},
  719. {id: 4, label: '4', group:'Group4'},
  720. {id: 5, label: '5', group:'Group4'}
  721. ]);
  722. // create an array with edges
  723. var edges = new vis.DataSet([
  724. {from: 1, to: 3},
  725. {from: 1, to: 2},
  726. {from: 2, to: 4},
  727. {from: 2, to: 5}
  728. ]);
  729. // create a network
  730. var container = document.getElementById('mynetwork');
  731. var data = {
  732. nodes: nodes,
  733. edges: edges
  734. };
  735. var options = {
  736. "groups" : {
  737. "Group1" : { level:1 },
  738. "Group2" : { level:2 },
  739. "Group3" : { level:3 },
  740. "Group4" : { level:4 }
  741. }
  742. };
  743. var network = new vis.Network (container, data, options);
  744. return network;
  745. }
  746. /**
  747. * Check on fix for #3367
  748. */
  749. it('correctly handles edge cases of clusterByEdgeCount()', function () {
  750. /**
  751. * Collect clustered id's
  752. *
  753. * All node id's in clustering nodes are collected into an array;
  754. * The results for all clusters are returned as an array.
  755. *
  756. * Ordering of output depends on the order in which they are defined
  757. * within nodes.clustering; strictly, speaking, the array and its items
  758. * are collections, so order should not matter.
  759. */
  760. var collectClusters = function(network) {
  761. var clusters = [];
  762. for(var n in network.body.nodes) {
  763. var node = network.body.nodes[n];
  764. if (node.containedNodes === undefined) continue; // clusters only
  765. // Collect id's of nodes in the cluster
  766. var nodes = [];
  767. for(var m in node.containedNodes) {
  768. nodes.push(m);
  769. }
  770. clusters.push(nodes);
  771. }
  772. return clusters;
  773. }
  774. /**
  775. * Compare cluster data
  776. *
  777. * params are arrays of arrays of id's, e.g:
  778. *
  779. * [[1,3],[2,4]]
  780. *
  781. * Item arrays are the id's of nodes in a given cluster
  782. *
  783. * This comparison depends on the ordering; better
  784. * would be to treat the items and values as collections.
  785. */
  786. var compareClusterInfo = function(recieved, expected) {
  787. if (recieved.length !== expected.length) return false;
  788. for (var n = 0; n < recieved.length; ++n) {
  789. var itema = recieved[n];
  790. var itemb = expected[n];
  791. if (itema.length !== itemb.length) return false;
  792. for (var m = 0; m < itema.length; ++m) {
  793. if (itema[m] != itemb[m]) return false; // != because values can be string or number
  794. }
  795. }
  796. return true;
  797. }
  798. var assertJoinCondition = function(joinCondition, expected) {
  799. var network = createOutlierGraph();
  800. network.clusterOutliers({joinCondition: joinCondition});
  801. var recieved = collectClusters(network);
  802. //console.log(recieved);
  803. assert(compareClusterInfo(recieved, expected),
  804. 'recieved:' + JSON.stringify(recieved) + '; '
  805. + 'expected: ' + JSON.stringify(expected));
  806. };
  807. // Should cluster 3,4,5:
  808. var joinAll_ = function(n) { return true ; }
  809. // Should cluster none:
  810. var joinNone_ = function(n) { return false ; }
  811. // Should cluster 4 & 5:
  812. var joinLevel_ = function(n) { return n.level > 3 ; }
  813. assertJoinCondition(undefined , [[1,3],[2,4,5]]);
  814. assertJoinCondition(null , [[1,3],[2,4,5]]);
  815. assertJoinCondition(joinNone_ , []);
  816. assertJoinCondition(joinLevel_ , [[2,4,5]]);
  817. });
  818. ///////////////////////////////////////////////////////////////
  819. // Automatic opening of clusters due to dynamic data change
  820. ///////////////////////////////////////////////////////////////
  821. /**
  822. * Helper function, created nested clusters, three deep
  823. */
  824. function createNetwork1() {
  825. var [network, data, numNodes, numEdges] = createSampleNetwork();
  826. clusterTo(network, 'c1', [3,4]);
  827. numNodes += 1; // new cluster node
  828. numEdges += 1; // 1 cluster edge expected
  829. assertNumNodes(network, numNodes, numNodes - 2); // 2 clustered nodes
  830. assertNumEdges(network, numEdges, numEdges - 2); // 2 edges hidden
  831. clusterTo(network, 'c2', [2,'c1']);
  832. numNodes += 1; // new cluster node
  833. numEdges += 1; // 2 cluster edges expected
  834. assertNumNodes(network, numNodes, numNodes - 4); // 4 clustered nodes, including c1
  835. assertNumEdges(network, numEdges, numEdges - 4); // 4 edges hidden, including edge for c1
  836. clusterTo(network, 'c3', [1,'c2']);
  837. // Attempt at visualization: parentheses belong to the cluster one level above
  838. // c3
  839. // ( -c2 )
  840. // ( -c1 )
  841. // 14-13-12-11 1 -2 (-3-4)
  842. numNodes += 1; // new cluster node
  843. numEdges += 0; // No new cluster edge expected
  844. assertNumNodes(network, numNodes, numNodes - 6); // 6 clustered nodes, including c1 and c2
  845. assertNumEdges(network, numEdges, numEdges - 5); // 5 edges hidden, including edges for c1 and c2
  846. return [network, data, numNodes, numEdges];
  847. }
  848. it('opens clusters automatically when nodes deleted', function () {
  849. var [network, data, numNodes, numEdges] = createSampleNetwork();
  850. // Simple case: cluster of two nodes, delete one node
  851. clusterTo(network, 'c1', [3,4]);
  852. numNodes += 1; // new cluster node
  853. numEdges += 1; // 1 cluster edge expected
  854. assertNumNodes(network, numNodes, numNodes - 2); // 2 clustered nodes
  855. assertNumEdges(network, numEdges, numEdges - 2); // 2 edges hidden
  856. data.nodes.remove(4);
  857. numNodes -= 2; // deleting clustered node also removes cluster node
  858. numEdges -= 2; // cluster edge should also be removed
  859. assertNumNodes(network, numNodes, numNodes);
  860. assertNumEdges(network, numEdges, numEdges);
  861. // Extended case: nested nodes, three deep
  862. [network, data, numNodes, numEdges] = createNetwork1();
  863. data.nodes.remove(4);
  864. // c3
  865. // ( -c2 )
  866. // 14-13-12-11 1 (-2 -3)
  867. numNodes -= 2; // node removed, c1 also gone
  868. numEdges -= 2;
  869. assertNumNodes(network, numNodes, numNodes - 4);
  870. assertNumEdges(network, numEdges, numEdges - 3);
  871. data.nodes.remove(1);
  872. // c2
  873. // 14-13-12-11 (2 -3)
  874. numNodes -= 2; // node removed, c3 also gone
  875. numEdges -= 2;
  876. assertNumNodes(network, numNodes, numNodes - 2);
  877. assertNumEdges(network, numEdges, numEdges - 1);
  878. data.nodes.remove(2);
  879. // 14-13-12-11 3
  880. numNodes -= 2; // node removed, c2 also gone
  881. numEdges -= 1;
  882. assertNumNodes(network, numNodes); // All visible again
  883. assertNumEdges(network, numEdges);
  884. // Same as previous step, but remove all the given nodes in one go
  885. // The result should be the same.
  886. [network, data, numNodes, numEdges] = createNetwork1(); // nested nodes, three deep
  887. data.nodes.remove([1,2,4]);
  888. // 14-13-12-11 3
  889. assertNumNodes(network, 5);
  890. assertNumEdges(network, 3);
  891. });
  892. ///////////////////////////////////////////////////////////////
  893. // Opening of clusters at various clustering depths
  894. ///////////////////////////////////////////////////////////////
  895. /**
  896. * Check correct opening of a single cluster.
  897. * This is the 'simple' case.
  898. */
  899. it('properly opens 1-level clusters', function () {
  900. var [network, data, numNodes, numEdges] = createSampleNetwork();
  901. // Pedantic: make a cluster of everything
  902. clusterTo(network, 'c1', [1,2,3,4,11, 12, 13, 14]);
  903. // c1(14-13-12-11 1-2-3-4)
  904. numNodes += 1;
  905. assertNumNodes(network, numNodes, 1); // Just the clustering node visible
  906. assertNumEdges(network, numEdges, 0); // No extra edges!
  907. network.clustering.openCluster('c1', {});
  908. numNodes -= 1;
  909. assertNumNodes(network, numNodes, numNodes); // Expecting same as original
  910. assertNumEdges(network, numEdges, numEdges);
  911. // One external connection
  912. [network, data, numNodes, numEdges] = createSampleNetwork();
  913. // 14-13-12-11 1-2-3-4
  914. clusterTo(network, 'c1', [3,4]);
  915. network.clustering.openCluster('c1', {});
  916. assertNumNodes(network, numNodes, numNodes); // Expecting same as original
  917. assertNumEdges(network, numEdges, numEdges);
  918. // Two external connections
  919. clusterTo(network, 'c1', [2,3]);
  920. network.clustering.openCluster('c1', {});
  921. assertNumNodes(network, numNodes, numNodes); // Expecting same as original
  922. assertNumEdges(network, numEdges, numEdges);
  923. // One external connection to cluster
  924. clusterTo(network, 'c1', [1,2]);
  925. clusterTo(network, 'c2', [3,4]);
  926. // 14-13-12-11 c1(1-2-)-c2(-3-4)
  927. network.clustering.openCluster('c1', {});
  928. // 14-13-12-11 1-2-c2(-3-4)
  929. numNodes += 1;
  930. numEdges += 1;
  931. assertNumNodes(network, numNodes, numNodes - 2);
  932. assertNumEdges(network, numEdges, numEdges - 2);
  933. // two external connections to clusters
  934. [network, data, numNodes, numEdges] = createSampleNetwork();
  935. data.edges.update({
  936. from: 1,
  937. to: 11,
  938. });
  939. numEdges += 1;
  940. assertNumNodes(network, numNodes, numNodes);
  941. assertNumEdges(network, numEdges, numEdges);
  942. clusterTo(network, 'c1', [1,2]);
  943. // 14-13-12-11-c1(-1-2-)-3-4
  944. numNodes += 1;
  945. numEdges += 2;
  946. clusterTo(network, 'c2', [3,4]);
  947. // 14-13-12-11-c1(-1-2-)-c2(-3-4)
  948. // NOTE: clustering edges are hidden by clustering here!
  949. numNodes += 1;
  950. numEdges += 1;
  951. clusterTo(network, 'c3', [11,12]);
  952. // 14-13-c3(-12-11-)-c1(-1-2-)-c2(-3-4)
  953. numNodes += 1;
  954. numEdges += 2;
  955. assertNumNodes(network, numNodes, numNodes - 6);
  956. assertNumEdges(network, numEdges, numEdges - 8); // 6 regular edges hidden; also 2 clustering!!!!!
  957. network.clustering.openCluster('c1', {});
  958. numNodes -= 1;
  959. numEdges -= 2;
  960. // 14-13-c3(-12-11-)-1-2-c2(-3-4)
  961. assertNumNodes(network, numNodes, numNodes - 4);
  962. assertNumEdges(network, numEdges, numEdges - 5);
  963. });
  964. /**
  965. * Check correct opening of nested clusters.
  966. * The test uses clustering three levels deep and opens the middle one.
  967. */
  968. it('properly opens clustered clusters', function () {
  969. var [network, data, numNodes, numEdges] = createSampleNetwork();
  970. data.edges.update({from: 1, to: 11,});
  971. numEdges += 1;
  972. clusterTo(network, 'c1', [3,4]);
  973. clusterTo(network, 'c2', [2,'c1']);
  974. clusterTo(network, 'c3', [1,'c2']);
  975. // Attempt at visualization: parentheses belong to the cluster one level above
  976. // -c3
  977. // ( -c2 )
  978. // ( -c1 )
  979. // 14-13-12-11 -1 -2 (-3-4)
  980. numNodes += 3;
  981. numEdges += 3;
  982. //console.log("numNodes: " + numNodes + "; numEdges: " + numEdges);
  983. assertNumNodes(network, numNodes, numNodes - 6);
  984. assertNumEdges(network, numEdges, numEdges - 6);
  985. // Open the middle cluster
  986. network.clustering.openCluster('c2', {});
  987. // -c3
  988. // ( -c1 )
  989. // 14-13-12-11 -1 -2 (-3-4)
  990. numNodes -= 1;
  991. numEdges -= 1;
  992. assertNumNodes(network, numNodes, numNodes - 5);
  993. assertNumEdges(network, numEdges, numEdges - 5);
  994. //
  995. // Same, with one external connection to cluster
  996. //
  997. var [network, data, numNodes, numEdges] = createSampleNetwork();
  998. data.edges.update({from: 1, to: 11,});
  999. data.edges.update({from: 2, to: 12,});
  1000. numEdges += 2;
  1001. // 14-13-12-11-1-2-3-4
  1002. // |------|
  1003. assertNumNodes(network, numNodes);
  1004. assertNumEdges(network, numEdges);
  1005. clusterTo(network, 'c0', [11,12]);
  1006. clusterTo(network, 'c1', [3,4]);
  1007. clusterTo(network, 'c2', [2,'c1']);
  1008. clusterTo(network, 'c3', [1,'c2']);
  1009. // +----------------+
  1010. // | c3 |
  1011. // | +----------+ |
  1012. // | | c2 | |
  1013. // +-------+ | | +----+ | |
  1014. // | c0 | | | | c1 | | |
  1015. // 14-13-|-12-11-|-|-1-|-2-|-3-4| | |
  1016. // | | | | | | +----+ | |
  1017. // +-------+ | | | | |
  1018. // | | +----------+ |
  1019. // | | | |
  1020. // | +----------------+
  1021. // |------------|
  1022. // (I)
  1023. numNodes += 4;
  1024. numEdges = 15;
  1025. assertNumNodes(network, numNodes, 4);
  1026. assertNumEdges(network, numEdges, 3); // (I) link 2-12 is combined into cluster edge for 11-1
  1027. // Open the middle cluster
  1028. network.clustering.openCluster('c2', {});
  1029. // +--------------+
  1030. // | c3 |
  1031. // | |
  1032. // +-------+ | +----+ |
  1033. // | c0 | | | c1 | |
  1034. // 14-13-|-12-11-|-|-1--2-|-3-4| |
  1035. // | | | | | +----+ |
  1036. // +-------+ | | |
  1037. // | | | |
  1038. // | +--------------+
  1039. // |-----------|
  1040. // (I)
  1041. numNodes -= 1;
  1042. numEdges -= 2;
  1043. assertNumNodes(network, numNodes, 4); // visibility doesn't change, cluster opened within cluster
  1044. assertNumEdges(network, numEdges, 3); // (I)
  1045. // Open the top cluster
  1046. network.clustering.openCluster('c3', {});
  1047. //
  1048. // +-------+ +----+
  1049. // | c0 | | c1 |
  1050. // 14-13-|-12-11-|-1-2-|-3-4|
  1051. // | | | | +----+
  1052. // +-------+ |
  1053. // | |
  1054. // |--------|
  1055. // (II)
  1056. numNodes -= 1;
  1057. numEdges = 12;
  1058. assertNumNodes(network, numNodes, 6); // visibility doesn't change, cluster opened within cluster
  1059. assertNumEdges(network, numEdges, 6); // (II) link 2-12 visible again
  1060. });
  1061. }); // Clustering
  1062. describe('on node.js', function () {
  1063. it('should be running', function () {
  1064. assert(this.container !== null, 'Container div not found');
  1065. // The following should now just plain succeed
  1066. var [network, data] = createSampleNetwork();
  1067. assert.equal(Object.keys(network.body.nodes).length, 8);
  1068. assert.equal(Object.keys(network.body.edges).length, 6);
  1069. });
  1070. describe('runs example ', function () {
  1071. function loadExample(path, noPhysics) {
  1072. include(path, this);
  1073. var container = document.getElementById('mynetwork');
  1074. // create a network
  1075. var data = {
  1076. nodes: new vis.DataSet(nodes),
  1077. edges: new vis.DataSet(edges)
  1078. };
  1079. if (noPhysics) {
  1080. // Avoid excessive processor time due to load.
  1081. // We're just interested that the load itself is good
  1082. options.physics = false;
  1083. }
  1084. var network = new vis.Network(container, data, options);
  1085. return network;
  1086. };
  1087. it('basicUsage', function () {
  1088. var network = loadExample('./test/network/basicUsage.js');
  1089. //console.log(Object.keys(network.body.edges));
  1090. // Count in following also contains the helper nodes for dynamic edges
  1091. assert.equal(Object.keys(network.body.nodes).length, 10);
  1092. assert.equal(Object.keys(network.body.edges).length, 5);
  1093. });
  1094. it('WorlCup2014', function (done) {
  1095. // This is a huge example (which is why it's tested here!), so it takes a long time to load.
  1096. this.timeout(15000);
  1097. var network = loadExample('./examples/network/datasources/WorldCup2014.js', true);
  1098. // Count in following also contains the helper nodes for dynamic edges
  1099. assert.equal(Object.keys(network.body.nodes).length, 9964);
  1100. assert.equal(Object.keys(network.body.edges).length, 9228);
  1101. done();
  1102. });
  1103. // This actually failed to load, added for this reason
  1104. it('disassemblerExample', function () {
  1105. var network = loadExample('./examples/network/exampleApplications/disassemblerExample.js');
  1106. // console.log(Object.keys(network.body.nodes));
  1107. // console.log(Object.keys(network.body.edges));
  1108. // Count in following also contains the helper nodes for dynamic edges
  1109. assert.equal(Object.keys(network.body.nodes).length, 9);
  1110. assert.equal(Object.keys(network.body.edges).length, 14 - 3); // NB 3 edges in data not displayed
  1111. });
  1112. }); // runs example
  1113. }); // on node.js
  1114. }); // Network