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.

449 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. util.forEach(this.nodesListeners, (callback, event) => {
  112. if (this.body.data.nodes)
  113. this.body.data.nodes.off(event, callback);
  114. });
  115. delete this.body.functions.createNode;
  116. delete this.nodesListeners.add;
  117. delete this.nodesListeners.update;
  118. delete this.nodesListeners.remove;
  119. delete this.nodesListeners;
  120. });
  121. }
  122. setOptions(options) {
  123. if (options !== undefined) {
  124. Node.parseOptions(this.options, options);
  125. // update the shape in all nodes
  126. if (options.shape !== undefined) {
  127. for (let nodeId in this.body.nodes) {
  128. if (this.body.nodes.hasOwnProperty(nodeId)) {
  129. this.body.nodes[nodeId].updateShape();
  130. }
  131. }
  132. }
  133. // update the font in all nodes
  134. if (options.font !== undefined) {
  135. Label.parseOptions(this.options.font, options);
  136. for (let nodeId in this.body.nodes) {
  137. if (this.body.nodes.hasOwnProperty(nodeId)) {
  138. this.body.nodes[nodeId].updateLabelModule();
  139. this.body.nodes[nodeId]._reset();
  140. }
  141. }
  142. }
  143. // update the shape size in all nodes
  144. if (options.size !== undefined) {
  145. for (let nodeId in this.body.nodes) {
  146. if (this.body.nodes.hasOwnProperty(nodeId)) {
  147. this.body.nodes[nodeId]._reset();
  148. }
  149. }
  150. }
  151. // update the state of the letiables if needed
  152. if (options.hidden !== undefined || options.physics !== undefined) {
  153. this.body.emitter.emit('_dataChanged');
  154. }
  155. }
  156. }
  157. /**
  158. * Set a data set with nodes for the network
  159. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  160. * @private
  161. */
  162. setData(nodes, doNotEmit = false) {
  163. let oldNodesData = this.body.data.nodes;
  164. if (nodes instanceof DataSet || nodes instanceof DataView) {
  165. this.body.data.nodes = nodes;
  166. }
  167. else if (Array.isArray(nodes)) {
  168. this.body.data.nodes = new DataSet();
  169. this.body.data.nodes.add(nodes);
  170. }
  171. else if (!nodes) {
  172. this.body.data.nodes = new DataSet();
  173. }
  174. else {
  175. throw new TypeError('Array or DataSet expected');
  176. }
  177. if (oldNodesData) {
  178. // unsubscribe from old dataset
  179. util.forEach(this.nodesListeners, function (callback, event) {
  180. oldNodesData.off(event, callback);
  181. });
  182. }
  183. // remove drawn nodes
  184. this.body.nodes = {};
  185. if (this.body.data.nodes) {
  186. // subscribe to new dataset
  187. let me = this;
  188. util.forEach(this.nodesListeners, function (callback, event) {
  189. me.body.data.nodes.on(event, callback);
  190. });
  191. // draw all new nodes
  192. let ids = this.body.data.nodes.getIds();
  193. this.add(ids, true);
  194. }
  195. if (doNotEmit === false) {
  196. this.body.emitter.emit("_dataChanged");
  197. }
  198. }
  199. /**
  200. * Add nodes
  201. * @param {Number[] | String[]} ids
  202. * @private
  203. */
  204. add(ids, doNotEmit = false) {
  205. let id;
  206. let newNodes = [];
  207. for (let i = 0; i < ids.length; i++) {
  208. id = ids[i];
  209. let properties = this.body.data.nodes.get(id);
  210. let node = this.create(properties);
  211. newNodes.push(node);
  212. this.body.nodes[id] = node; // note: this may replace an existing node
  213. }
  214. this.layoutEngine.positionInitially(newNodes);
  215. if (doNotEmit === false) {
  216. this.body.emitter.emit("_dataChanged");
  217. }
  218. }
  219. /**
  220. * Update existing nodes, or create them when not yet existing
  221. * @param {Number[] | String[]} ids
  222. * @private
  223. */
  224. update(ids, changedData) {
  225. let nodes = this.body.nodes;
  226. let dataChanged = false;
  227. for (let i = 0; i < ids.length; i++) {
  228. let id = ids[i];
  229. let node = nodes[id];
  230. let data = changedData[i];
  231. if (node !== undefined) {
  232. // update node
  233. dataChanged = node.setOptions(data);
  234. }
  235. else {
  236. dataChanged = true;
  237. // create node
  238. node = this.create(data);
  239. nodes[id] = node;
  240. }
  241. }
  242. if (dataChanged === true) {
  243. this.body.emitter.emit("_dataChanged");
  244. }
  245. else {
  246. this.body.emitter.emit("_dataUpdated");
  247. }
  248. }
  249. /**
  250. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  251. * @param {Number[] | String[]} ids
  252. * @private
  253. */
  254. remove(ids) {
  255. let nodes = this.body.nodes;
  256. for (let i = 0; i < ids.length; i++) {
  257. let id = ids[i];
  258. delete nodes[id];
  259. }
  260. this.body.emitter.emit("_dataChanged");
  261. }
  262. /**
  263. * create a node
  264. * @param properties
  265. * @param constructorClass
  266. */
  267. create(properties, constructorClass = Node) {
  268. return new constructorClass(properties, this.body, this.images, this.groups, this.options)
  269. }
  270. refresh(clearPositions = false) {
  271. let nodes = this.body.nodes;
  272. for (let nodeId in nodes) {
  273. let node = undefined;
  274. if (nodes.hasOwnProperty(nodeId)) {
  275. node = nodes[nodeId];
  276. }
  277. let data = this.body.data.nodes._data[nodeId];
  278. if (node !== undefined && data !== undefined) {
  279. if (clearPositions === true) {
  280. node.setOptions({x:null, y:null});
  281. }
  282. node.setOptions({ fixed: false });
  283. node.setOptions(data);
  284. }
  285. }
  286. }
  287. /**
  288. * Returns the positions of the nodes.
  289. * @param ids --> optional, can be array of nodeIds, can be string
  290. * @returns {{}}
  291. */
  292. getPositions(ids) {
  293. let dataArray = {};
  294. if (ids !== undefined) {
  295. if (Array.isArray(ids) === true) {
  296. for (let i = 0; i < ids.length; i++) {
  297. if (this.body.nodes[ids[i]] !== undefined) {
  298. let node = this.body.nodes[ids[i]];
  299. dataArray[ids[i]] = { x: Math.round(node.x), y: Math.round(node.y) };
  300. }
  301. }
  302. }
  303. else {
  304. if (this.body.nodes[ids] !== undefined) {
  305. let node = this.body.nodes[ids];
  306. dataArray[ids] = { x: Math.round(node.x), y: Math.round(node.y) };
  307. }
  308. }
  309. }
  310. else {
  311. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  312. let node = this.body.nodes[this.body.nodeIndices[i]];
  313. dataArray[this.body.nodeIndices[i]] = { x: Math.round(node.x), y: Math.round(node.y) };
  314. }
  315. }
  316. return dataArray;
  317. }
  318. /**
  319. * Load the XY positions of the nodes into the dataset.
  320. */
  321. storePositions() {
  322. // todo: add support for clusters and hierarchical.
  323. let dataArray = [];
  324. var dataset = this.body.data.nodes.getDataSet();
  325. for (let nodeId in dataset._data) {
  326. if (dataset._data.hasOwnProperty(nodeId)) {
  327. let node = this.body.nodes[nodeId];
  328. if (dataset._data[nodeId].x != Math.round(node.x) || dataset._data[nodeId].y != Math.round(node.y)) {
  329. dataArray.push({ id: node.id, x: Math.round(node.x), y: Math.round(node.y) });
  330. }
  331. }
  332. }
  333. dataset.update(dataArray);
  334. }
  335. /**
  336. * get the bounding box of a node.
  337. * @param nodeId
  338. * @returns {j|*}
  339. */
  340. getBoundingBox(nodeId) {
  341. if (this.body.nodes[nodeId] !== undefined) {
  342. return this.body.nodes[nodeId].shape.boundingBox;
  343. }
  344. }
  345. /**
  346. * Get the Ids of nodes connected to this node.
  347. * @param nodeId
  348. * @returns {Array}
  349. */
  350. getConnectedNodes(nodeId) {
  351. let nodeList = [];
  352. if (this.body.nodes[nodeId] !== undefined) {
  353. let node = this.body.nodes[nodeId];
  354. let nodeObj = {}; // used to quickly check if node already exists
  355. for (let i = 0; i < node.edges.length; i++) {
  356. let edge = node.edges[i];
  357. if (edge.toId == node.id) { // these are double equals since ids can be numeric or string
  358. if (nodeObj[edge.fromId] === undefined) {
  359. nodeList.push(edge.fromId);
  360. nodeObj[edge.fromId] = true;
  361. }
  362. }
  363. else if (edge.fromId == node.id) { // these are double equals since ids can be numeric or string
  364. if (nodeObj[edge.toId] === undefined) {
  365. nodeList.push(edge.toId);
  366. nodeObj[edge.toId] = true;
  367. }
  368. }
  369. }
  370. }
  371. return nodeList;
  372. }
  373. /**
  374. * Get the ids of the edges connected to this node.
  375. * @param nodeId
  376. * @returns {*}
  377. */
  378. getConnectedEdges(nodeId) {
  379. let edgeList = [];
  380. if (this.body.nodes[nodeId] !== undefined) {
  381. let node = this.body.nodes[nodeId];
  382. for (let i = 0; i < node.edges.length; i++) {
  383. edgeList.push(node.edges[i].id)
  384. }
  385. }
  386. else {
  387. console.log("NodeId provided for getConnectedEdges does not exist. Provided: ", nodeId);
  388. }
  389. return edgeList;
  390. }
  391. /**
  392. * Move a node.
  393. * @param String nodeId
  394. * @param Number x
  395. * @param Number y
  396. */
  397. moveNode(nodeId, x, y) {
  398. if (this.body.nodes[nodeId] !== undefined) {
  399. this.body.nodes[nodeId].x = Number(x);
  400. this.body.nodes[nodeId].y = Number(y);
  401. setTimeout(() => {this.body.emitter.emit("startSimulation")},0);
  402. }
  403. else {
  404. console.log("Node id supplied to moveNode does not exist. Provided: ", nodeId);
  405. }
  406. }
  407. }
  408. export default NodesHandler;