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.

428 lines
11 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. 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. size: 10,
  86. x: 5,
  87. y: 5
  88. },
  89. shape: 'ellipse',
  90. shapeProperties: {
  91. borderDashes: false,
  92. borderRadius: 6,
  93. useImageSize: false
  94. },
  95. size: 25,
  96. title: undefined,
  97. value: undefined,
  98. x: undefined,
  99. y: undefined
  100. };
  101. util.extend(this.options, this.defaultOptions);
  102. this.bindEventListeners();
  103. }
  104. bindEventListeners() {
  105. // refresh the nodes. Used when reverting from hierarchical layout
  106. this.body.emitter.on('refreshNodes', this.refresh.bind(this));
  107. this.body.emitter.on('refresh', this.refresh.bind(this));
  108. this.body.emitter.on('destroy', () => {
  109. delete this.body.functions.createNode;
  110. delete this.nodesListeners.add;
  111. delete this.nodesListeners.update;
  112. delete this.nodesListeners.remove;
  113. delete this.nodesListeners;
  114. });
  115. }
  116. setOptions(options) {
  117. if (options !== undefined) {
  118. Node.parseOptions(this.options, options);
  119. // update the shape in all nodes
  120. if (options.shape !== undefined) {
  121. for (let nodeId in this.body.nodes) {
  122. if (this.body.nodes.hasOwnProperty(nodeId)) {
  123. this.body.nodes[nodeId].updateShape();
  124. }
  125. }
  126. }
  127. // update the shape size in all nodes
  128. if (options.font !== undefined) {
  129. Label.parseOptions(this.options.font, options);
  130. for (let nodeId in this.body.nodes) {
  131. if (this.body.nodes.hasOwnProperty(nodeId)) {
  132. this.body.nodes[nodeId].updateLabelModule();
  133. this.body.nodes[nodeId]._reset();
  134. }
  135. }
  136. }
  137. // update the shape size in all nodes
  138. if (options.size !== undefined) {
  139. for (let nodeId in this.body.nodes) {
  140. if (this.body.nodes.hasOwnProperty(nodeId)) {
  141. this.body.nodes[nodeId]._reset();
  142. }
  143. }
  144. }
  145. // update the state of the letiables if needed
  146. if (options.hidden !== undefined || options.physics !== undefined) {
  147. this.body.emitter.emit('_dataChanged');
  148. }
  149. }
  150. }
  151. /**
  152. * Set a data set with nodes for the network
  153. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  154. * @private
  155. */
  156. setData(nodes, doNotEmit = false) {
  157. let oldNodesData = this.body.data.nodes;
  158. if (nodes instanceof DataSet || nodes instanceof DataView) {
  159. this.body.data.nodes = nodes;
  160. }
  161. else if (Array.isArray(nodes)) {
  162. this.body.data.nodes = new DataSet();
  163. this.body.data.nodes.add(nodes);
  164. }
  165. else if (!nodes) {
  166. this.body.data.nodes = new DataSet();
  167. }
  168. else {
  169. throw new TypeError('Array or DataSet expected');
  170. }
  171. if (oldNodesData) {
  172. // unsubscribe from old dataset
  173. util.forEach(this.nodesListeners, function (callback, event) {
  174. oldNodesData.off(event, callback);
  175. });
  176. }
  177. // remove drawn nodes
  178. this.body.nodes = {};
  179. if (this.body.data.nodes) {
  180. // subscribe to new dataset
  181. let me = this;
  182. util.forEach(this.nodesListeners, function (callback, event) {
  183. me.body.data.nodes.on(event, callback);
  184. });
  185. // draw all new nodes
  186. let ids = this.body.data.nodes.getIds();
  187. this.add(ids, true);
  188. }
  189. if (doNotEmit === false) {
  190. this.body.emitter.emit("_dataChanged");
  191. }
  192. }
  193. /**
  194. * Add nodes
  195. * @param {Number[] | String[]} ids
  196. * @private
  197. */
  198. add(ids, doNotEmit = false) {
  199. let id;
  200. let newNodes = [];
  201. for (let i = 0; i < ids.length; i++) {
  202. id = ids[i];
  203. let properties = this.body.data.nodes.get(id);
  204. let node = this.create(properties);
  205. newNodes.push(node);
  206. this.body.nodes[id] = node; // note: this may replace an existing node
  207. }
  208. this.layoutEngine.positionInitially(newNodes);
  209. if (doNotEmit === false) {
  210. this.body.emitter.emit("_dataChanged");
  211. }
  212. }
  213. /**
  214. * Update existing nodes, or create them when not yet existing
  215. * @param {Number[] | String[]} ids
  216. * @private
  217. */
  218. update(ids, changedData) {
  219. let nodes = this.body.nodes;
  220. let dataChanged = false;
  221. for (let i = 0; i < ids.length; i++) {
  222. let id = ids[i];
  223. let node = nodes[id];
  224. let data = changedData[i];
  225. if (node !== undefined) {
  226. // update node
  227. dataChanged = node.setOptions(data);
  228. }
  229. else {
  230. dataChanged = true;
  231. // create node
  232. node = this.create(data);
  233. nodes[id] = node;
  234. }
  235. }
  236. if (dataChanged === true) {
  237. this.body.emitter.emit("_dataChanged");
  238. }
  239. else {
  240. this.body.emitter.emit("_dataUpdated");
  241. }
  242. }
  243. /**
  244. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  245. * @param {Number[] | String[]} ids
  246. * @private
  247. */
  248. remove(ids) {
  249. let nodes = this.body.nodes;
  250. for (let i = 0; i < ids.length; i++) {
  251. let id = ids[i];
  252. delete nodes[id];
  253. }
  254. this.body.emitter.emit("_dataChanged");
  255. }
  256. /**
  257. * create a node
  258. * @param properties
  259. * @param constructorClass
  260. */
  261. create(properties, constructorClass = Node) {
  262. return new constructorClass(properties, this.body, this.images, this.groups, this.options)
  263. }
  264. refresh(clearPositions = false) {
  265. let nodes = this.body.nodes;
  266. for (let nodeId in nodes) {
  267. let node = undefined;
  268. if (nodes.hasOwnProperty(nodeId)) {
  269. node = nodes[nodeId];
  270. }
  271. let data = this.body.data.nodes._data[nodeId];
  272. if (node !== undefined && data !== undefined) {
  273. if (clearPositions === true) {
  274. node.setOptions({x:null, y:null});
  275. }
  276. node.setOptions({ fixed: false });
  277. node.setOptions(data);
  278. }
  279. }
  280. }
  281. /**
  282. * Returns the positions of the nodes.
  283. * @param ids --> optional, can be array of nodeIds, can be string
  284. * @returns {{}}
  285. */
  286. getPositions(ids) {
  287. let dataArray = {};
  288. if (ids !== undefined) {
  289. if (Array.isArray(ids) === true) {
  290. for (let i = 0; i < ids.length; i++) {
  291. if (this.body.nodes[ids[i]] !== undefined) {
  292. let node = this.body.nodes[ids[i]];
  293. dataArray[ids[i]] = { x: Math.round(node.x), y: Math.round(node.y) };
  294. }
  295. }
  296. }
  297. else {
  298. if (this.body.nodes[ids] !== undefined) {
  299. let node = this.body.nodes[ids];
  300. dataArray[ids] = { x: Math.round(node.x), y: Math.round(node.y) };
  301. }
  302. }
  303. }
  304. else {
  305. for (let nodeId in this.body.nodes) {
  306. if (this.body.nodes.hasOwnProperty(nodeId)) {
  307. let node = this.body.nodes[nodeId];
  308. dataArray[nodeId] = { x: Math.round(node.x), y: Math.round(node.y) };
  309. }
  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: nodeId, 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 == nodeId) { // 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 == nodeId) { // 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. export default NodesHandler;