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.

578 lines
19 KiB

9 years ago
9 years ago
9 years ago
  1. var util = require('../../../util');
  2. var Label = require('./shared/Label').default;
  3. var ComponentUtil = require('./shared/ComponentUtil').default;
  4. var Box = require('./nodes/shapes/Box').default;
  5. var Circle = require('./nodes/shapes/Circle').default;
  6. var CircularImage = require('./nodes/shapes/CircularImage').default;
  7. var Database = require('./nodes/shapes/Database').default;
  8. var Diamond = require('./nodes/shapes/Diamond').default;
  9. var Dot = require('./nodes/shapes/Dot').default;
  10. var Ellipse = require('./nodes/shapes/Ellipse').default;
  11. var Icon = require('./nodes/shapes/Icon').default;
  12. var Image = require('./nodes/shapes/Image').default;
  13. var Square = require('./nodes/shapes/Square').default;
  14. var Hexagon = require('./nodes/shapes/Hexagon').default;
  15. var Star = require('./nodes/shapes/Star').default;
  16. var Text = require('./nodes/shapes/Text').default;
  17. var Triangle = require('./nodes/shapes/Triangle').default;
  18. var TriangleDown = require('./nodes/shapes/TriangleDown').default;
  19. var { printStyle } = require("../../../shared/Validator");
  20. /**
  21. * A node. A node can be connected to other nodes via one or multiple edges.
  22. */
  23. class Node {
  24. /**
  25. *
  26. * @param {object} options An object containing options for the node. All
  27. * options are optional, except for the id.
  28. * {number} id Id of the node. Required
  29. * {string} label Text label for the node
  30. * {number} x Horizontal position of the node
  31. * {number} y Vertical position of the node
  32. * {string} shape Node shape, available:
  33. * "database", "circle", "ellipse",
  34. * "box", "image", "text", "dot",
  35. * "star", "triangle", "triangleDown",
  36. * "square", "icon"
  37. * {string} image An image url
  38. * {string} title An title text, can be HTML
  39. * {anytype} group A group name or number
  40. * @param {Object} body
  41. * @param {Network.Images} imagelist A list with images. Only needed
  42. * when the node has an image
  43. * @param {Groups} grouplist A list with groups. Needed for
  44. * retrieving group options
  45. * @param {Object} globalOptions An object with default values for
  46. * example for the color
  47. * @param {Object} defaultOptions
  48. * @param {Object} nodeOptions
  49. */
  50. constructor(options, body, imagelist, grouplist, globalOptions, defaultOptions, nodeOptions) {
  51. this.options = util.bridgeObject(globalOptions);
  52. this.globalOptions = globalOptions;
  53. this.defaultOptions = defaultOptions;
  54. this.nodeOptions = nodeOptions;
  55. this.body = body;
  56. this.edges = []; // all edges connected to this node
  57. // set defaults for the options
  58. this.id = undefined;
  59. this.imagelist = imagelist;
  60. this.grouplist = grouplist;
  61. // state options
  62. this.x = undefined;
  63. this.y = undefined;
  64. this.baseSize = this.options.size;
  65. this.baseFontSize = this.options.font.size;
  66. this.predefinedPosition = false; // used to check if initial fit should just take the range or approximate
  67. this.selected = false;
  68. this.hover = false;
  69. this.labelModule = new Label(this.body, this.options, false /* Not edge label */);
  70. this.setOptions(options);
  71. }
  72. /**
  73. * Attach a edge to the node
  74. * @param {Edge} edge
  75. */
  76. attachEdge(edge) {
  77. if (this.edges.indexOf(edge) === -1) {
  78. this.edges.push(edge);
  79. }
  80. }
  81. /**
  82. * Detach a edge from the node
  83. *
  84. * @param {Edge} edge
  85. */
  86. detachEdge(edge) {
  87. var index = this.edges.indexOf(edge);
  88. if (index != -1) {
  89. this.edges.splice(index, 1);
  90. }
  91. }
  92. /**
  93. * Set or overwrite options for the node
  94. *
  95. * @param {Object} options an object with options
  96. * @returns {null|boolean}
  97. */
  98. setOptions(options) {
  99. let currentShape = this.options.shape;
  100. if (!options) {
  101. return; // Note that the return value will be 'undefined'! This is OK.
  102. }
  103. // basic options
  104. if (options.id !== undefined) {this.id = options.id;}
  105. if (this.id === undefined) {
  106. throw new Error("Node must have an id");
  107. }
  108. Node.checkMass(options, this.id);
  109. // set these options locally
  110. // clear x and y positions
  111. if (options.x !== undefined) {
  112. if (options.x === null) {this.x = undefined; this.predefinedPosition = false;}
  113. else {this.x = parseInt(options.x); this.predefinedPosition = true;}
  114. }
  115. if (options.y !== undefined) {
  116. if (options.y === null) {this.y = undefined; this.predefinedPosition = false;}
  117. else {this.y = parseInt(options.y); this.predefinedPosition = true;}
  118. }
  119. if (options.size !== undefined) {this.baseSize = options.size;}
  120. if (options.value !== undefined) {options.value = parseFloat(options.value);}
  121. // copy group options
  122. if (typeof options.group === 'number' || (typeof options.group === 'string' && options.group != '')) {
  123. var groupObj = this.grouplist.get(options.group);
  124. util.deepExtend(this.options, groupObj);
  125. // the color object needs to be completely defined. Since groups can partially overwrite the colors, we parse it again, just in case.
  126. this.options.color = util.parseColor(this.options.color);
  127. }
  128. // this transforms all shorthands into fully defined options
  129. Node.parseOptions(this.options, options, true, this.globalOptions);
  130. let pile = [options, this.options, this.defaultOptions];
  131. this.chooser = ComponentUtil.choosify('node', pile);
  132. this._load_images();
  133. this.updateLabelModule(options);
  134. this.updateShape(currentShape);
  135. this.labelModule.propagateFonts(this.nodeOptions, options, this.defaultOptions);
  136. return (options.hidden !== undefined || options.physics !== undefined);
  137. }
  138. /**
  139. * Load the images from the options, for the nodes that need them.
  140. *
  141. * TODO: The imageObj members should be moved to CircularImageBase.
  142. * It's the only place where they are required.
  143. *
  144. * @private
  145. */
  146. _load_images() {
  147. // Don't bother loading for nodes without images
  148. if (this.options.shape !== 'circularImage' && this.options.shape !== 'image') {
  149. return;
  150. }
  151. if (this.options.image === undefined) {
  152. throw new Error("Option image must be defined for node type '" + this.options.shape + "'");
  153. }
  154. if (this.imagelist === undefined) {
  155. throw new Error("Internal Error: No images provided");
  156. }
  157. if (typeof this.options.image === 'string') {
  158. this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage, this.id);
  159. } else {
  160. if (this.options.image.unselected === undefined) {
  161. throw new Error("No unselected image provided");
  162. }
  163. this.imageObj = this.imagelist.load(this.options.image.unselected, this.options.brokenImage, this.id);
  164. if (this.options.image.selected !== undefined) {
  165. this.imageObjAlt = this.imagelist.load(this.options.image.selected, this.options.brokenImage, this.id);
  166. } else {
  167. this.imageObjAlt = undefined;
  168. }
  169. }
  170. }
  171. /**
  172. * This process all possible shorthands in the new options and makes sure that the parentOptions are fully defined.
  173. * Static so it can also be used by the handler.
  174. *
  175. * @param {Object} parentOptions
  176. * @param {Object} newOptions
  177. * @param {boolean} [allowDeletion=false]
  178. * @param {Object} [globalOptions={}]
  179. * @static
  180. */
  181. static parseOptions(parentOptions, newOptions, allowDeletion = false, globalOptions = {}) {
  182. var fields = [
  183. 'color',
  184. 'font',
  185. 'fixed',
  186. 'shadow'
  187. ];
  188. util.selectiveNotDeepExtend(fields, parentOptions, newOptions, allowDeletion);
  189. Node.checkMass(newOptions);
  190. // merge the shadow options into the parent.
  191. util.mergeOptions(parentOptions, newOptions, 'shadow', globalOptions);
  192. // individual shape newOptions
  193. if (newOptions.color !== undefined && newOptions.color !== null) {
  194. let parsedColor = util.parseColor(newOptions.color);
  195. util.fillIfDefined(parentOptions.color, parsedColor);
  196. }
  197. else if (allowDeletion === true && newOptions.color === null) {
  198. parentOptions.color = util.bridgeObject(globalOptions.color); // set the object back to the global options
  199. }
  200. // handle the fixed options
  201. if (newOptions.fixed !== undefined && newOptions.fixed !== null) {
  202. if (typeof newOptions.fixed === 'boolean') {
  203. parentOptions.fixed.x = newOptions.fixed;
  204. parentOptions.fixed.y = newOptions.fixed;
  205. }
  206. else {
  207. if (newOptions.fixed.x !== undefined && typeof newOptions.fixed.x === 'boolean') {
  208. parentOptions.fixed.x = newOptions.fixed.x;
  209. }
  210. if (newOptions.fixed.y !== undefined && typeof newOptions.fixed.y === 'boolean') {
  211. parentOptions.fixed.y = newOptions.fixed.y;
  212. }
  213. }
  214. }
  215. // handle the font options
  216. if (newOptions.font !== undefined && newOptions.font !== null) {
  217. Label.parseOptions(parentOptions.font, newOptions);
  218. }
  219. else if (allowDeletion === true && newOptions.font === null) {
  220. parentOptions.font = util.bridgeObject(globalOptions.font); // set the object back to the global options
  221. }
  222. // handle the scaling options, specifically the label part
  223. if (newOptions.scaling !== undefined) {
  224. util.mergeOptions(parentOptions.scaling, newOptions.scaling, 'label', globalOptions.scaling);
  225. }
  226. }
  227. /**
  228. *
  229. * @returns {{color: *, borderWidth: *, borderColor: *, size: *, borderDashes: (boolean|Array|allOptions.nodes.shapeProperties.borderDashes|{boolean, array}), borderRadius: (number|allOptions.nodes.shapeProperties.borderRadius|{number}|Array), shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *}}
  230. */
  231. getFormattingValues() {
  232. let values = {
  233. color: this.options.color.background,
  234. borderWidth: this.options.borderWidth,
  235. borderColor: this.options.color.border,
  236. size: this.options.size,
  237. borderDashes: this.options.shapeProperties.borderDashes,
  238. borderRadius: this.options.shapeProperties.borderRadius,
  239. shadow: this.options.shadow.enabled,
  240. shadowColor: this.options.shadow.color,
  241. shadowSize: this.options.shadow.size,
  242. shadowX: this.options.shadow.x,
  243. shadowY: this.options.shadow.y
  244. };
  245. if (this.selected || this.hover) {
  246. if (this.chooser === true) {
  247. if (this.selected) {
  248. values.borderWidth *= 2;
  249. values.color = this.options.color.highlight.background;
  250. values.borderColor = this.options.color.highlight.border;
  251. values.shadow = this.options.shadow.enabled;
  252. } else if (this.hover) {
  253. values.color = this.options.color.hover.background;
  254. values.borderColor = this.options.color.hover.border;
  255. values.shadow = this.options.shadow.enabled;
  256. }
  257. } else if (typeof this.chooser === 'function') {
  258. this.chooser(values, this.options.id, this.selected, this.hover);
  259. if (values.shadow === false) {
  260. if ((values.shadowColor !== this.options.shadow.color) ||
  261. (values.shadowSize !== this.options.shadow.size) ||
  262. (values.shadowX !== this.options.shadow.x) ||
  263. (values.shadowY !== this.options.shadow.y)) {
  264. values.shadow = true;
  265. }
  266. }
  267. }
  268. } else {
  269. values.shadow = this.options.shadow.enabled;
  270. }
  271. return values;
  272. }
  273. /**
  274. *
  275. * @param {Object} options
  276. */
  277. updateLabelModule(options) {
  278. if (this.options.label === undefined || this.options.label === null) {
  279. this.options.label = '';
  280. }
  281. let pile = [options, this.nodeOptions, this.defaultOptions];
  282. this.labelModule.update(this.options, pile);
  283. if (this.labelModule.baseSize !== undefined) {
  284. this.baseFontSize = this.labelModule.baseSize;
  285. }
  286. }
  287. /**
  288. *
  289. * @param {string} currentShape
  290. */
  291. updateShape(currentShape) {
  292. if (currentShape === this.options.shape && this.shape) {
  293. this.shape.setOptions(this.options, this.imageObj, this.imageObjAlt);
  294. }
  295. else {
  296. // choose draw method depending on the shape
  297. switch (this.options.shape) {
  298. case 'box':
  299. this.shape = new Box(this.options, this.body, this.labelModule);
  300. break;
  301. case 'circle':
  302. this.shape = new Circle(this.options, this.body, this.labelModule);
  303. break;
  304. case 'circularImage':
  305. this.shape = new CircularImage(this.options, this.body, this.labelModule, this.imageObj, this.imageObjAlt);
  306. break;
  307. case 'database':
  308. this.shape = new Database(this.options, this.body, this.labelModule);
  309. break;
  310. case 'diamond':
  311. this.shape = new Diamond(this.options, this.body, this.labelModule);
  312. break;
  313. case 'dot':
  314. this.shape = new Dot(this.options, this.body, this.labelModule);
  315. break;
  316. case 'ellipse':
  317. this.shape = new Ellipse(this.options, this.body, this.labelModule);
  318. break;
  319. case 'icon':
  320. this.shape = new Icon(this.options, this.body, this.labelModule);
  321. break;
  322. case 'image':
  323. this.shape = new Image(this.options, this.body, this.labelModule, this.imageObj, this.imageObjAlt);
  324. break;
  325. case 'square':
  326. this.shape = new Square(this.options, this.body, this.labelModule);
  327. break;
  328. case 'hexagon':
  329. this.shape = new Hexagon(this.options, this.body, this.labelModule);
  330. break;
  331. case 'star':
  332. this.shape = new Star(this.options, this.body, this.labelModule);
  333. break;
  334. case 'text':
  335. this.shape = new Text(this.options, this.body, this.labelModule);
  336. break;
  337. case 'triangle':
  338. this.shape = new Triangle(this.options, this.body, this.labelModule);
  339. break;
  340. case 'triangleDown':
  341. this.shape = new TriangleDown(this.options, this.body, this.labelModule);
  342. break;
  343. default:
  344. this.shape = new Ellipse(this.options, this.body, this.labelModule);
  345. break;
  346. }
  347. }
  348. this.needsRefresh();
  349. }
  350. /**
  351. * select this node
  352. */
  353. select() {
  354. this.selected = true;
  355. this.needsRefresh();
  356. }
  357. /**
  358. * unselect this node
  359. */
  360. unselect() {
  361. this.selected = false;
  362. this.needsRefresh();
  363. }
  364. /**
  365. * Reset the calculated size of the node, forces it to recalculate its size
  366. */
  367. needsRefresh() {
  368. this.shape.refreshNeeded = true;
  369. }
  370. /**
  371. * get the title of this node.
  372. * @return {string} title The title of the node, or undefined when no title
  373. * has been set.
  374. */
  375. getTitle() {
  376. return this.options.title;
  377. }
  378. /**
  379. * Calculate the distance to the border of the Node
  380. * @param {CanvasRenderingContext2D} ctx
  381. * @param {number} angle Angle in radians
  382. * @returns {number} distance Distance to the border in pixels
  383. */
  384. distanceToBorder(ctx, angle) {
  385. return this.shape.distanceToBorder(ctx,angle);
  386. }
  387. /**
  388. * Check if this node has a fixed x and y position
  389. * @return {boolean} true if fixed, false if not
  390. */
  391. isFixed() {
  392. return (this.options.fixed.x && this.options.fixed.y);
  393. }
  394. /**
  395. * check if this node is selecte
  396. * @return {boolean} selected True if node is selected, else false
  397. */
  398. isSelected() {
  399. return this.selected;
  400. }
  401. /**
  402. * Retrieve the value of the node. Can be undefined
  403. * @return {number} value
  404. */
  405. getValue() {
  406. return this.options.value;
  407. }
  408. /**
  409. * Adjust the value range of the node. The node will adjust it's size
  410. * based on its value.
  411. * @param {number} min
  412. * @param {number} max
  413. * @param {number} total
  414. */
  415. setValueRange(min, max, total) {
  416. if (this.options.value !== undefined) {
  417. var scale = this.options.scaling.customScalingFunction(min, max, total, this.options.value);
  418. var sizeDiff = this.options.scaling.max - this.options.scaling.min;
  419. if (this.options.scaling.label.enabled === true) {
  420. var fontDiff = this.options.scaling.label.max - this.options.scaling.label.min;
  421. this.options.font.size = this.options.scaling.label.min + scale * fontDiff;
  422. }
  423. this.options.size = this.options.scaling.min + scale * sizeDiff;
  424. }
  425. else {
  426. this.options.size = this.baseSize;
  427. this.options.font.size = this.baseFontSize;
  428. }
  429. this.updateLabelModule();
  430. }
  431. /**
  432. * Draw this node in the given canvas
  433. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  434. * @param {CanvasRenderingContext2D} ctx
  435. */
  436. draw(ctx) {
  437. let values = this.getFormattingValues();
  438. this.shape.draw(ctx, this.x, this.y, this.selected, this.hover, values);
  439. }
  440. /**
  441. * Update the bounding box of the shape
  442. * @param {CanvasRenderingContext2D} ctx
  443. */
  444. updateBoundingBox(ctx) {
  445. this.shape.updateBoundingBox(this.x,this.y,ctx);
  446. }
  447. /**
  448. * Recalculate the size of this node in the given canvas
  449. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  450. * @param {CanvasRenderingContext2D} ctx
  451. */
  452. resize(ctx) {
  453. let values = this.getFormattingValues();
  454. this.shape.resize(ctx, this.selected, this.hover, values);
  455. }
  456. /**
  457. * Check if this object is overlapping with the provided object
  458. * @param {Object} obj an object with parameters left, top, right, bottom
  459. * @return {boolean} True if location is located on node
  460. */
  461. isOverlappingWith(obj) {
  462. return (
  463. this.shape.left < obj.right &&
  464. this.shape.left + this.shape.width > obj.left &&
  465. this.shape.top < obj.bottom &&
  466. this.shape.top + this.shape.height > obj.top
  467. );
  468. }
  469. /**
  470. * Check if this object is overlapping with the provided object
  471. * @param {Object} obj an object with parameters left, top, right, bottom
  472. * @return {boolean} True if location is located on node
  473. */
  474. isBoundingBoxOverlappingWith(obj) {
  475. return (
  476. this.shape.boundingBox.left < obj.right &&
  477. this.shape.boundingBox.right > obj.left &&
  478. this.shape.boundingBox.top < obj.bottom &&
  479. this.shape.boundingBox.bottom > obj.top
  480. );
  481. }
  482. /**
  483. * Check valid values for mass
  484. *
  485. * The mass may not be negative or zero. If it is, reset to 1
  486. *
  487. * @param {object} options
  488. * @param {Node.id} id
  489. * @static
  490. */
  491. static checkMass(options, id) {
  492. if (options.mass !== undefined && options.mass <= 0) {
  493. let strId = '';
  494. if (id !== undefined) {
  495. strId = ' in node id: ' + id;
  496. }
  497. console.log('%cNegative or zero mass disallowed' + strId +
  498. ', setting mass to 1.' , printStyle);
  499. options.mass = 1;
  500. }
  501. }
  502. }
  503. export default Node;