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.

1447 lines
46 KiB

9 years ago
  1. /* ===========================================================================
  2. # TODO
  3. - `edgeReplacedById` not cleaned up yet on cluster edge removal
  4. - allowSingleNodeCluster could be a global option as well; currently needs to always
  5. be passed to clustering methods
  6. ----------------------------------------------
  7. # State Model for Clustering
  8. The total state for clustering is non-trivial. It is useful to have a model
  9. available as to how it works. The following documents the relevant state items.
  10. ## Network State
  11. The following `network`-members are relevant to clustering:
  12. - `body.nodes` - all nodes actively participating in the network
  13. - `body.edges` - same for edges
  14. - `body.nodeIndices` - id's of nodes that are visible at a given moment
  15. - `body.edgeIndices` - same for edges
  16. This includes:
  17. - helper nodes for dragging in `manipulation`
  18. - helper nodes for edge type `dynamic`
  19. - cluster nodes and edges
  20. - there may be more than this.
  21. A node/edge may be missing in the `Indices` member if:
  22. - it is a helper node
  23. - the node or edge state has option `hidden` set
  24. - It is not visible due to clustering
  25. ## Clustering State
  26. For the hashes, the id's of the nodes/edges are used as key.
  27. Member `network.clustering` contains the following items:
  28. - `clusteredNodes` - hash with values: { clusterId: <id of cluster>, node: <node instance>}
  29. - `clusteredEdges` - hash with values: restore information for given edge
  30. Due to nesting of clusters, these members can contain cluster nodes and edges as well.
  31. The important thing to note here, is that the clustered nodes and edges also
  32. appear in the members of the cluster nodes. For data update, it is therefore
  33. important to scan these lists as well as the cluster nodes.
  34. ### Cluster Node
  35. A cluster node has the following extra fields:
  36. - `isCluster : true` - indication that this is a cluster node
  37. - `containedNodes` - hash of nodes contained in this cluster
  38. - `containedEdges` - same for edges
  39. - `edges` - array of cluster edges for this node
  40. **NOTE:**
  41. - `containedEdges` can also contain edges which are not clustered; e.g. an edge
  42. connecting two nodes in the same cluster.
  43. ### Cluster Edge
  44. These are the items in the `edges` member of a clustered node. They have the
  45. following relevant members:
  46. - 'clusteringEdgeReplacingIds` - array of id's of edges replaced by this edge
  47. Note that it's possible to nest clusters, so that `clusteringEdgeReplacingIds`
  48. can contain edge id's of other clusters.
  49. ### Clustered Edge
  50. This is any edge contained by a cluster edge. It gets the following additional
  51. member:
  52. - `edgeReplacedById` - id of the cluster edge in which current edge is clustered
  53. =========================================================================== */
  54. let util = require("../../util");
  55. var NetworkUtil = require('../NetworkUtil').default;
  56. var Cluster = require('./components/nodes/Cluster').default;
  57. var Edge = require('./components/Edge').default; // Only needed for check on type!
  58. var Node = require('./components/Node').default; // Only needed for check on type!
  59. /**
  60. * The clustering engine
  61. */
  62. class ClusterEngine {
  63. /**
  64. * @param {Object} body
  65. */
  66. constructor(body) {
  67. this.body = body;
  68. this.clusteredNodes = {}; // key: node id, value: { clusterId: <id of cluster>, node: <node instance>}
  69. this.clusteredEdges = {}; // key: edge id, value: restore information for given edge
  70. this.options = {};
  71. this.defaultOptions = {};
  72. util.extend(this.options, this.defaultOptions);
  73. this.body.emitter.on('_resetData', () => {this.clusteredNodes = {}; this.clusteredEdges = {};})
  74. }
  75. /**
  76. *
  77. * @param {number} hubsize
  78. * @param {Object} options
  79. */
  80. clusterByHubsize(hubsize, options) {
  81. if (hubsize === undefined) {
  82. hubsize = this._getHubSize();
  83. }
  84. else if (typeof(hubsize) === "object") {
  85. options = this._checkOptions(hubsize);
  86. hubsize = this._getHubSize();
  87. }
  88. let nodesToCluster = [];
  89. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  90. let node = this.body.nodes[this.body.nodeIndices[i]];
  91. if (node.edges.length >= hubsize) {
  92. nodesToCluster.push(node.id);
  93. }
  94. }
  95. for (let i = 0; i < nodesToCluster.length; i++) {
  96. this.clusterByConnection(nodesToCluster[i],options,true);
  97. }
  98. this.body.emitter.emit('_dataChanged');
  99. }
  100. /**
  101. * loop over all nodes, check if they adhere to the condition and cluster if needed.
  102. * @param {Object} options
  103. * @param {boolean} [refreshData=true]
  104. */
  105. cluster(options = {}, refreshData = true) {
  106. if (options.joinCondition === undefined) {throw new Error("Cannot call clusterByNodeData without a joinCondition function in the options.");}
  107. // check if the options object is fine, append if needed
  108. options = this._checkOptions(options);
  109. let childNodesObj = {};
  110. let childEdgesObj = {};
  111. // collect the nodes that will be in the cluster
  112. util.forEach(this.body.nodes, (node, nodeId) => {
  113. let clonedOptions = NetworkUtil.cloneOptions(node);
  114. if (options.joinCondition(clonedOptions) === true) {
  115. childNodesObj[nodeId] = node;
  116. // collect the edges that will be in the cluster
  117. util.forEach(node.edges, (edge) => {
  118. if (this.clusteredEdges[edge.id] === undefined) {
  119. childEdgesObj[edge.id] = edge;
  120. }
  121. });
  122. }
  123. });
  124. this._cluster(childNodesObj, childEdgesObj, options, refreshData);
  125. }
  126. /**
  127. * Cluster all nodes in the network that have only X edges
  128. * @param {number} edgeCount
  129. * @param {Object} options
  130. * @param {boolean} [refreshData=true]
  131. */
  132. clusterByEdgeCount(edgeCount, options, refreshData = true) {
  133. options = this._checkOptions(options);
  134. let clusters = [];
  135. let usedNodes = {};
  136. let edge, edges, relevantEdgeCount;
  137. // collect the nodes that will be in the cluster
  138. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  139. let childNodesObj = {};
  140. let childEdgesObj = {};
  141. let nodeId = this.body.nodeIndices[i];
  142. let node = this.body.nodes[nodeId];
  143. // if this node is already used in another cluster this session, we do not have to re-evaluate it.
  144. if (usedNodes[nodeId] === undefined) {
  145. relevantEdgeCount = 0;
  146. edges = [];
  147. for (let j = 0; j < node.edges.length; j++) {
  148. edge = node.edges[j];
  149. if (this.clusteredEdges[edge.id] === undefined) {
  150. if (edge.toId !== edge.fromId) {
  151. relevantEdgeCount++;
  152. }
  153. edges.push(edge);
  154. }
  155. }
  156. // this node qualifies, we collect its neighbours to start the clustering process.
  157. if (relevantEdgeCount === edgeCount) {
  158. var checkJoinCondition = function(node) {
  159. if (options.joinCondition === undefined || options.joinCondition === null) {
  160. return true;
  161. }
  162. let clonedOptions = NetworkUtil.cloneOptions(node);
  163. return options.joinCondition(clonedOptions);
  164. }
  165. let gatheringSuccessful = true;
  166. for (let j = 0; j < edges.length; j++) {
  167. edge = edges[j];
  168. let childNodeId = this._getConnectedId(edge, nodeId);
  169. // add the nodes to the list by the join condition.
  170. if (checkJoinCondition(node)) {
  171. childEdgesObj[edge.id] = edge;
  172. childNodesObj[nodeId] = node;
  173. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  174. usedNodes[nodeId] = true;
  175. } else {
  176. // this node does not qualify after all.
  177. gatheringSuccessful = false;
  178. break;
  179. }
  180. }
  181. // add to the cluster queue
  182. if (Object.keys(childNodesObj).length > 0 && Object.keys(childEdgesObj).length > 0 && gatheringSuccessful === true) {
  183. /**
  184. * Search for cluster data that contains any of the node id's
  185. * @returns {Boolean} true if no joinCondition, otherwise return value of joinCondition
  186. */
  187. var findClusterData = function() {
  188. for (let n = 0; n < clusters.length; ++n) {
  189. // Search for a cluster containing any of the node id's
  190. for (var m in childNodesObj) {
  191. if (clusters[n].nodes[m] !== undefined) {
  192. return clusters[n];
  193. }
  194. }
  195. }
  196. return undefined;
  197. };
  198. // If any of the found nodes is part of a cluster found in this method,
  199. // add the current values to that cluster
  200. var foundCluster = findClusterData();
  201. if (foundCluster !== undefined) {
  202. // Add nodes to found cluster if not present
  203. for (let m in childNodesObj) {
  204. if (foundCluster.nodes[m] === undefined) {
  205. foundCluster.nodes[m] = childNodesObj[m];
  206. }
  207. }
  208. // Add edges to found cluster, if not present
  209. for (let m in childEdgesObj) {
  210. if (foundCluster.edges[m] === undefined) {
  211. foundCluster.edges[m] = childEdgesObj[m];
  212. }
  213. }
  214. } else {
  215. // Create a new cluster group
  216. clusters.push({nodes: childNodesObj, edges: childEdgesObj})
  217. }
  218. }
  219. }
  220. }
  221. }
  222. for (let i = 0; i < clusters.length; i++) {
  223. this._cluster(clusters[i].nodes, clusters[i].edges, options, false)
  224. }
  225. if (refreshData === true) {
  226. this.body.emitter.emit('_dataChanged');
  227. }
  228. }
  229. /**
  230. * Cluster all nodes in the network that have only 1 edge
  231. * @param {Object} options
  232. * @param {boolean} [refreshData=true]
  233. */
  234. clusterOutliers(options, refreshData = true) {
  235. this.clusterByEdgeCount(1,options,refreshData);
  236. }
  237. /**
  238. * Cluster all nodes in the network that have only 2 edge
  239. * @param {Object} options
  240. * @param {boolean} [refreshData=true]
  241. */
  242. clusterBridges(options, refreshData = true) {
  243. this.clusterByEdgeCount(2,options,refreshData);
  244. }
  245. /**
  246. * suck all connected nodes of a node into the node.
  247. * @param {Node.id} nodeId
  248. * @param {Object} options
  249. * @param {boolean} [refreshData=true]
  250. */
  251. clusterByConnection(nodeId, options, refreshData = true) {
  252. // kill conditions
  253. if (nodeId === undefined) {throw new Error("No nodeId supplied to clusterByConnection!");}
  254. if (this.body.nodes[nodeId] === undefined) {throw new Error("The nodeId given to clusterByConnection does not exist!");}
  255. let node = this.body.nodes[nodeId];
  256. options = this._checkOptions(options, node);
  257. if (options.clusterNodeProperties.x === undefined) {options.clusterNodeProperties.x = node.x;}
  258. if (options.clusterNodeProperties.y === undefined) {options.clusterNodeProperties.y = node.y;}
  259. if (options.clusterNodeProperties.fixed === undefined) {
  260. options.clusterNodeProperties.fixed = {};
  261. options.clusterNodeProperties.fixed.x = node.options.fixed.x;
  262. options.clusterNodeProperties.fixed.y = node.options.fixed.y;
  263. }
  264. let childNodesObj = {};
  265. let childEdgesObj = {};
  266. let parentNodeId = node.id;
  267. let parentClonedOptions = NetworkUtil.cloneOptions(node);
  268. childNodesObj[parentNodeId] = node;
  269. // collect the nodes that will be in the cluster
  270. for (let i = 0; i < node.edges.length; i++) {
  271. let edge = node.edges[i];
  272. if (this.clusteredEdges[edge.id] === undefined) {
  273. let childNodeId = this._getConnectedId(edge, parentNodeId);
  274. // if the child node is not in a cluster
  275. if (this.clusteredNodes[childNodeId] === undefined) {
  276. if (childNodeId !== parentNodeId) {
  277. if (options.joinCondition === undefined) {
  278. childEdgesObj[edge.id] = edge;
  279. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  280. }
  281. else {
  282. // clone the options and insert some additional parameters that could be interesting.
  283. let childClonedOptions = NetworkUtil.cloneOptions(this.body.nodes[childNodeId]);
  284. if (options.joinCondition(parentClonedOptions, childClonedOptions) === true) {
  285. childEdgesObj[edge.id] = edge;
  286. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  287. }
  288. }
  289. }
  290. else {
  291. // swallow the edge if it is self-referencing.
  292. childEdgesObj[edge.id] = edge;
  293. }
  294. }
  295. }
  296. }
  297. var childNodeIDs = Object.keys(childNodesObj).map(function(childNode){
  298. return childNodesObj[childNode].id;
  299. })
  300. for (childNode in childNodesObj) {
  301. if (!childNodesObj.hasOwnProperty(childNode)) continue;
  302. var childNode = childNodesObj[childNode];
  303. for (var y=0; y < childNode.edges.length; y++){
  304. var childEdge = childNode.edges[y];
  305. if (childNodeIDs.indexOf(this._getConnectedId(childEdge,childNode.id)) > -1){
  306. childEdgesObj[childEdge.id] = childEdge;
  307. }
  308. }
  309. }
  310. this._cluster(childNodesObj, childEdgesObj, options, refreshData);
  311. }
  312. /**
  313. * This function creates the edges that will be attached to the cluster
  314. * It looks for edges that are connected to the nodes from the "outside' of the cluster.
  315. *
  316. * @param {{Node.id: vis.Node}} childNodesObj
  317. * @param {{vis.Edge.id: vis.Edge}} childEdgesObj
  318. * @param {Object} clusterNodeProperties
  319. * @param {Object} clusterEdgeProperties
  320. * @private
  321. */
  322. _createClusterEdges (childNodesObj, childEdgesObj, clusterNodeProperties, clusterEdgeProperties) {
  323. let edge, childNodeId, childNode, toId, fromId, otherNodeId;
  324. // loop over all child nodes and their edges to find edges going out of the cluster
  325. // these edges will be replaced by clusterEdges.
  326. let childKeys = Object.keys(childNodesObj);
  327. let createEdges = [];
  328. for (let i = 0; i < childKeys.length; i++) {
  329. childNodeId = childKeys[i];
  330. childNode = childNodesObj[childNodeId];
  331. // construct new edges from the cluster to others
  332. for (let j = 0; j < childNode.edges.length; j++) {
  333. edge = childNode.edges[j];
  334. // we only handle edges that are visible to the system, not the disabled ones from the clustering process.
  335. if (this.clusteredEdges[edge.id] === undefined) {
  336. // self-referencing edges will be added to the "hidden" list
  337. if (edge.toId == edge.fromId) {
  338. childEdgesObj[edge.id] = edge;
  339. }
  340. else {
  341. // set up the from and to.
  342. if (edge.toId == childNodeId) { // this is a double equals because ints and strings can be interchanged here.
  343. toId = clusterNodeProperties.id;
  344. fromId = edge.fromId;
  345. otherNodeId = fromId;
  346. }
  347. else {
  348. toId = edge.toId;
  349. fromId = clusterNodeProperties.id;
  350. otherNodeId = toId;
  351. }
  352. }
  353. // Only edges from the cluster outwards are being replaced.
  354. if (childNodesObj[otherNodeId] === undefined) {
  355. createEdges.push({edge: edge, fromId: fromId, toId: toId});
  356. }
  357. }
  358. }
  359. }
  360. //
  361. // Here we actually create the replacement edges.
  362. //
  363. // We could not do this in the loop above as the creation process
  364. // would add an edge to the edges array we are iterating over.
  365. //
  366. // NOTE: a clustered edge can have multiple base edges!
  367. //
  368. var newEdges = [];
  369. /**
  370. * Find a cluster edge which matches the given created edge.
  371. * @param {vis.Edge} createdEdge
  372. * @returns {vis.Edge}
  373. */
  374. var getNewEdge = function(createdEdge) {
  375. for (let j = 0; j < newEdges.length; j++) {
  376. let newEdge = newEdges[j];
  377. // We replace both to and from edges with a single cluster edge
  378. let matchToDirection = (createdEdge.fromId === newEdge.fromId && createdEdge.toId === newEdge.toId);
  379. let matchFromDirection = (createdEdge.fromId === newEdge.toId && createdEdge.toId === newEdge.fromId);
  380. if (matchToDirection || matchFromDirection ) {
  381. return newEdge;
  382. }
  383. }
  384. return null;
  385. };
  386. for (let j = 0; j < createEdges.length; j++) {
  387. let createdEdge = createEdges[j];
  388. let edge = createdEdge.edge;
  389. let newEdge = getNewEdge(createdEdge);
  390. if (newEdge === null) {
  391. // Create a clustered edge for this connection
  392. newEdge = this._createClusteredEdge(
  393. createdEdge.fromId,
  394. createdEdge.toId,
  395. edge,
  396. clusterEdgeProperties);
  397. newEdges.push(newEdge);
  398. } else {
  399. newEdge.clusteringEdgeReplacingIds.push(edge.id);
  400. }
  401. // also reference the new edge in the old edge
  402. this.body.edges[edge.id].edgeReplacedById = newEdge.id;
  403. // hide the replaced edge
  404. this._backupEdgeOptions(edge);
  405. edge.setOptions({physics:false});
  406. }
  407. }
  408. /**
  409. * This function checks the options that can be supplied to the different cluster functions
  410. * for certain fields and inserts defaults if needed
  411. * @param {Object} options
  412. * @returns {*}
  413. * @private
  414. */
  415. _checkOptions(options = {}) {
  416. if (options.clusterEdgeProperties === undefined) {options.clusterEdgeProperties = {};}
  417. if (options.clusterNodeProperties === undefined) {options.clusterNodeProperties = {};}
  418. return options;
  419. }
  420. /**
  421. *
  422. * @param {Object} childNodesObj | object with node objects, id as keys, same as childNodes except it also contains a source node
  423. * @param {Object} childEdgesObj | object with edge objects, id as keys
  424. * @param {Array} options | object with {clusterNodeProperties, clusterEdgeProperties, processProperties}
  425. * @param {boolean} refreshData | when true, do not wrap up
  426. * @private
  427. */
  428. _cluster(childNodesObj, childEdgesObj, options, refreshData = true) {
  429. // Remove nodes which are already clustered
  430. var tmpNodesToRemove = []
  431. for (let nodeId in childNodesObj) {
  432. if (childNodesObj.hasOwnProperty(nodeId)) {
  433. if (this.clusteredNodes[nodeId] !== undefined) {
  434. tmpNodesToRemove.push(nodeId);
  435. }
  436. }
  437. }
  438. for (var n = 0; n < tmpNodesToRemove.length; ++n) {
  439. delete childNodesObj[tmpNodesToRemove[n]];
  440. }
  441. // kill condition: no nodes don't bother
  442. if (Object.keys(childNodesObj).length == 0) {return;}
  443. // allow clusters of 1 if options allow
  444. if (Object.keys(childNodesObj).length == 1 && options.clusterNodeProperties.allowSingleNodeCluster != true) {return;}
  445. let clusterNodeProperties = util.deepExtend({},options.clusterNodeProperties);
  446. // construct the clusterNodeProperties
  447. if (options.processProperties !== undefined) {
  448. // get the childNode options
  449. let childNodesOptions = [];
  450. for (let nodeId in childNodesObj) {
  451. if (childNodesObj.hasOwnProperty(nodeId)) {
  452. let clonedOptions = NetworkUtil.cloneOptions(childNodesObj[nodeId]);
  453. childNodesOptions.push(clonedOptions);
  454. }
  455. }
  456. // get cluster properties based on childNodes
  457. let childEdgesOptions = [];
  458. for (let edgeId in childEdgesObj) {
  459. if (childEdgesObj.hasOwnProperty(edgeId)) {
  460. // these cluster edges will be removed on creation of the cluster.
  461. if (edgeId.substr(0, 12) !== "clusterEdge:") {
  462. let clonedOptions = NetworkUtil.cloneOptions(childEdgesObj[edgeId], 'edge');
  463. childEdgesOptions.push(clonedOptions);
  464. }
  465. }
  466. }
  467. clusterNodeProperties = options.processProperties(clusterNodeProperties, childNodesOptions, childEdgesOptions);
  468. if (!clusterNodeProperties) {
  469. throw new Error("The processProperties function does not return properties!");
  470. }
  471. }
  472. // check if we have an unique id;
  473. if (clusterNodeProperties.id === undefined) {clusterNodeProperties.id = 'cluster:' + util.randomUUID();}
  474. let clusterId = clusterNodeProperties.id;
  475. if (clusterNodeProperties.label === undefined) {
  476. clusterNodeProperties.label = 'cluster';
  477. }
  478. // give the clusterNode a position if it does not have one.
  479. let pos = undefined;
  480. if (clusterNodeProperties.x === undefined) {
  481. pos = this._getClusterPosition(childNodesObj);
  482. clusterNodeProperties.x = pos.x;
  483. }
  484. if (clusterNodeProperties.y === undefined) {
  485. if (pos === undefined) {pos = this._getClusterPosition(childNodesObj);}
  486. clusterNodeProperties.y = pos.y;
  487. }
  488. // force the ID to remain the same
  489. clusterNodeProperties.id = clusterId;
  490. // create the cluster Node
  491. // Note that allowSingleNodeCluster, if present, is stored in the options as well
  492. let clusterNode = this.body.functions.createNode(clusterNodeProperties, Cluster);
  493. clusterNode.containedNodes = childNodesObj;
  494. clusterNode.containedEdges = childEdgesObj;
  495. // cache a copy from the cluster edge properties if we have to reconnect others later on
  496. clusterNode.clusterEdgeProperties = options.clusterEdgeProperties;
  497. // finally put the cluster node into global
  498. this.body.nodes[clusterNodeProperties.id] = clusterNode;
  499. this._clusterEdges(childNodesObj, childEdgesObj, clusterNodeProperties, options.clusterEdgeProperties);
  500. // set ID to undefined so no duplicates arise
  501. clusterNodeProperties.id = undefined;
  502. // wrap up
  503. if (refreshData === true) {
  504. this.body.emitter.emit('_dataChanged');
  505. }
  506. }
  507. /**
  508. *
  509. * @param {Edge} edge
  510. * @private
  511. */
  512. _backupEdgeOptions(edge) {
  513. if (this.clusteredEdges[edge.id] === undefined) {
  514. this.clusteredEdges[edge.id] = {physics: edge.options.physics};
  515. }
  516. }
  517. /**
  518. *
  519. * @param {Edge} edge
  520. * @private
  521. */
  522. _restoreEdge(edge) {
  523. let originalOptions = this.clusteredEdges[edge.id];
  524. if (originalOptions !== undefined) {
  525. edge.setOptions({physics: originalOptions.physics});
  526. delete this.clusteredEdges[edge.id];
  527. }
  528. }
  529. /**
  530. * Check if a node is a cluster.
  531. * @param {Node.id} nodeId
  532. * @returns {*}
  533. */
  534. isCluster(nodeId) {
  535. if (this.body.nodes[nodeId] !== undefined) {
  536. return this.body.nodes[nodeId].isCluster === true;
  537. }
  538. else {
  539. console.log("Node does not exist.");
  540. return false;
  541. }
  542. }
  543. /**
  544. * get the position of the cluster node based on what's inside
  545. * @param {object} childNodesObj | object with node objects, id as keys
  546. * @returns {{x: number, y: number}}
  547. * @private
  548. */
  549. _getClusterPosition(childNodesObj) {
  550. let childKeys = Object.keys(childNodesObj);
  551. let minX = childNodesObj[childKeys[0]].x;
  552. let maxX = childNodesObj[childKeys[0]].x;
  553. let minY = childNodesObj[childKeys[0]].y;
  554. let maxY = childNodesObj[childKeys[0]].y;
  555. let node;
  556. for (let i = 1; i < childKeys.length; i++) {
  557. node = childNodesObj[childKeys[i]];
  558. minX = node.x < minX ? node.x : minX;
  559. maxX = node.x > maxX ? node.x : maxX;
  560. minY = node.y < minY ? node.y : minY;
  561. maxY = node.y > maxY ? node.y : maxY;
  562. }
  563. return {x: 0.5*(minX + maxX), y: 0.5*(minY + maxY)};
  564. }
  565. /**
  566. * Open a cluster by calling this function.
  567. * @param {vis.Edge.id} clusterNodeId | the ID of the cluster node
  568. * @param {Object} options
  569. * @param {boolean} refreshData | wrap up afterwards if not true
  570. */
  571. openCluster(clusterNodeId, options, refreshData = true) {
  572. // kill conditions
  573. if (clusterNodeId === undefined) {
  574. throw new Error("No clusterNodeId supplied to openCluster.");
  575. }
  576. let clusterNode = this.body.nodes[clusterNodeId];
  577. if (clusterNode === undefined) {
  578. throw new Error("The clusterNodeId supplied to openCluster does not exist.");
  579. }
  580. if (clusterNode.isCluster !== true
  581. || clusterNode.containedNodes === undefined
  582. || clusterNode.containedEdges === undefined) {
  583. throw new Error("The node:" + clusterNodeId + " is not a valid cluster.");
  584. }
  585. // Check if current cluster is clustered itself
  586. let stack = this.findNode(clusterNodeId);
  587. let parentIndex = stack.indexOf(clusterNodeId) - 1;
  588. if (parentIndex >= 0) {
  589. // Current cluster is clustered; transfer contained nodes and edges to parent
  590. let parentClusterNodeId = stack[parentIndex];
  591. let parentClusterNode = this.body.nodes[parentClusterNodeId];
  592. // clustering.clusteredNodes and clustering.clusteredEdges remain unchanged
  593. parentClusterNode._openChildCluster(clusterNodeId);
  594. // All components of child cluster node have been transferred. It can die now.
  595. delete this.body.nodes[clusterNodeId];
  596. if (refreshData === true) {
  597. this.body.emitter.emit('_dataChanged');
  598. }
  599. return;
  600. }
  601. // main body
  602. let containedNodes = clusterNode.containedNodes;
  603. let containedEdges = clusterNode.containedEdges;
  604. // allow the user to position the nodes after release.
  605. if (options !== undefined && options.releaseFunction !== undefined && typeof options.releaseFunction === 'function') {
  606. let positions = {};
  607. let clusterPosition = {x:clusterNode.x, y:clusterNode.y};
  608. for (let nodeId in containedNodes) {
  609. if (containedNodes.hasOwnProperty(nodeId)) {
  610. let containedNode = this.body.nodes[nodeId];
  611. positions[nodeId] = {x: containedNode.x, y: containedNode.y};
  612. }
  613. }
  614. let newPositions = options.releaseFunction(clusterPosition, positions);
  615. for (let nodeId in containedNodes) {
  616. if (containedNodes.hasOwnProperty(nodeId)) {
  617. let containedNode = this.body.nodes[nodeId];
  618. if (newPositions[nodeId] !== undefined) {
  619. containedNode.x = (newPositions[nodeId].x === undefined ? clusterNode.x : newPositions[nodeId].x);
  620. containedNode.y = (newPositions[nodeId].y === undefined ? clusterNode.y : newPositions[nodeId].y);
  621. }
  622. }
  623. }
  624. }
  625. else {
  626. // copy the position from the cluster
  627. util.forEach(containedNodes, function(containedNode) {
  628. // inherit position
  629. if (containedNode.options.fixed.x === false) {containedNode.x = clusterNode.x;}
  630. if (containedNode.options.fixed.y === false) {containedNode.y = clusterNode.y;}
  631. });
  632. }
  633. // release nodes
  634. for (let nodeId in containedNodes) {
  635. if (containedNodes.hasOwnProperty(nodeId)) {
  636. let containedNode = this.body.nodes[nodeId];
  637. // inherit speed
  638. containedNode.vx = clusterNode.vx;
  639. containedNode.vy = clusterNode.vy;
  640. containedNode.setOptions({physics:true});
  641. delete this.clusteredNodes[nodeId];
  642. }
  643. }
  644. // copy the clusterNode edges because we cannot iterate over an object that we add or remove from.
  645. let edgesToBeDeleted = [];
  646. for (let i = 0; i < clusterNode.edges.length; i++) {
  647. edgesToBeDeleted.push(clusterNode.edges[i]);
  648. }
  649. // actually handling the deleting.
  650. for (let i = 0; i < edgesToBeDeleted.length; i++) {
  651. let edge = edgesToBeDeleted[i];
  652. let otherNodeId = this._getConnectedId(edge, clusterNodeId);
  653. let otherNode = this.clusteredNodes[otherNodeId];
  654. for (let j = 0; j < edge.clusteringEdgeReplacingIds.length; j++) {
  655. let transferId = edge.clusteringEdgeReplacingIds[j];
  656. let transferEdge = this.body.edges[transferId];
  657. if (transferEdge === undefined) continue;
  658. // if the other node is in another cluster, we transfer ownership of this edge to the other cluster
  659. if (otherNode !== undefined) {
  660. // transfer ownership:
  661. let otherCluster = this.body.nodes[otherNode.clusterId];
  662. otherCluster.containedEdges[transferEdge.id] = transferEdge;
  663. // delete local reference
  664. delete containedEdges[transferEdge.id];
  665. // get to and from
  666. let fromId = transferEdge.fromId;
  667. let toId = transferEdge.toId;
  668. if (transferEdge.toId == otherNodeId) {
  669. toId = otherNode.clusterId;
  670. }
  671. else {
  672. fromId = otherNode.clusterId;
  673. }
  674. // create new cluster edge from the otherCluster
  675. this._createClusteredEdge(
  676. fromId,
  677. toId,
  678. transferEdge,
  679. otherCluster.clusterEdgeProperties,
  680. {hidden: false, physics: true});
  681. } else {
  682. this._restoreEdge(transferEdge);
  683. }
  684. }
  685. edge.remove();
  686. }
  687. // handle the releasing of the edges
  688. for (let edgeId in containedEdges) {
  689. if (containedEdges.hasOwnProperty(edgeId)) {
  690. this._restoreEdge(containedEdges[edgeId]);
  691. }
  692. }
  693. // remove clusterNode
  694. delete this.body.nodes[clusterNodeId];
  695. if (refreshData === true) {
  696. this.body.emitter.emit('_dataChanged');
  697. }
  698. }
  699. /**
  700. *
  701. * @param {Cluster.id} clusterId
  702. * @returns {Array.<Node.id>}
  703. */
  704. getNodesInCluster(clusterId) {
  705. let nodesArray = [];
  706. if (this.isCluster(clusterId) === true) {
  707. let containedNodes = this.body.nodes[clusterId].containedNodes;
  708. for (let nodeId in containedNodes) {
  709. if (containedNodes.hasOwnProperty(nodeId)) {
  710. nodesArray.push(this.body.nodes[nodeId].id)
  711. }
  712. }
  713. }
  714. return nodesArray;
  715. }
  716. /**
  717. * Get the stack clusterId's that a certain node resides in. cluster A -> cluster B -> cluster C -> node
  718. *
  719. * If a node can't be found in the chain, return an empty array.
  720. *
  721. * @param {string|number} nodeId
  722. * @returns {Array}
  723. */
  724. findNode(nodeId) {
  725. let stack = [];
  726. let max = 100;
  727. let counter = 0;
  728. let node;
  729. while (this.clusteredNodes[nodeId] !== undefined && counter < max) {
  730. node = this.body.nodes[nodeId]
  731. if (node === undefined) return [];
  732. stack.push(node.id);
  733. nodeId = this.clusteredNodes[nodeId].clusterId;
  734. counter++;
  735. }
  736. node = this.body.nodes[nodeId]
  737. if (node === undefined) return [];
  738. stack.push(node.id);
  739. stack.reverse();
  740. return stack;
  741. }
  742. /**
  743. * Using a clustered nodeId, update with the new options
  744. * @param {vis.Edge.id} clusteredNodeId
  745. * @param {object} newOptions
  746. */
  747. updateClusteredNode(clusteredNodeId, newOptions) {
  748. if (clusteredNodeId === undefined) {throw new Error("No clusteredNodeId supplied to updateClusteredNode.");}
  749. if (newOptions === undefined) {throw new Error("No newOptions supplied to updateClusteredNode.");}
  750. if (this.body.nodes[clusteredNodeId] === undefined) {throw new Error("The clusteredNodeId supplied to updateClusteredNode does not exist.");}
  751. this.body.nodes[clusteredNodeId].setOptions(newOptions);
  752. this.body.emitter.emit('_dataChanged');
  753. }
  754. /**
  755. * Using a base edgeId, update all related clustered edges with the new options
  756. * @param {vis.Edge.id} startEdgeId
  757. * @param {object} newOptions
  758. */
  759. updateEdge(startEdgeId, newOptions) {
  760. if (startEdgeId === undefined) {throw new Error("No startEdgeId supplied to updateEdge.");}
  761. if (newOptions === undefined) {throw new Error("No newOptions supplied to updateEdge.");}
  762. if (this.body.edges[startEdgeId] === undefined) {throw new Error("The startEdgeId supplied to updateEdge does not exist.");}
  763. let allEdgeIds = this.getClusteredEdges(startEdgeId);
  764. for (let i = 0; i < allEdgeIds.length; i++) {
  765. var edge = this.body.edges[allEdgeIds[i]];
  766. edge.setOptions(newOptions);
  767. }
  768. this.body.emitter.emit('_dataChanged');
  769. }
  770. /**
  771. * Get a stack of clusterEdgeId's (+base edgeid) that a base edge is the same as. cluster edge C -> cluster edge B -> cluster edge A -> base edge(edgeId)
  772. * @param {vis.Edge.id} edgeId
  773. * @returns {Array.<vis.Edge.id>}
  774. */
  775. getClusteredEdges(edgeId) {
  776. let stack = [];
  777. let max = 100;
  778. let counter = 0;
  779. while (edgeId !== undefined && this.body.edges[edgeId] !== undefined && counter < max) {
  780. stack.push(this.body.edges[edgeId].id);
  781. edgeId = this.body.edges[edgeId].edgeReplacedById;
  782. counter++;
  783. }
  784. stack.reverse();
  785. return stack;
  786. }
  787. /**
  788. * Get the base edge id of clusterEdgeId. cluster edge (clusteredEdgeId) -> cluster edge B -> cluster edge C -> base edge
  789. * @param {vis.Edge.id} clusteredEdgeId
  790. * @returns {vis.Edge.id} baseEdgeId
  791. *
  792. * TODO: deprecate in 5.0.0. Method getBaseEdges() is the correct one to use.
  793. */
  794. getBaseEdge(clusteredEdgeId) {
  795. // Just kludge this by returning the first base edge id found
  796. return this.getBaseEdges(clusteredEdgeId)[0];
  797. }
  798. /**
  799. * Get all regular edges for this clustered edge id.
  800. *
  801. * @param {vis.Edge.id} clusteredEdgeId
  802. * @returns {Array.<vis.Edge.id>} all baseEdgeId's under this clustered edge
  803. */
  804. getBaseEdges(clusteredEdgeId) {
  805. let IdsToHandle = [clusteredEdgeId];
  806. let doneIds = [];
  807. let foundIds = [];
  808. let max = 100;
  809. let counter = 0;
  810. while (IdsToHandle.length > 0 && counter < max) {
  811. let nextId = IdsToHandle.pop();
  812. if (nextId === undefined) continue; // Paranoia here and onwards
  813. let nextEdge = this.body.edges[nextId];
  814. if (nextEdge === undefined) continue;
  815. counter++;
  816. let replacingIds = nextEdge.clusteringEdgeReplacingIds;
  817. if (replacingIds === undefined) {
  818. // nextId is a base id
  819. foundIds.push(nextId);
  820. } else {
  821. // Another cluster edge, unravel this one as well
  822. for (let i = 0; i < replacingIds.length; ++i) {
  823. let replacingId = replacingIds[i];
  824. // Don't add if already handled
  825. // TODO: never triggers; find a test-case which does
  826. if (IdsToHandle.indexOf(replacingIds) !== -1 || doneIds.indexOf(replacingIds) !== -1) {
  827. continue;
  828. }
  829. IdsToHandle.push(replacingId);
  830. }
  831. }
  832. doneIds.push(nextId);
  833. }
  834. return foundIds;
  835. }
  836. /**
  837. * Get the Id the node is connected to
  838. * @param {vis.Edge} edge
  839. * @param {Node.id} nodeId
  840. * @returns {*}
  841. * @private
  842. */
  843. _getConnectedId(edge, nodeId) {
  844. if (edge.toId != nodeId) {
  845. return edge.toId;
  846. }
  847. else if (edge.fromId != nodeId) {
  848. return edge.fromId;
  849. }
  850. else {
  851. return edge.fromId;
  852. }
  853. }
  854. /**
  855. * We determine how many connections denote an important hub.
  856. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  857. *
  858. * @returns {number}
  859. * @private
  860. */
  861. _getHubSize() {
  862. let average = 0;
  863. let averageSquared = 0;
  864. let hubCounter = 0;
  865. let largestHub = 0;
  866. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  867. let node = this.body.nodes[this.body.nodeIndices[i]];
  868. if (node.edges.length > largestHub) {
  869. largestHub = node.edges.length;
  870. }
  871. average += node.edges.length;
  872. averageSquared += Math.pow(node.edges.length,2);
  873. hubCounter += 1;
  874. }
  875. average = average / hubCounter;
  876. averageSquared = averageSquared / hubCounter;
  877. let variance = averageSquared - Math.pow(average,2);
  878. let standardDeviation = Math.sqrt(variance);
  879. let hubThreshold = Math.floor(average + 2*standardDeviation);
  880. // always have at least one to cluster
  881. if (hubThreshold > largestHub) {
  882. hubThreshold = largestHub;
  883. }
  884. return hubThreshold;
  885. }
  886. /**
  887. * Create an edge for the cluster representation.
  888. *
  889. * @param {Node.id} fromId
  890. * @param {Node.id} toId
  891. * @param {vis.Edge} baseEdge
  892. * @param {Object} clusterEdgeProperties
  893. * @param {Object} extraOptions
  894. * @returns {Edge} newly created clustered edge
  895. * @private
  896. */
  897. _createClusteredEdge(fromId, toId, baseEdge, clusterEdgeProperties, extraOptions) {
  898. // copy the options of the edge we will replace
  899. let clonedOptions = NetworkUtil.cloneOptions(baseEdge, 'edge');
  900. // make sure the properties of clusterEdges are superimposed on it
  901. util.deepExtend(clonedOptions, clusterEdgeProperties);
  902. // set up the edge
  903. clonedOptions.from = fromId;
  904. clonedOptions.to = toId;
  905. clonedOptions.id = 'clusterEdge:' + util.randomUUID();
  906. // apply the edge specific options to it if specified
  907. if (extraOptions !== undefined) {
  908. util.deepExtend(clonedOptions, extraOptions);
  909. }
  910. let newEdge = this.body.functions.createEdge(clonedOptions);
  911. newEdge.clusteringEdgeReplacingIds = [baseEdge.id];
  912. newEdge.connect();
  913. // Register the new edge
  914. this.body.edges[newEdge.id] = newEdge;
  915. return newEdge;
  916. }
  917. /**
  918. * Add the passed child nodes and edges to the given cluster node.
  919. *
  920. * @param {Object|Node} childNodes hash of nodes or single node to add in cluster
  921. * @param {Object|Edge} childEdges hash of edges or single edge to take into account when clustering
  922. * @param {Node} clusterNode cluster node to add nodes and edges to
  923. * @param {Object} [clusterEdgeProperties]
  924. * @private
  925. */
  926. _clusterEdges(childNodes, childEdges, clusterNode, clusterEdgeProperties) {
  927. if (childEdges instanceof Edge) {
  928. let edge = childEdges;
  929. let obj = {};
  930. obj[edge.id] = edge;
  931. childEdges = obj;
  932. }
  933. if (childNodes instanceof Node) {
  934. let node = childNodes;
  935. let obj = {};
  936. obj[node.id] = node;
  937. childNodes = obj;
  938. }
  939. if (clusterNode === undefined || clusterNode === null) {
  940. throw new Error("_clusterEdges: parameter clusterNode required");
  941. }
  942. if (clusterEdgeProperties === undefined) {
  943. // Take the required properties from the cluster node
  944. clusterEdgeProperties = clusterNode.clusterEdgeProperties;
  945. }
  946. // create the new edges that will connect to the cluster.
  947. // All self-referencing edges will be added to childEdges here.
  948. this._createClusterEdges(childNodes, childEdges, clusterNode, clusterEdgeProperties);
  949. // disable the childEdges
  950. for (let edgeId in childEdges) {
  951. if (childEdges.hasOwnProperty(edgeId)) {
  952. if (this.body.edges[edgeId] !== undefined) {
  953. let edge = this.body.edges[edgeId];
  954. // cache the options before changing
  955. this._backupEdgeOptions(edge);
  956. // disable physics and hide the edge
  957. edge.setOptions({physics:false});
  958. }
  959. }
  960. }
  961. // disable the childNodes
  962. for (let nodeId in childNodes) {
  963. if (childNodes.hasOwnProperty(nodeId)) {
  964. this.clusteredNodes[nodeId] = {clusterId:clusterNode.id, node: this.body.nodes[nodeId]};
  965. this.body.nodes[nodeId].setOptions({physics:false});
  966. }
  967. }
  968. }
  969. /**
  970. * Determine in which cluster given nodeId resides.
  971. *
  972. * If not in cluster, return undefined.
  973. *
  974. * NOTE: If you know a cleaner way to do this, please enlighten me (wimrijnders).
  975. *
  976. * @param {Node.id} nodeId
  977. * @returns {Node|undefined} Node instance for cluster, if present
  978. * @private
  979. */
  980. _getClusterNodeForNode(nodeId) {
  981. if (nodeId === undefined) return undefined;
  982. let clusteredNode = this.clusteredNodes[nodeId];
  983. // NOTE: If no cluster info found, it should actually be an error
  984. if (clusteredNode === undefined) return undefined;
  985. let clusterId = clusteredNode.clusterId;
  986. if (clusterId === undefined) return undefined;
  987. return this.body.nodes[clusterId];
  988. }
  989. /**
  990. * Internal helper function for conditionally removing items in array
  991. *
  992. * Done like this because Array.filter() is not fully supported by all IE's.
  993. *
  994. * @param {Array} arr
  995. * @param {function} callback
  996. * @returns {Array}
  997. * @private
  998. */
  999. _filter(arr, callback) {
  1000. let ret = [];
  1001. util.forEach(arr, (item) => {
  1002. if (callback(item)) {
  1003. ret.push(item);
  1004. }
  1005. });
  1006. return ret;
  1007. }
  1008. /**
  1009. * Scan all edges for changes in clustering and adjust this if necessary.
  1010. *
  1011. * Call this (internally) after there has been a change in node or edge data.
  1012. *
  1013. * Pre: States of this.body.nodes and this.body.edges consistent
  1014. * Pre: this.clusteredNodes and this.clusteredEdge consistent with containedNodes and containedEdges
  1015. * of cluster nodes.
  1016. */
  1017. _updateState() {
  1018. let nodeId;
  1019. let deletedNodeIds = [];
  1020. let deletedEdgeIds = [];
  1021. /**
  1022. * Utility function to iterate over clustering nodes only
  1023. *
  1024. * @param {Function} callback function to call for each cluster node
  1025. */
  1026. let eachClusterNode = (callback) => {
  1027. util.forEach(this.body.nodes, (node) => {
  1028. if (node.isCluster === true) {
  1029. callback(node);
  1030. }
  1031. });
  1032. };
  1033. //
  1034. // Remove deleted regular nodes from clustering
  1035. //
  1036. // Determine the deleted nodes
  1037. for (nodeId in this.clusteredNodes) {
  1038. if (!this.clusteredNodes.hasOwnProperty(nodeId)) continue;
  1039. let node = this.body.nodes[nodeId];
  1040. if (node === undefined) {
  1041. deletedNodeIds.push(nodeId);
  1042. }
  1043. }
  1044. // Remove nodes from cluster nodes
  1045. eachClusterNode(function(clusterNode) {
  1046. for (let n = 0; n < deletedNodeIds.length; n++) {
  1047. delete clusterNode.containedNodes[deletedNodeIds[n]];
  1048. }
  1049. });
  1050. // Remove nodes from cluster list
  1051. for (let n = 0; n < deletedNodeIds.length; n++) {
  1052. delete this.clusteredNodes[deletedNodeIds[n]];
  1053. }
  1054. //
  1055. // Remove deleted edges from clustering
  1056. //
  1057. // Add the deleted clustered edges to the list
  1058. util.forEach(this.clusteredEdges, (edgeId) => {
  1059. let edge = this.body.edges[edgeId];
  1060. if (edge === undefined || !edge.endPointsValid()) {
  1061. deletedEdgeIds.push(edgeId);
  1062. }
  1063. });
  1064. // Cluster nodes can also contain edges which are not clustered,
  1065. // i.e. nodes 1-2 within cluster with an edge in between.
  1066. // So the cluster nodes also need to be scanned for invalid edges
  1067. eachClusterNode(function(clusterNode) {
  1068. util.forEach(clusterNode.containedEdges, (edge, edgeId) => {
  1069. if (!edge.endPointsValid() && deletedEdgeIds.indexOf(edgeId) === -1) {
  1070. deletedEdgeIds.push(edgeId);
  1071. }
  1072. });
  1073. });
  1074. // Also scan for cluster edges which need to be removed in the active list.
  1075. // Regular edges have been removed beforehand, so this only picks up the cluster edges.
  1076. util.forEach(this.body.edges, (edge, edgeId) => {
  1077. // Explicitly scan the contained edges for validity
  1078. let isValid = true;
  1079. let replacedIds = edge.clusteringEdgeReplacingIds;
  1080. if (replacedIds !== undefined) {
  1081. let numValid = 0;
  1082. util.forEach(replacedIds, (containedEdgeId) => {
  1083. let containedEdge = this.body.edges[containedEdgeId];
  1084. if (containedEdge !== undefined && containedEdge.endPointsValid()) {
  1085. numValid += 1;
  1086. }
  1087. });
  1088. isValid = (numValid > 0);
  1089. }
  1090. if (!edge.endPointsValid() || !isValid) {
  1091. deletedEdgeIds.push(edgeId);
  1092. }
  1093. });
  1094. // Remove edges from cluster nodes
  1095. eachClusterNode((clusterNode) => {
  1096. util.forEach(deletedEdgeIds, (deletedEdgeId) => {
  1097. delete clusterNode.containedEdges[deletedEdgeId];
  1098. util.forEach(clusterNode.edges, (edge, m) => {
  1099. if (edge.id === deletedEdgeId) {
  1100. clusterNode.edges[m] = null; // Don't want to directly delete here, because in the loop
  1101. return;
  1102. }
  1103. edge.clusteringEdgeReplacingIds = this._filter(edge.clusteringEdgeReplacingIds, function(id) {
  1104. return deletedEdgeIds.indexOf(id) === -1;
  1105. });
  1106. });
  1107. // Clean up the nulls
  1108. clusterNode.edges = this._filter(clusterNode.edges, function(item) {return item !== null});
  1109. });
  1110. });
  1111. // Remove from cluster list
  1112. util.forEach(deletedEdgeIds, (edgeId) => {
  1113. delete this.clusteredEdges[edgeId];
  1114. });
  1115. // Remove cluster edges from active list (this.body.edges).
  1116. // deletedEdgeIds still contains id of regular edges, but these should all
  1117. // be gone when you reach here.
  1118. util.forEach(deletedEdgeIds, (edgeId) => {
  1119. delete this.body.edges[edgeId];
  1120. });
  1121. //
  1122. // Check changed cluster state of edges
  1123. //
  1124. // Iterating over keys here, because edges may be removed in the loop
  1125. let ids = Object.keys(this.body.edges);
  1126. util.forEach(ids, (edgeId) => {
  1127. let edge = this.body.edges[edgeId];
  1128. let shouldBeClustered = this._isClusteredNode(edge.fromId) || this._isClusteredNode(edge.toId);
  1129. if (shouldBeClustered === this._isClusteredEdge(edge.id)) {
  1130. return; // all is well
  1131. }
  1132. if (shouldBeClustered) {
  1133. // add edge to clustering
  1134. let clusterFrom = this._getClusterNodeForNode(edge.fromId);
  1135. if (clusterFrom !== undefined) {
  1136. this._clusterEdges(this.body.nodes[edge.fromId], edge, clusterFrom);
  1137. }
  1138. let clusterTo = this._getClusterNodeForNode(edge.toId);
  1139. if (clusterTo !== undefined) {
  1140. this._clusterEdges(this.body.nodes[edge.toId], edge, clusterTo);
  1141. }
  1142. // TODO: check that it works for both edges clustered
  1143. // (This might be paranoia)
  1144. } else {
  1145. // This should not be happening, the state should
  1146. // be properly updated at this point.
  1147. //
  1148. // If it *is* reached during normal operation, then we have to implement
  1149. // undo clustering for this edge here.
  1150. throw new Error('remove edge from clustering not implemented!');
  1151. }
  1152. });
  1153. // Clusters may be nested to any level. Keep on opening until nothing to open
  1154. var changed = false;
  1155. var continueLoop = true;
  1156. while (continueLoop) {
  1157. let clustersToOpen = [];
  1158. // Determine the id's of clusters that need opening
  1159. eachClusterNode(function(clusterNode) {
  1160. let numNodes = Object.keys(clusterNode.containedNodes).length;
  1161. let allowSingle = (clusterNode.options.allowSingleNodeCluster === true);
  1162. if ((allowSingle && numNodes < 1) || (!allowSingle && numNodes < 2)) {
  1163. clustersToOpen.push(clusterNode.id);
  1164. }
  1165. });
  1166. // Open them
  1167. for (let n = 0; n < clustersToOpen.length; ++n) {
  1168. this.openCluster(clustersToOpen[n], {}, false /* Don't refresh, we're in an refresh/update already */);
  1169. }
  1170. continueLoop = (clustersToOpen.length > 0);
  1171. changed = changed || continueLoop;
  1172. }
  1173. if (changed) {
  1174. this._updateState() // Redo this method (recursion possible! should be safe)
  1175. }
  1176. }
  1177. /**
  1178. * Determine if node with given id is part of a cluster.
  1179. *
  1180. * @param {Node.id} nodeId
  1181. * @return {boolean} true if part of a cluster.
  1182. */
  1183. _isClusteredNode(nodeId) {
  1184. return this.clusteredNodes[nodeId] !== undefined;
  1185. }
  1186. /**
  1187. * Determine if edge with given id is not visible due to clustering.
  1188. *
  1189. * An edge is considered clustered if:
  1190. * - it is directly replaced by a clustering edge
  1191. * - any of its connecting nodes is in a cluster
  1192. *
  1193. * @param {vis.Edge.id} edgeId
  1194. * @return {boolean} true if part of a cluster.
  1195. */
  1196. _isClusteredEdge(edgeId) {
  1197. return this.clusteredEdges[edgeId] !== undefined;
  1198. }
  1199. }
  1200. export default ClusterEngine;