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.

1442 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. // kill condition: no nodes don't bother
  430. if (Object.keys(childNodesObj).length == 0) {return;}
  431. // allow clusters of 1 if options allow
  432. if (Object.keys(childNodesObj).length == 1 && options.clusterNodeProperties.allowSingleNodeCluster != true) {return;}
  433. // check if this cluster call is not trying to cluster anything that is in another cluster.
  434. for (let nodeId in childNodesObj) {
  435. if (childNodesObj.hasOwnProperty(nodeId)) {
  436. if (this.clusteredNodes[nodeId] !== undefined) {
  437. return;
  438. }
  439. }
  440. }
  441. let clusterNodeProperties = util.deepExtend({},options.clusterNodeProperties);
  442. // construct the clusterNodeProperties
  443. if (options.processProperties !== undefined) {
  444. // get the childNode options
  445. let childNodesOptions = [];
  446. for (let nodeId in childNodesObj) {
  447. if (childNodesObj.hasOwnProperty(nodeId)) {
  448. let clonedOptions = NetworkUtil.cloneOptions(childNodesObj[nodeId]);
  449. childNodesOptions.push(clonedOptions);
  450. }
  451. }
  452. // get cluster properties based on childNodes
  453. let childEdgesOptions = [];
  454. for (let edgeId in childEdgesObj) {
  455. if (childEdgesObj.hasOwnProperty(edgeId)) {
  456. // these cluster edges will be removed on creation of the cluster.
  457. if (edgeId.substr(0, 12) !== "clusterEdge:") {
  458. let clonedOptions = NetworkUtil.cloneOptions(childEdgesObj[edgeId], 'edge');
  459. childEdgesOptions.push(clonedOptions);
  460. }
  461. }
  462. }
  463. clusterNodeProperties = options.processProperties(clusterNodeProperties, childNodesOptions, childEdgesOptions);
  464. if (!clusterNodeProperties) {
  465. throw new Error("The processProperties function does not return properties!");
  466. }
  467. }
  468. // check if we have an unique id;
  469. if (clusterNodeProperties.id === undefined) {clusterNodeProperties.id = 'cluster:' + util.randomUUID();}
  470. let clusterId = clusterNodeProperties.id;
  471. if (clusterNodeProperties.label === undefined) {
  472. clusterNodeProperties.label = 'cluster';
  473. }
  474. // give the clusterNode a position if it does not have one.
  475. let pos = undefined;
  476. if (clusterNodeProperties.x === undefined) {
  477. pos = this._getClusterPosition(childNodesObj);
  478. clusterNodeProperties.x = pos.x;
  479. }
  480. if (clusterNodeProperties.y === undefined) {
  481. if (pos === undefined) {pos = this._getClusterPosition(childNodesObj);}
  482. clusterNodeProperties.y = pos.y;
  483. }
  484. // force the ID to remain the same
  485. clusterNodeProperties.id = clusterId;
  486. // create the cluster Node
  487. // Note that allowSingleNodeCluster, if present, is stored in the options as well
  488. let clusterNode = this.body.functions.createNode(clusterNodeProperties, Cluster);
  489. clusterNode.containedNodes = childNodesObj;
  490. clusterNode.containedEdges = childEdgesObj;
  491. // cache a copy from the cluster edge properties if we have to reconnect others later on
  492. clusterNode.clusterEdgeProperties = options.clusterEdgeProperties;
  493. // finally put the cluster node into global
  494. this.body.nodes[clusterNodeProperties.id] = clusterNode;
  495. this._clusterEdges(childNodesObj, childEdgesObj, clusterNodeProperties, options.clusterEdgeProperties);
  496. // set ID to undefined so no duplicates arise
  497. clusterNodeProperties.id = undefined;
  498. // wrap up
  499. if (refreshData === true) {
  500. this.body.emitter.emit('_dataChanged');
  501. }
  502. }
  503. /**
  504. *
  505. * @param {Edge} edge
  506. * @private
  507. */
  508. _backupEdgeOptions(edge) {
  509. if (this.clusteredEdges[edge.id] === undefined) {
  510. this.clusteredEdges[edge.id] = {physics: edge.options.physics};
  511. }
  512. }
  513. /**
  514. *
  515. * @param {Edge} edge
  516. * @private
  517. */
  518. _restoreEdge(edge) {
  519. let originalOptions = this.clusteredEdges[edge.id];
  520. if (originalOptions !== undefined) {
  521. edge.setOptions({physics: originalOptions.physics});
  522. delete this.clusteredEdges[edge.id];
  523. }
  524. }
  525. /**
  526. * Check if a node is a cluster.
  527. * @param {Node.id} nodeId
  528. * @returns {*}
  529. */
  530. isCluster(nodeId) {
  531. if (this.body.nodes[nodeId] !== undefined) {
  532. return this.body.nodes[nodeId].isCluster === true;
  533. }
  534. else {
  535. console.log("Node does not exist.");
  536. return false;
  537. }
  538. }
  539. /**
  540. * get the position of the cluster node based on what's inside
  541. * @param {object} childNodesObj | object with node objects, id as keys
  542. * @returns {{x: number, y: number}}
  543. * @private
  544. */
  545. _getClusterPosition(childNodesObj) {
  546. let childKeys = Object.keys(childNodesObj);
  547. let minX = childNodesObj[childKeys[0]].x;
  548. let maxX = childNodesObj[childKeys[0]].x;
  549. let minY = childNodesObj[childKeys[0]].y;
  550. let maxY = childNodesObj[childKeys[0]].y;
  551. let node;
  552. for (let i = 1; i < childKeys.length; i++) {
  553. node = childNodesObj[childKeys[i]];
  554. minX = node.x < minX ? node.x : minX;
  555. maxX = node.x > maxX ? node.x : maxX;
  556. minY = node.y < minY ? node.y : minY;
  557. maxY = node.y > maxY ? node.y : maxY;
  558. }
  559. return {x: 0.5*(minX + maxX), y: 0.5*(minY + maxY)};
  560. }
  561. /**
  562. * Open a cluster by calling this function.
  563. * @param {vis.Edge.id} clusterNodeId | the ID of the cluster node
  564. * @param {Object} options
  565. * @param {boolean} refreshData | wrap up afterwards if not true
  566. */
  567. openCluster(clusterNodeId, options, refreshData = true) {
  568. // kill conditions
  569. if (clusterNodeId === undefined) {
  570. throw new Error("No clusterNodeId supplied to openCluster.");
  571. }
  572. let clusterNode = this.body.nodes[clusterNodeId];
  573. if (clusterNode === undefined) {
  574. throw new Error("The clusterNodeId supplied to openCluster does not exist.");
  575. }
  576. if (clusterNode.isCluster !== true
  577. || clusterNode.containedNodes === undefined
  578. || clusterNode.containedEdges === undefined) {
  579. throw new Error("The node:" + clusterNodeId + " is not a valid cluster.");
  580. }
  581. // Check if current cluster is clustered itself
  582. let stack = this.findNode(clusterNodeId);
  583. let parentIndex = stack.indexOf(clusterNodeId) - 1;
  584. if (parentIndex >= 0) {
  585. // Current cluster is clustered; transfer contained nodes and edges to parent
  586. let parentClusterNodeId = stack[parentIndex];
  587. let parentClusterNode = this.body.nodes[parentClusterNodeId];
  588. // clustering.clusteredNodes and clustering.clusteredEdges remain unchanged
  589. parentClusterNode._openChildCluster(clusterNodeId);
  590. // All components of child cluster node have been transferred. It can die now.
  591. delete this.body.nodes[clusterNodeId];
  592. if (refreshData === true) {
  593. this.body.emitter.emit('_dataChanged');
  594. }
  595. return;
  596. }
  597. // main body
  598. let containedNodes = clusterNode.containedNodes;
  599. let containedEdges = clusterNode.containedEdges;
  600. // allow the user to position the nodes after release.
  601. if (options !== undefined && options.releaseFunction !== undefined && typeof options.releaseFunction === 'function') {
  602. let positions = {};
  603. let clusterPosition = {x:clusterNode.x, y:clusterNode.y};
  604. for (let nodeId in containedNodes) {
  605. if (containedNodes.hasOwnProperty(nodeId)) {
  606. let containedNode = this.body.nodes[nodeId];
  607. positions[nodeId] = {x: containedNode.x, y: containedNode.y};
  608. }
  609. }
  610. let newPositions = options.releaseFunction(clusterPosition, positions);
  611. for (let nodeId in containedNodes) {
  612. if (containedNodes.hasOwnProperty(nodeId)) {
  613. let containedNode = this.body.nodes[nodeId];
  614. if (newPositions[nodeId] !== undefined) {
  615. containedNode.x = (newPositions[nodeId].x === undefined ? clusterNode.x : newPositions[nodeId].x);
  616. containedNode.y = (newPositions[nodeId].y === undefined ? clusterNode.y : newPositions[nodeId].y);
  617. }
  618. }
  619. }
  620. }
  621. else {
  622. // copy the position from the cluster
  623. util.forEach(containedNodes, function(containedNode) {
  624. // inherit position
  625. if (containedNode.options.fixed.x === false) {containedNode.x = clusterNode.x;}
  626. if (containedNode.options.fixed.y === false) {containedNode.y = clusterNode.y;}
  627. });
  628. }
  629. // release nodes
  630. for (let nodeId in containedNodes) {
  631. if (containedNodes.hasOwnProperty(nodeId)) {
  632. let containedNode = this.body.nodes[nodeId];
  633. // inherit speed
  634. containedNode.vx = clusterNode.vx;
  635. containedNode.vy = clusterNode.vy;
  636. containedNode.setOptions({physics:true});
  637. delete this.clusteredNodes[nodeId];
  638. }
  639. }
  640. // copy the clusterNode edges because we cannot iterate over an object that we add or remove from.
  641. let edgesToBeDeleted = [];
  642. for (let i = 0; i < clusterNode.edges.length; i++) {
  643. edgesToBeDeleted.push(clusterNode.edges[i]);
  644. }
  645. // actually handling the deleting.
  646. for (let i = 0; i < edgesToBeDeleted.length; i++) {
  647. let edge = edgesToBeDeleted[i];
  648. let otherNodeId = this._getConnectedId(edge, clusterNodeId);
  649. let otherNode = this.clusteredNodes[otherNodeId];
  650. for (let j = 0; j < edge.clusteringEdgeReplacingIds.length; j++) {
  651. let transferId = edge.clusteringEdgeReplacingIds[j];
  652. let transferEdge = this.body.edges[transferId];
  653. if (transferEdge === undefined) continue;
  654. // if the other node is in another cluster, we transfer ownership of this edge to the other cluster
  655. if (otherNode !== undefined) {
  656. // transfer ownership:
  657. let otherCluster = this.body.nodes[otherNode.clusterId];
  658. otherCluster.containedEdges[transferEdge.id] = transferEdge;
  659. // delete local reference
  660. delete containedEdges[transferEdge.id];
  661. // get to and from
  662. let fromId = transferEdge.fromId;
  663. let toId = transferEdge.toId;
  664. if (transferEdge.toId == otherNodeId) {
  665. toId = otherNode.clusterId;
  666. }
  667. else {
  668. fromId = otherNode.clusterId;
  669. }
  670. // create new cluster edge from the otherCluster
  671. this._createClusteredEdge(
  672. fromId,
  673. toId,
  674. transferEdge,
  675. otherCluster.clusterEdgeProperties,
  676. {hidden: false, physics: true});
  677. } else {
  678. this._restoreEdge(transferEdge);
  679. }
  680. }
  681. edge.remove();
  682. }
  683. // handle the releasing of the edges
  684. for (let edgeId in containedEdges) {
  685. if (containedEdges.hasOwnProperty(edgeId)) {
  686. this._restoreEdge(containedEdges[edgeId]);
  687. }
  688. }
  689. // remove clusterNode
  690. delete this.body.nodes[clusterNodeId];
  691. if (refreshData === true) {
  692. this.body.emitter.emit('_dataChanged');
  693. }
  694. }
  695. /**
  696. *
  697. * @param {Cluster.id} clusterId
  698. * @returns {Array.<Node.id>}
  699. */
  700. getNodesInCluster(clusterId) {
  701. let nodesArray = [];
  702. if (this.isCluster(clusterId) === true) {
  703. let containedNodes = this.body.nodes[clusterId].containedNodes;
  704. for (let nodeId in containedNodes) {
  705. if (containedNodes.hasOwnProperty(nodeId)) {
  706. nodesArray.push(this.body.nodes[nodeId].id)
  707. }
  708. }
  709. }
  710. return nodesArray;
  711. }
  712. /**
  713. * Get the stack clusterId's that a certain node resides in. cluster A -> cluster B -> cluster C -> node
  714. *
  715. * If a node can't be found in the chain, return an empty array.
  716. *
  717. * @param {string|number} nodeId
  718. * @returns {Array}
  719. */
  720. findNode(nodeId) {
  721. let stack = [];
  722. let max = 100;
  723. let counter = 0;
  724. let node;
  725. while (this.clusteredNodes[nodeId] !== undefined && counter < max) {
  726. node = this.body.nodes[nodeId]
  727. if (node === undefined) return [];
  728. stack.push(node.id);
  729. nodeId = this.clusteredNodes[nodeId].clusterId;
  730. counter++;
  731. }
  732. node = this.body.nodes[nodeId]
  733. if (node === undefined) return [];
  734. stack.push(node.id);
  735. stack.reverse();
  736. return stack;
  737. }
  738. /**
  739. * Using a clustered nodeId, update with the new options
  740. * @param {vis.Edge.id} clusteredNodeId
  741. * @param {object} newOptions
  742. */
  743. updateClusteredNode(clusteredNodeId, newOptions) {
  744. if (clusteredNodeId === undefined) {throw new Error("No clusteredNodeId supplied to updateClusteredNode.");}
  745. if (newOptions === undefined) {throw new Error("No newOptions supplied to updateClusteredNode.");}
  746. if (this.body.nodes[clusteredNodeId] === undefined) {throw new Error("The clusteredNodeId supplied to updateClusteredNode does not exist.");}
  747. this.body.nodes[clusteredNodeId].setOptions(newOptions);
  748. this.body.emitter.emit('_dataChanged');
  749. }
  750. /**
  751. * Using a base edgeId, update all related clustered edges with the new options
  752. * @param {vis.Edge.id} startEdgeId
  753. * @param {object} newOptions
  754. */
  755. updateEdge(startEdgeId, newOptions) {
  756. if (startEdgeId === undefined) {throw new Error("No startEdgeId supplied to updateEdge.");}
  757. if (newOptions === undefined) {throw new Error("No newOptions supplied to updateEdge.");}
  758. if (this.body.edges[startEdgeId] === undefined) {throw new Error("The startEdgeId supplied to updateEdge does not exist.");}
  759. let allEdgeIds = this.getClusteredEdges(startEdgeId);
  760. for (let i = 0; i < allEdgeIds.length; i++) {
  761. var edge = this.body.edges[allEdgeIds[i]];
  762. edge.setOptions(newOptions);
  763. }
  764. this.body.emitter.emit('_dataChanged');
  765. }
  766. /**
  767. * 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)
  768. * @param {vis.Edge.id} edgeId
  769. * @returns {Array.<vis.Edge.id>}
  770. */
  771. getClusteredEdges(edgeId) {
  772. let stack = [];
  773. let max = 100;
  774. let counter = 0;
  775. while (edgeId !== undefined && this.body.edges[edgeId] !== undefined && counter < max) {
  776. stack.push(this.body.edges[edgeId].id);
  777. edgeId = this.body.edges[edgeId].edgeReplacedById;
  778. counter++;
  779. }
  780. stack.reverse();
  781. return stack;
  782. }
  783. /**
  784. * Get the base edge id of clusterEdgeId. cluster edge (clusteredEdgeId) -> cluster edge B -> cluster edge C -> base edge
  785. * @param {vis.Edge.id} clusteredEdgeId
  786. * @returns {vis.Edge.id} baseEdgeId
  787. *
  788. * TODO: deprecate in 5.0.0. Method getBaseEdges() is the correct one to use.
  789. */
  790. getBaseEdge(clusteredEdgeId) {
  791. // Just kludge this by returning the first base edge id found
  792. return this.getBaseEdges(clusteredEdgeId)[0];
  793. }
  794. /**
  795. * Get all regular edges for this clustered edge id.
  796. *
  797. * @param {vis.Edge.id} clusteredEdgeId
  798. * @returns {Array.<vis.Edge.id>} all baseEdgeId's under this clustered edge
  799. */
  800. getBaseEdges(clusteredEdgeId) {
  801. let IdsToHandle = [clusteredEdgeId];
  802. let doneIds = [];
  803. let foundIds = [];
  804. let max = 100;
  805. let counter = 0;
  806. while (IdsToHandle.length > 0 && counter < max) {
  807. let nextId = IdsToHandle.pop();
  808. if (nextId === undefined) continue; // Paranoia here and onwards
  809. let nextEdge = this.body.edges[nextId];
  810. if (nextEdge === undefined) continue;
  811. counter++;
  812. let replacingIds = nextEdge.clusteringEdgeReplacingIds;
  813. if (replacingIds === undefined) {
  814. // nextId is a base id
  815. foundIds.push(nextId);
  816. } else {
  817. // Another cluster edge, unravel this one as well
  818. for (let i = 0; i < replacingIds.length; ++i) {
  819. let replacingId = replacingIds[i];
  820. // Don't add if already handled
  821. // TODO: never triggers; find a test-case which does
  822. if (IdsToHandle.indexOf(replacingIds) !== -1 || doneIds.indexOf(replacingIds) !== -1) {
  823. continue;
  824. }
  825. IdsToHandle.push(replacingId);
  826. }
  827. }
  828. doneIds.push(nextId);
  829. }
  830. return foundIds;
  831. }
  832. /**
  833. * Get the Id the node is connected to
  834. * @param {vis.Edge} edge
  835. * @param {Node.id} nodeId
  836. * @returns {*}
  837. * @private
  838. */
  839. _getConnectedId(edge, nodeId) {
  840. if (edge.toId != nodeId) {
  841. return edge.toId;
  842. }
  843. else if (edge.fromId != nodeId) {
  844. return edge.fromId;
  845. }
  846. else {
  847. return edge.fromId;
  848. }
  849. }
  850. /**
  851. * We determine how many connections denote an important hub.
  852. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  853. *
  854. * @returns {number}
  855. * @private
  856. */
  857. _getHubSize() {
  858. let average = 0;
  859. let averageSquared = 0;
  860. let hubCounter = 0;
  861. let largestHub = 0;
  862. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  863. let node = this.body.nodes[this.body.nodeIndices[i]];
  864. if (node.edges.length > largestHub) {
  865. largestHub = node.edges.length;
  866. }
  867. average += node.edges.length;
  868. averageSquared += Math.pow(node.edges.length,2);
  869. hubCounter += 1;
  870. }
  871. average = average / hubCounter;
  872. averageSquared = averageSquared / hubCounter;
  873. let variance = averageSquared - Math.pow(average,2);
  874. let standardDeviation = Math.sqrt(variance);
  875. let hubThreshold = Math.floor(average + 2*standardDeviation);
  876. // always have at least one to cluster
  877. if (hubThreshold > largestHub) {
  878. hubThreshold = largestHub;
  879. }
  880. return hubThreshold;
  881. }
  882. /**
  883. * Create an edge for the cluster representation.
  884. *
  885. * @param {Node.id} fromId
  886. * @param {Node.id} toId
  887. * @param {vis.Edge} baseEdge
  888. * @param {Object} clusterEdgeProperties
  889. * @param {Object} extraOptions
  890. * @returns {Edge} newly created clustered edge
  891. * @private
  892. */
  893. _createClusteredEdge(fromId, toId, baseEdge, clusterEdgeProperties, extraOptions) {
  894. // copy the options of the edge we will replace
  895. let clonedOptions = NetworkUtil.cloneOptions(baseEdge, 'edge');
  896. // make sure the properties of clusterEdges are superimposed on it
  897. util.deepExtend(clonedOptions, clusterEdgeProperties);
  898. // set up the edge
  899. clonedOptions.from = fromId;
  900. clonedOptions.to = toId;
  901. clonedOptions.id = 'clusterEdge:' + util.randomUUID();
  902. // apply the edge specific options to it if specified
  903. if (extraOptions !== undefined) {
  904. util.deepExtend(clonedOptions, extraOptions);
  905. }
  906. let newEdge = this.body.functions.createEdge(clonedOptions);
  907. newEdge.clusteringEdgeReplacingIds = [baseEdge.id];
  908. newEdge.connect();
  909. // Register the new edge
  910. this.body.edges[newEdge.id] = newEdge;
  911. return newEdge;
  912. }
  913. /**
  914. * Add the passed child nodes and edges to the given cluster node.
  915. *
  916. * @param {Object|Node} childNodes hash of nodes or single node to add in cluster
  917. * @param {Object|Edge} childEdges hash of edges or single edge to take into account when clustering
  918. * @param {Node} clusterNode cluster node to add nodes and edges to
  919. * @param {Object} [clusterEdgeProperties]
  920. * @private
  921. */
  922. _clusterEdges(childNodes, childEdges, clusterNode, clusterEdgeProperties) {
  923. if (childEdges instanceof Edge) {
  924. let edge = childEdges;
  925. let obj = {};
  926. obj[edge.id] = edge;
  927. childEdges = obj;
  928. }
  929. if (childNodes instanceof Node) {
  930. let node = childNodes;
  931. let obj = {};
  932. obj[node.id] = node;
  933. childNodes = obj;
  934. }
  935. if (clusterNode === undefined || clusterNode === null) {
  936. throw new Error("_clusterEdges: parameter clusterNode required");
  937. }
  938. if (clusterEdgeProperties === undefined) {
  939. // Take the required properties from the cluster node
  940. clusterEdgeProperties = clusterNode.clusterEdgeProperties;
  941. }
  942. // create the new edges that will connect to the cluster.
  943. // All self-referencing edges will be added to childEdges here.
  944. this._createClusterEdges(childNodes, childEdges, clusterNode, clusterEdgeProperties);
  945. // disable the childEdges
  946. for (let edgeId in childEdges) {
  947. if (childEdges.hasOwnProperty(edgeId)) {
  948. if (this.body.edges[edgeId] !== undefined) {
  949. let edge = this.body.edges[edgeId];
  950. // cache the options before changing
  951. this._backupEdgeOptions(edge);
  952. // disable physics and hide the edge
  953. edge.setOptions({physics:false});
  954. }
  955. }
  956. }
  957. // disable the childNodes
  958. for (let nodeId in childNodes) {
  959. if (childNodes.hasOwnProperty(nodeId)) {
  960. this.clusteredNodes[nodeId] = {clusterId:clusterNode.id, node: this.body.nodes[nodeId]};
  961. this.body.nodes[nodeId].setOptions({physics:false});
  962. }
  963. }
  964. }
  965. /**
  966. * Determine in which cluster given nodeId resides.
  967. *
  968. * If not in cluster, return undefined.
  969. *
  970. * NOTE: If you know a cleaner way to do this, please enlighten me (wimrijnders).
  971. *
  972. * @param {Node.id} nodeId
  973. * @returns {Node|undefined} Node instance for cluster, if present
  974. * @private
  975. */
  976. _getClusterNodeForNode(nodeId) {
  977. if (nodeId === undefined) return undefined;
  978. let clusteredNode = this.clusteredNodes[nodeId];
  979. // NOTE: If no cluster info found, it should actually be an error
  980. if (clusteredNode === undefined) return undefined;
  981. let clusterId = clusteredNode.clusterId;
  982. if (clusterId === undefined) return undefined;
  983. return this.body.nodes[clusterId];
  984. }
  985. /**
  986. * Internal helper function for conditionally removing items in array
  987. *
  988. * Done like this because Array.filter() is not fully supported by all IE's.
  989. *
  990. * @param {Array} arr
  991. * @param {function} callback
  992. * @returns {Array}
  993. * @private
  994. */
  995. _filter(arr, callback) {
  996. let ret = [];
  997. util.forEach(arr, (item) => {
  998. if (callback(item)) {
  999. ret.push(item);
  1000. }
  1001. });
  1002. return ret;
  1003. }
  1004. /**
  1005. * Scan all edges for changes in clustering and adjust this if necessary.
  1006. *
  1007. * Call this (internally) after there has been a change in node or edge data.
  1008. *
  1009. * Pre: States of this.body.nodes and this.body.edges consistent
  1010. * Pre: this.clusteredNodes and this.clusteredEdge consistent with containedNodes and containedEdges
  1011. * of cluster nodes.
  1012. */
  1013. _updateState() {
  1014. let nodeId;
  1015. let deletedNodeIds = [];
  1016. let deletedEdgeIds = [];
  1017. /**
  1018. * Utility function to iterate over clustering nodes only
  1019. *
  1020. * @param {Function} callback function to call for each cluster node
  1021. */
  1022. let eachClusterNode = (callback) => {
  1023. util.forEach(this.body.nodes, (node) => {
  1024. if (node.isCluster === true) {
  1025. callback(node);
  1026. }
  1027. });
  1028. };
  1029. //
  1030. // Remove deleted regular nodes from clustering
  1031. //
  1032. // Determine the deleted nodes
  1033. for (nodeId in this.clusteredNodes) {
  1034. if (!this.clusteredNodes.hasOwnProperty(nodeId)) continue;
  1035. let node = this.body.nodes[nodeId];
  1036. if (node === undefined) {
  1037. deletedNodeIds.push(nodeId);
  1038. }
  1039. }
  1040. // Remove nodes from cluster nodes
  1041. eachClusterNode(function(clusterNode) {
  1042. for (let n = 0; n < deletedNodeIds.length; n++) {
  1043. delete clusterNode.containedNodes[deletedNodeIds[n]];
  1044. }
  1045. });
  1046. // Remove nodes from cluster list
  1047. for (let n = 0; n < deletedNodeIds.length; n++) {
  1048. delete this.clusteredNodes[deletedNodeIds[n]];
  1049. }
  1050. //
  1051. // Remove deleted edges from clustering
  1052. //
  1053. // Add the deleted clustered edges to the list
  1054. util.forEach(this.clusteredEdges, (edgeId) => {
  1055. let edge = this.body.edges[edgeId];
  1056. if (edge === undefined || !edge.endPointsValid()) {
  1057. deletedEdgeIds.push(edgeId);
  1058. }
  1059. });
  1060. // Cluster nodes can also contain edges which are not clustered,
  1061. // i.e. nodes 1-2 within cluster with an edge in between.
  1062. // So the cluster nodes also need to be scanned for invalid edges
  1063. eachClusterNode(function(clusterNode) {
  1064. util.forEach(clusterNode.containedEdges, (edge, edgeId) => {
  1065. if (!edge.endPointsValid() && deletedEdgeIds.indexOf(edgeId) === -1) {
  1066. deletedEdgeIds.push(edgeId);
  1067. }
  1068. });
  1069. });
  1070. // Also scan for cluster edges which need to be removed in the active list.
  1071. // Regular edges have been removed beforehand, so this only picks up the cluster edges.
  1072. util.forEach(this.body.edges, (edge, edgeId) => {
  1073. // Explicitly scan the contained edges for validity
  1074. let isValid = true;
  1075. let replacedIds = edge.clusteringEdgeReplacingIds;
  1076. if (replacedIds !== undefined) {
  1077. let numValid = 0;
  1078. util.forEach(replacedIds, (containedEdgeId) => {
  1079. let containedEdge = this.body.edges[containedEdgeId];
  1080. if (containedEdge !== undefined && containedEdge.endPointsValid()) {
  1081. numValid += 1;
  1082. }
  1083. });
  1084. isValid = (numValid > 0);
  1085. }
  1086. if (!edge.endPointsValid() || !isValid) {
  1087. deletedEdgeIds.push(edgeId);
  1088. }
  1089. });
  1090. // Remove edges from cluster nodes
  1091. eachClusterNode((clusterNode) => {
  1092. util.forEach(deletedEdgeIds, (deletedEdgeId) => {
  1093. delete clusterNode.containedEdges[deletedEdgeId];
  1094. util.forEach(clusterNode.edges, (edge, m) => {
  1095. if (edge.id === deletedEdgeId) {
  1096. clusterNode.edges[m] = null; // Don't want to directly delete here, because in the loop
  1097. return;
  1098. }
  1099. edge.clusteringEdgeReplacingIds = this._filter(edge.clusteringEdgeReplacingIds, function(id) {
  1100. return deletedEdgeIds.indexOf(id) === -1;
  1101. });
  1102. });
  1103. // Clean up the nulls
  1104. clusterNode.edges = this._filter(clusterNode.edges, function(item) {return item !== null});
  1105. });
  1106. });
  1107. // Remove from cluster list
  1108. util.forEach(deletedEdgeIds, (edgeId) => {
  1109. delete this.clusteredEdges[edgeId];
  1110. });
  1111. // Remove cluster edges from active list (this.body.edges).
  1112. // deletedEdgeIds still contains id of regular edges, but these should all
  1113. // be gone when you reach here.
  1114. util.forEach(deletedEdgeIds, (edgeId) => {
  1115. delete this.body.edges[edgeId];
  1116. });
  1117. //
  1118. // Check changed cluster state of edges
  1119. //
  1120. // Iterating over keys here, because edges may be removed in the loop
  1121. let ids = Object.keys(this.body.edges);
  1122. util.forEach(ids, (edgeId) => {
  1123. let edge = this.body.edges[edgeId];
  1124. let shouldBeClustered = this._isClusteredNode(edge.fromId) || this._isClusteredNode(edge.toId);
  1125. if (shouldBeClustered === this._isClusteredEdge(edge.id)) {
  1126. return; // all is well
  1127. }
  1128. if (shouldBeClustered) {
  1129. // add edge to clustering
  1130. let clusterFrom = this._getClusterNodeForNode(edge.fromId);
  1131. if (clusterFrom !== undefined) {
  1132. this._clusterEdges(this.body.nodes[edge.fromId], edge, clusterFrom);
  1133. }
  1134. let clusterTo = this._getClusterNodeForNode(edge.toId);
  1135. if (clusterTo !== undefined) {
  1136. this._clusterEdges(this.body.nodes[edge.toId], edge, clusterTo);
  1137. }
  1138. // TODO: check that it works for both edges clustered
  1139. // (This might be paranoia)
  1140. } else {
  1141. // This should not be happening, the state should
  1142. // be properly updated at this point.
  1143. //
  1144. // If it *is* reached during normal operation, then we have to implement
  1145. // undo clustering for this edge here.
  1146. throw new Error('remove edge from clustering not implemented!');
  1147. }
  1148. });
  1149. // Clusters may be nested to any level. Keep on opening until nothing to open
  1150. var changed = false;
  1151. var continueLoop = true;
  1152. while (continueLoop) {
  1153. let clustersToOpen = [];
  1154. // Determine the id's of clusters that need opening
  1155. eachClusterNode(function(clusterNode) {
  1156. let numNodes = Object.keys(clusterNode.containedNodes).length;
  1157. let allowSingle = (clusterNode.options.allowSingleNodeCluster === true);
  1158. if ((allowSingle && numNodes < 1) || (!allowSingle && numNodes < 2)) {
  1159. clustersToOpen.push(clusterNode.id);
  1160. }
  1161. });
  1162. // Open them
  1163. for (let n = 0; n < clustersToOpen.length; ++n) {
  1164. this.openCluster(clustersToOpen[n], {}, false /* Don't refresh, we're in an refresh/update already */);
  1165. }
  1166. continueLoop = (clustersToOpen.length > 0);
  1167. changed = changed || continueLoop;
  1168. }
  1169. if (changed) {
  1170. this._updateState() // Redo this method (recursion possible! should be safe)
  1171. }
  1172. }
  1173. /**
  1174. * Determine if node with given id is part of a cluster.
  1175. *
  1176. * @param {Node.id} nodeId
  1177. * @return {boolean} true if part of a cluster.
  1178. */
  1179. _isClusteredNode(nodeId) {
  1180. return this.clusteredNodes[nodeId] !== undefined;
  1181. }
  1182. /**
  1183. * Determine if edge with given id is not visible due to clustering.
  1184. *
  1185. * An edge is considered clustered if:
  1186. * - it is directly replaced by a clustering edge
  1187. * - any of its connecting nodes is in a cluster
  1188. *
  1189. * @param {vis.Edge.id} edgeId
  1190. * @return {boolean} true if part of a cluster.
  1191. */
  1192. _isClusteredEdge(edgeId) {
  1193. return this.clusteredEdges[edgeId] !== undefined;
  1194. }
  1195. }
  1196. export default ClusterEngine;