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.

445 lines
12 KiB

9 years ago
9 years ago
9 years ago
9 years ago
  1. let util = require("../../util");
  2. let DataSet = require('../../DataSet');
  3. let DataView = require('../../DataView');
  4. import Node from "./components/Node";
  5. import Label from "./components/shared/Label";
  6. class NodesHandler {
  7. constructor(body, images, groups, layoutEngine) {
  8. this.body = body;
  9. this.images = images;
  10. this.groups = groups;
  11. this.layoutEngine = layoutEngine;
  12. // create the node API in the body container
  13. this.body.functions.createNode = this.create.bind(this);
  14. this.nodesListeners = {
  15. add: (event, params) => { this.add(params.items); },
  16. update: (event, params) => { this.update(params.items, params.data); },
  17. remove: (event, params) => { this.remove(params.items); }
  18. };
  19. this.options = {};
  20. this.defaultOptions = {
  21. borderWidth: 1,
  22. borderWidthSelected: 2,
  23. brokenImage: undefined,
  24. color: {
  25. border: '#2B7CE9',
  26. background: '#97C2FC',
  27. highlight: {
  28. border: '#2B7CE9',
  29. background: '#D2E5FF'
  30. },
  31. hover: {
  32. border: '#2B7CE9',
  33. background: '#D2E5FF'
  34. }
  35. },
  36. fixed: {
  37. x: false,
  38. y: false
  39. },
  40. font: {
  41. color: '#343434',
  42. size: 14, // px
  43. face: 'arial',
  44. background: 'none',
  45. strokeWidth: 0, // px
  46. strokeColor: '#ffffff',
  47. align: 'horizontal'
  48. },
  49. group: undefined,
  50. hidden: false,
  51. icon: {
  52. face: 'FontAwesome', //'FontAwesome',
  53. code: undefined, //'\uf007',
  54. size: 50, //50,
  55. color: '#2B7CE9' //'#aa00ff'
  56. },
  57. image: undefined, // --> URL
  58. label: undefined,
  59. labelHighlightBold: true,
  60. level: undefined,
  61. mass: 1,
  62. physics: true,
  63. scaling: {
  64. min: 10,
  65. max: 30,
  66. label: {
  67. enabled: false,
  68. min: 14,
  69. max: 30,
  70. maxVisible: 30,
  71. drawThreshold: 5
  72. },
  73. customScalingFunction: function (min, max, total, value) {
  74. if (max === min) {
  75. return 0.5;
  76. }
  77. else {
  78. let scale = 1 / (max - min);
  79. return Math.max(0, (value - min) * scale);
  80. }
  81. }
  82. },
  83. shadow: {
  84. enabled: false,
  85. color: 'rgba(0,0,0,0.5)',
  86. size: 10,
  87. x: 5,
  88. y: 5
  89. },
  90. shape: 'ellipse',
  91. shapeProperties: {
  92. borderDashes: false, // only for borders
  93. borderRadius: 6, // only for box shape
  94. useImageSize: false, // only for image and circularImage shapes
  95. useBorderWithImage: false // only for image shape
  96. },
  97. size: 25,
  98. title: undefined,
  99. value: undefined,
  100. x: undefined,
  101. y: undefined
  102. };
  103. util.extend(this.options, this.defaultOptions);
  104. this.bindEventListeners();
  105. }
  106. bindEventListeners() {
  107. // refresh the nodes. Used when reverting from hierarchical layout
  108. this.body.emitter.on('refreshNodes', this.refresh.bind(this));
  109. this.body.emitter.on('refresh', this.refresh.bind(this));
  110. this.body.emitter.on('destroy', () => {
  111. delete this.body.functions.createNode;
  112. delete this.nodesListeners.add;
  113. delete this.nodesListeners.update;
  114. delete this.nodesListeners.remove;
  115. delete this.nodesListeners;
  116. });
  117. }
  118. setOptions(options) {
  119. if (options !== undefined) {
  120. Node.parseOptions(this.options, options);
  121. // update the shape in all nodes
  122. if (options.shape !== undefined) {
  123. for (let nodeId in this.body.nodes) {
  124. if (this.body.nodes.hasOwnProperty(nodeId)) {
  125. this.body.nodes[nodeId].updateShape();
  126. }
  127. }
  128. }
  129. // update the font in all nodes
  130. if (options.font !== undefined) {
  131. Label.parseOptions(this.options.font, options);
  132. for (let nodeId in this.body.nodes) {
  133. if (this.body.nodes.hasOwnProperty(nodeId)) {
  134. this.body.nodes[nodeId].updateLabelModule();
  135. this.body.nodes[nodeId]._reset();
  136. }
  137. }
  138. }
  139. // update the shape size in all nodes
  140. if (options.size !== undefined) {
  141. for (let nodeId in this.body.nodes) {
  142. if (this.body.nodes.hasOwnProperty(nodeId)) {
  143. this.body.nodes[nodeId]._reset();
  144. }
  145. }
  146. }
  147. // update the state of the letiables if needed
  148. if (options.hidden !== undefined || options.physics !== undefined) {
  149. this.body.emitter.emit('_dataChanged');
  150. }
  151. }
  152. }
  153. /**
  154. * Set a data set with nodes for the network
  155. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  156. * @private
  157. */
  158. setData(nodes, doNotEmit = false) {
  159. let oldNodesData = this.body.data.nodes;
  160. if (nodes instanceof DataSet || nodes instanceof DataView) {
  161. this.body.data.nodes = nodes;
  162. }
  163. else if (Array.isArray(nodes)) {
  164. this.body.data.nodes = new DataSet();
  165. this.body.data.nodes.add(nodes);
  166. }
  167. else if (!nodes) {
  168. this.body.data.nodes = new DataSet();
  169. }
  170. else {
  171. throw new TypeError('Array or DataSet expected');
  172. }
  173. if (oldNodesData) {
  174. // unsubscribe from old dataset
  175. util.forEach(this.nodesListeners, function (callback, event) {
  176. oldNodesData.off(event, callback);
  177. });
  178. }
  179. // remove drawn nodes
  180. this.body.nodes = {};
  181. if (this.body.data.nodes) {
  182. // subscribe to new dataset
  183. let me = this;
  184. util.forEach(this.nodesListeners, function (callback, event) {
  185. me.body.data.nodes.on(event, callback);
  186. });
  187. // draw all new nodes
  188. let ids = this.body.data.nodes.getIds();
  189. this.add(ids, true);
  190. }
  191. if (doNotEmit === false) {
  192. this.body.emitter.emit("_dataChanged");
  193. }
  194. }
  195. /**
  196. * Add nodes
  197. * @param {Number[] | String[]} ids
  198. * @private
  199. */
  200. add(ids, doNotEmit = false) {
  201. let id;
  202. let newNodes = [];
  203. for (let i = 0; i < ids.length; i++) {
  204. id = ids[i];
  205. let properties = this.body.data.nodes.get(id);
  206. let node = this.create(properties);
  207. newNodes.push(node);
  208. this.body.nodes[id] = node; // note: this may replace an existing node
  209. }
  210. this.layoutEngine.positionInitially(newNodes);
  211. if (doNotEmit === false) {
  212. this.body.emitter.emit("_dataChanged");
  213. }
  214. }
  215. /**
  216. * Update existing nodes, or create them when not yet existing
  217. * @param {Number[] | String[]} ids
  218. * @private
  219. */
  220. update(ids, changedData) {
  221. let nodes = this.body.nodes;
  222. let dataChanged = false;
  223. for (let i = 0; i < ids.length; i++) {
  224. let id = ids[i];
  225. let node = nodes[id];
  226. let data = changedData[i];
  227. if (node !== undefined) {
  228. // update node
  229. dataChanged = node.setOptions(data);
  230. }
  231. else {
  232. dataChanged = true;
  233. // create node
  234. node = this.create(data);
  235. nodes[id] = node;
  236. }
  237. }
  238. if (dataChanged === true) {
  239. this.body.emitter.emit("_dataChanged");
  240. }
  241. else {
  242. this.body.emitter.emit("_dataUpdated");
  243. }
  244. }
  245. /**
  246. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  247. * @param {Number[] | String[]} ids
  248. * @private
  249. */
  250. remove(ids) {
  251. let nodes = this.body.nodes;
  252. for (let i = 0; i < ids.length; i++) {
  253. let id = ids[i];
  254. delete nodes[id];
  255. }
  256. this.body.emitter.emit("_dataChanged");
  257. }
  258. /**
  259. * create a node
  260. * @param properties
  261. * @param constructorClass
  262. */
  263. create(properties, constructorClass = Node) {
  264. return new constructorClass(properties, this.body, this.images, this.groups, this.options)
  265. }
  266. refresh(clearPositions = false) {
  267. let nodes = this.body.nodes;
  268. for (let nodeId in nodes) {
  269. let node = undefined;
  270. if (nodes.hasOwnProperty(nodeId)) {
  271. node = nodes[nodeId];
  272. }
  273. let data = this.body.data.nodes._data[nodeId];
  274. if (node !== undefined && data !== undefined) {
  275. if (clearPositions === true) {
  276. node.setOptions({x:null, y:null});
  277. }
  278. node.setOptions({ fixed: false });
  279. node.setOptions(data);
  280. }
  281. }
  282. }
  283. /**
  284. * Returns the positions of the nodes.
  285. * @param ids --> optional, can be array of nodeIds, can be string
  286. * @returns {{}}
  287. */
  288. getPositions(ids) {
  289. let dataArray = {};
  290. if (ids !== undefined) {
  291. if (Array.isArray(ids) === true) {
  292. for (let i = 0; i < ids.length; i++) {
  293. if (this.body.nodes[ids[i]] !== undefined) {
  294. let node = this.body.nodes[ids[i]];
  295. dataArray[ids[i]] = { x: Math.round(node.x), y: Math.round(node.y) };
  296. }
  297. }
  298. }
  299. else {
  300. if (this.body.nodes[ids] !== undefined) {
  301. let node = this.body.nodes[ids];
  302. dataArray[ids] = { x: Math.round(node.x), y: Math.round(node.y) };
  303. }
  304. }
  305. }
  306. else {
  307. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  308. let node = this.body.nodes[this.body.nodeIndices[i]];
  309. dataArray[this.body.nodeIndices[i]] = { x: Math.round(node.x), y: Math.round(node.y) };
  310. }
  311. }
  312. return dataArray;
  313. }
  314. /**
  315. * Load the XY positions of the nodes into the dataset.
  316. */
  317. storePositions() {
  318. // todo: add support for clusters and hierarchical.
  319. let dataArray = [];
  320. var dataset = this.body.data.nodes.getDataSet();
  321. for (let nodeId in dataset._data) {
  322. if (dataset._data.hasOwnProperty(nodeId)) {
  323. let node = this.body.nodes[nodeId];
  324. if (dataset._data[nodeId].x != Math.round(node.x) || dataset._data[nodeId].y != Math.round(node.y)) {
  325. dataArray.push({ id: node.id, x: Math.round(node.x), y: Math.round(node.y) });
  326. }
  327. }
  328. }
  329. dataset.update(dataArray);
  330. }
  331. /**
  332. * get the bounding box of a node.
  333. * @param nodeId
  334. * @returns {j|*}
  335. */
  336. getBoundingBox(nodeId) {
  337. if (this.body.nodes[nodeId] !== undefined) {
  338. return this.body.nodes[nodeId].shape.boundingBox;
  339. }
  340. }
  341. /**
  342. * Get the Ids of nodes connected to this node.
  343. * @param nodeId
  344. * @returns {Array}
  345. */
  346. getConnectedNodes(nodeId) {
  347. let nodeList = [];
  348. if (this.body.nodes[nodeId] !== undefined) {
  349. let node = this.body.nodes[nodeId];
  350. let nodeObj = {}; // used to quickly check if node already exists
  351. for (let i = 0; i < node.edges.length; i++) {
  352. let edge = node.edges[i];
  353. if (edge.toId == node.id) { // these are double equals since ids can be numeric or string
  354. if (nodeObj[edge.fromId] === undefined) {
  355. nodeList.push(edge.fromId);
  356. nodeObj[edge.fromId] = true;
  357. }
  358. }
  359. else if (edge.fromId == node.id) { // these are double equals since ids can be numeric or string
  360. if (nodeObj[edge.toId] === undefined) {
  361. nodeList.push(edge.toId);
  362. nodeObj[edge.toId] = true;
  363. }
  364. }
  365. }
  366. }
  367. return nodeList;
  368. }
  369. /**
  370. * Get the ids of the edges connected to this node.
  371. * @param nodeId
  372. * @returns {*}
  373. */
  374. getConnectedEdges(nodeId) {
  375. let edgeList = [];
  376. if (this.body.nodes[nodeId] !== undefined) {
  377. let node = this.body.nodes[nodeId];
  378. for (let i = 0; i < node.edges.length; i++) {
  379. edgeList.push(node.edges[i].id)
  380. }
  381. }
  382. else {
  383. console.log("NodeId provided for getConnectedEdges does not exist. Provided: ", nodeId);
  384. }
  385. return edgeList;
  386. }
  387. /**
  388. * Move a node.
  389. * @param String nodeId
  390. * @param Number x
  391. * @param Number y
  392. */
  393. moveNode(nodeId, x, y) {
  394. if (this.body.nodes[nodeId] !== undefined) {
  395. this.body.nodes[nodeId].x = Number(x);
  396. this.body.nodes[nodeId].y = Number(y);
  397. setTimeout(() => {this.body.emitter.emit("startSimulation")},0);
  398. }
  399. else {
  400. console.log("Node id supplied to moveNode does not exist. Provided: ", nodeId);
  401. }
  402. }
  403. }
  404. export default NodesHandler;