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.

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