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.

477 lines
13 KiB

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