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.

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