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.

1102 lines
36 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
  1. var util = require('../../util');
  2. var DOMutil = require('../../DOMutil');
  3. var DataSet = require('../../DataSet');
  4. var DataView = require('../../DataView');
  5. var Component = require('./Component');
  6. var DataAxis = require('./DataAxis');
  7. var GraphGroup = require('./GraphGroup');
  8. var Legend = require('./Legend');
  9. var Bars = require('./graph2d_types/bar');
  10. var Lines = require('./graph2d_types/line');
  11. var Points = require('./graph2d_types/points');
  12. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  13. /**
  14. * This is the constructor of the LineGraph. It requires a Timeline body and options.
  15. *
  16. * @param {vis.Timeline.body} body
  17. * @param {Object} options
  18. * @constructor
  19. */
  20. function LineGraph(body, options) {
  21. this.id = util.randomUUID();
  22. this.body = body;
  23. this.defaultOptions = {
  24. yAxisOrientation: 'left',
  25. defaultGroup: 'default',
  26. sort: true,
  27. sampling: true,
  28. stack: false,
  29. graphHeight: '400px',
  30. shaded: {
  31. enabled: false,
  32. orientation: 'bottom' // top, bottom, zero
  33. },
  34. style: 'line', // line, bar
  35. barChart: {
  36. width: 50,
  37. sideBySide: false,
  38. align: 'center' // left, center, right
  39. },
  40. interpolation: {
  41. enabled: true,
  42. parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
  43. alpha: 0.5
  44. },
  45. drawPoints: {
  46. enabled: true,
  47. size: 6,
  48. style: 'square' // square, circle
  49. },
  50. dataAxis: {}, //Defaults are done on DataAxis level
  51. legend: {}, //Defaults are done on Legend level
  52. groups: {
  53. visibility: {}
  54. }
  55. };
  56. // options is shared by this lineGraph and all its items
  57. this.options = util.extend({}, this.defaultOptions);
  58. this.dom = {};
  59. this.props = {};
  60. this.hammer = null;
  61. this.groups = {};
  62. this.abortedGraphUpdate = false;
  63. this.updateSVGheight = false;
  64. this.updateSVGheightOnResize = false;
  65. this.forceGraphUpdate = true;
  66. var me = this;
  67. this.itemsData = null; // DataSet
  68. this.groupsData = null; // DataSet
  69. // listeners for the DataSet of the items
  70. this.itemListeners = {
  71. 'add': function (event, params, senderId) { // eslint-disable-line no-unused-vars
  72. me._onAdd(params.items);
  73. },
  74. 'update': function (event, params, senderId) { // eslint-disable-line no-unused-vars
  75. me._onUpdate(params.items);
  76. },
  77. 'remove': function (event, params, senderId) { // eslint-disable-line no-unused-vars
  78. me._onRemove(params.items);
  79. }
  80. };
  81. // listeners for the DataSet of the groups
  82. this.groupListeners = {
  83. 'add': function (event, params, senderId) { // eslint-disable-line no-unused-vars
  84. me._onAddGroups(params.items);
  85. },
  86. 'update': function (event, params, senderId) { // eslint-disable-line no-unused-vars
  87. me._onUpdateGroups(params.items);
  88. },
  89. 'remove': function (event, params, senderId) { // eslint-disable-line no-unused-vars
  90. me._onRemoveGroups(params.items);
  91. }
  92. };
  93. this.items = {}; // object with an Item for every data item
  94. this.selection = []; // list with the ids of all selected nodes
  95. this.lastStart = this.body.range.start;
  96. this.touchParams = {}; // stores properties while dragging
  97. this.svgElements = {};
  98. this.setOptions(options);
  99. this.groupsUsingDefaultStyles = [0];
  100. this.body.emitter.on('rangechanged', function () {
  101. me.lastStart = me.body.range.start;
  102. me.svg.style.left = util.option.asSize(-me.props.width);
  103. me.forceGraphUpdate = true;
  104. //Is this local redraw necessary? (Core also does a change event!)
  105. me.redraw.call(me);
  106. });
  107. // create the HTML DOM
  108. this._create();
  109. this.framework = {svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups};
  110. }
  111. LineGraph.prototype = new Component();
  112. /**
  113. * Create the HTML DOM for the ItemSet
  114. */
  115. LineGraph.prototype._create = function () {
  116. var frame = document.createElement('div');
  117. frame.className = 'vis-line-graph';
  118. this.dom.frame = frame;
  119. // create svg element for graph drawing.
  120. this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  121. this.svg.style.position = 'relative';
  122. this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px';
  123. this.svg.style.display = 'block';
  124. frame.appendChild(this.svg);
  125. // data axis
  126. this.options.dataAxis.orientation = 'left';
  127. this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  128. this.options.dataAxis.orientation = 'right';
  129. this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  130. delete this.options.dataAxis.orientation;
  131. // legends
  132. this.legendLeft = new Legend(this.body, this.options.legend, 'left', this.options.groups);
  133. this.legendRight = new Legend(this.body, this.options.legend, 'right', this.options.groups);
  134. this.show();
  135. };
  136. /**
  137. * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element.
  138. * @param {object} options
  139. */
  140. LineGraph.prototype.setOptions = function (options) {
  141. if (options) {
  142. var fields = ['sampling', 'defaultGroup', 'stack', 'height', 'graphHeight', 'yAxisOrientation', 'style', 'barChart', 'dataAxis', 'sort', 'groups'];
  143. if (options.graphHeight === undefined && options.height !== undefined) {
  144. this.updateSVGheight = true;
  145. this.updateSVGheightOnResize = true;
  146. }
  147. else if (this.body.domProps.centerContainer.height !== undefined && options.graphHeight !== undefined) {
  148. if (parseInt((options.graphHeight + '').replace("px", '')) < this.body.domProps.centerContainer.height) {
  149. this.updateSVGheight = true;
  150. }
  151. }
  152. util.selectiveDeepExtend(fields, this.options, options);
  153. util.mergeOptions(this.options, options, 'interpolation');
  154. util.mergeOptions(this.options, options, 'drawPoints');
  155. util.mergeOptions(this.options, options, 'shaded');
  156. util.mergeOptions(this.options, options, 'legend');
  157. if (options.interpolation) {
  158. if (typeof options.interpolation == 'object') {
  159. if (options.interpolation.parametrization) {
  160. if (options.interpolation.parametrization == 'uniform') {
  161. this.options.interpolation.alpha = 0;
  162. }
  163. else if (options.interpolation.parametrization == 'chordal') {
  164. this.options.interpolation.alpha = 1.0;
  165. }
  166. else {
  167. this.options.interpolation.parametrization = 'centripetal';
  168. this.options.interpolation.alpha = 0.5;
  169. }
  170. }
  171. }
  172. }
  173. if (this.yAxisLeft) {
  174. if (options.dataAxis !== undefined) {
  175. this.yAxisLeft.setOptions(this.options.dataAxis);
  176. this.yAxisRight.setOptions(this.options.dataAxis);
  177. }
  178. }
  179. if (this.legendLeft) {
  180. if (options.legend !== undefined) {
  181. this.legendLeft.setOptions(this.options.legend);
  182. this.legendRight.setOptions(this.options.legend);
  183. }
  184. }
  185. if (this.groups.hasOwnProperty(UNGROUPED)) {
  186. this.groups[UNGROUPED].setOptions(options);
  187. }
  188. }
  189. // this is used to redraw the graph if the visibility of the groups is changed.
  190. if (this.dom.frame) { //not on initial run?
  191. this.forceGraphUpdate=true;
  192. this.body.emitter.emit("_change",{queue: true});
  193. }
  194. };
  195. /**
  196. * Hide the component from the DOM
  197. */
  198. LineGraph.prototype.hide = function () {
  199. // remove the frame containing the items
  200. if (this.dom.frame.parentNode) {
  201. this.dom.frame.parentNode.removeChild(this.dom.frame);
  202. }
  203. };
  204. /**
  205. * Show the component in the DOM (when not already visible).
  206. */
  207. LineGraph.prototype.show = function () {
  208. // show frame containing the items
  209. if (!this.dom.frame.parentNode) {
  210. this.body.dom.center.appendChild(this.dom.frame);
  211. }
  212. };
  213. /**
  214. * Set items
  215. * @param {vis.DataSet | null} items
  216. */
  217. LineGraph.prototype.setItems = function (items) {
  218. var me = this,
  219. ids,
  220. oldItemsData = this.itemsData;
  221. // replace the dataset
  222. if (!items) {
  223. this.itemsData = null;
  224. }
  225. else if (items instanceof DataSet || items instanceof DataView) {
  226. this.itemsData = items;
  227. }
  228. else {
  229. throw new TypeError('Data must be an instance of DataSet or DataView');
  230. }
  231. if (oldItemsData) {
  232. // unsubscribe from old dataset
  233. util.forEach(this.itemListeners, function (callback, event) {
  234. oldItemsData.off(event, callback);
  235. });
  236. // remove all drawn items
  237. ids = oldItemsData.getIds();
  238. this._onRemove(ids);
  239. }
  240. if (this.itemsData) {
  241. // subscribe to new dataset
  242. var id = this.id;
  243. util.forEach(this.itemListeners, function (callback, event) {
  244. me.itemsData.on(event, callback, id);
  245. });
  246. // add all new items
  247. ids = this.itemsData.getIds();
  248. this._onAdd(ids);
  249. }
  250. };
  251. /**
  252. * Set groups
  253. * @param {vis.DataSet} groups
  254. */
  255. LineGraph.prototype.setGroups = function (groups) {
  256. var me = this;
  257. var ids;
  258. // unsubscribe from current dataset
  259. if (this.groupsData) {
  260. util.forEach(this.groupListeners, function (callback, event) {
  261. me.groupsData.off(event, callback);
  262. });
  263. // remove all drawn groups
  264. ids = this.groupsData.getIds();
  265. this.groupsData = null;
  266. for (var i = 0; i < ids.length; i++) {
  267. this._removeGroup(ids[i]);
  268. }
  269. }
  270. // replace the dataset
  271. if (!groups) {
  272. this.groupsData = null;
  273. }
  274. else if (groups instanceof DataSet || groups instanceof DataView) {
  275. this.groupsData = groups;
  276. }
  277. else {
  278. throw new TypeError('Data must be an instance of DataSet or DataView');
  279. }
  280. if (this.groupsData) {
  281. // subscribe to new dataset
  282. var id = this.id;
  283. util.forEach(this.groupListeners, function (callback, event) {
  284. me.groupsData.on(event, callback, id);
  285. });
  286. // draw all ms
  287. ids = this.groupsData.getIds();
  288. this._onAddGroups(ids);
  289. }
  290. };
  291. LineGraph.prototype._onUpdate = function (ids) {
  292. this._updateAllGroupData(ids);
  293. };
  294. LineGraph.prototype._onAdd = function (ids) {
  295. this._onUpdate(ids);
  296. };
  297. LineGraph.prototype._onRemove = function (ids) {
  298. this._onUpdate(ids);
  299. };
  300. LineGraph.prototype._onUpdateGroups = function (groupIds) {
  301. this._updateAllGroupData(null, groupIds);
  302. };
  303. LineGraph.prototype._onAddGroups = function (groupIds) {
  304. this._onUpdateGroups(groupIds);
  305. };
  306. /**
  307. * this cleans the group out off the legends and the dataaxis, updates the ungrouped and updates the graph
  308. * @param {Array} groupIds
  309. * @private
  310. */
  311. LineGraph.prototype._onRemoveGroups = function (groupIds) {
  312. for (var i = 0; i < groupIds.length; i++) {
  313. this._removeGroup(groupIds[i]);
  314. }
  315. this.forceGraphUpdate = true;
  316. this.body.emitter.emit("_change",{queue: true});
  317. };
  318. /**
  319. * this cleans the group out off the legends and the dataaxis
  320. * @param {vis.GraphGroup.id} groupId
  321. * @private
  322. */
  323. LineGraph.prototype._removeGroup = function (groupId) {
  324. if (this.groups.hasOwnProperty(groupId)) {
  325. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  326. this.yAxisRight.removeGroup(groupId);
  327. this.legendRight.removeGroup(groupId);
  328. this.legendRight.redraw();
  329. }
  330. else {
  331. this.yAxisLeft.removeGroup(groupId);
  332. this.legendLeft.removeGroup(groupId);
  333. this.legendLeft.redraw();
  334. }
  335. delete this.groups[groupId];
  336. }
  337. };
  338. /**
  339. * update a group object with the group dataset entree
  340. *
  341. * @param {vis.GraphGroup} group
  342. * @param {vis.GraphGroup.id} groupId
  343. * @private
  344. */
  345. LineGraph.prototype._updateGroup = function (group, groupId) {
  346. if (!this.groups.hasOwnProperty(groupId)) {
  347. this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles);
  348. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  349. this.yAxisRight.addGroup(groupId, this.groups[groupId]);
  350. this.legendRight.addGroup(groupId, this.groups[groupId]);
  351. }
  352. else {
  353. this.yAxisLeft.addGroup(groupId, this.groups[groupId]);
  354. this.legendLeft.addGroup(groupId, this.groups[groupId]);
  355. }
  356. }
  357. else {
  358. this.groups[groupId].update(group);
  359. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  360. this.yAxisRight.updateGroup(groupId, this.groups[groupId]);
  361. this.legendRight.updateGroup(groupId, this.groups[groupId]);
  362. //If yAxisOrientation changed, clean out the group from the other axis.
  363. this.yAxisLeft.removeGroup(groupId);
  364. this.legendLeft.removeGroup(groupId);
  365. }
  366. else {
  367. this.yAxisLeft.updateGroup(groupId, this.groups[groupId]);
  368. this.legendLeft.updateGroup(groupId, this.groups[groupId]);
  369. //If yAxisOrientation changed, clean out the group from the other axis.
  370. this.yAxisRight.removeGroup(groupId);
  371. this.legendRight.removeGroup(groupId);
  372. }
  373. }
  374. this.legendLeft.redraw();
  375. this.legendRight.redraw();
  376. };
  377. /**
  378. * this updates all groups, it is used when there is an update the the itemset.
  379. *
  380. * @param {Array} ids
  381. * @param {Array} groupIds
  382. * @private
  383. */
  384. LineGraph.prototype._updateAllGroupData = function (ids, groupIds) {
  385. if (this.itemsData != null) {
  386. var groupsContent = {};
  387. var items = this.itemsData.get();
  388. var fieldId = this.itemsData._fieldId;
  389. var idMap = {};
  390. if (ids){
  391. ids.map(function (id) {
  392. idMap[id] = id;
  393. });
  394. }
  395. //pre-Determine array sizes, for more efficient memory claim
  396. var groupCounts = {};
  397. for (var i = 0; i < items.length; i++) {
  398. var item = items[i];
  399. var groupId = item.group;
  400. if (groupId === null || groupId === undefined) {
  401. groupId = UNGROUPED;
  402. }
  403. groupCounts.hasOwnProperty(groupId) ? groupCounts[groupId]++ : groupCounts[groupId] = 1;
  404. }
  405. //Pre-load arrays from existing groups if items are not changed (not in ids)
  406. var existingItemsMap = {};
  407. if (!groupIds && ids) {
  408. for (groupId in this.groups) {
  409. if (this.groups.hasOwnProperty(groupId)) {
  410. group = this.groups[groupId];
  411. var existing_items = group.getItems();
  412. groupsContent[groupId] = existing_items.filter(function (item) {
  413. existingItemsMap[item[fieldId]] = item[fieldId];
  414. return (item[fieldId] !== idMap[item[fieldId]]);
  415. });
  416. var newLength = groupCounts[groupId];
  417. groupCounts[groupId] -= groupsContent[groupId].length;
  418. if (groupsContent[groupId].length < newLength) {
  419. groupsContent[groupId][newLength - 1] = {};
  420. }
  421. }
  422. }
  423. }
  424. //Now insert data into the arrays.
  425. for (i = 0; i < items.length; i++) {
  426. item = items[i];
  427. groupId = item.group;
  428. if (groupId === null || groupId === undefined) {
  429. groupId = UNGROUPED;
  430. }
  431. if (!groupIds && ids && (item[fieldId] !== idMap[item[fieldId]]) && existingItemsMap.hasOwnProperty(item[fieldId])) {
  432. continue;
  433. }
  434. if (!groupsContent.hasOwnProperty(groupId)) {
  435. groupsContent[groupId] = new Array(groupCounts[groupId]);
  436. }
  437. //Copy data (because of unmodifiable DataView input.
  438. var extended = util.bridgeObject(item);
  439. extended.x = util.convert(item.x, 'Date');
  440. extended.end = util.convert(item.end, 'Date');
  441. extended.orginalY = item.y; //real Y
  442. extended.y = Number(item.y);
  443. extended[fieldId] = item[fieldId];
  444. var index= groupsContent[groupId].length - groupCounts[groupId]--;
  445. groupsContent[groupId][index] = extended;
  446. }
  447. //Make sure all groups are present, to allow removal of old groups
  448. for (groupId in this.groups){
  449. if (this.groups.hasOwnProperty(groupId)){
  450. if (!groupsContent.hasOwnProperty(groupId)) {
  451. groupsContent[groupId] = new Array(0);
  452. }
  453. }
  454. }
  455. //Update legendas, style and axis
  456. for (groupId in groupsContent) {
  457. if (groupsContent.hasOwnProperty(groupId)) {
  458. if (groupsContent[groupId].length == 0) {
  459. if (this.groups.hasOwnProperty(groupId)) {
  460. this._removeGroup(groupId);
  461. }
  462. } else {
  463. var group = undefined;
  464. if (this.groupsData != undefined) {
  465. group = this.groupsData.get(groupId);
  466. }
  467. if (group == undefined) {
  468. group = {id: groupId, content: this.options.defaultGroup + groupId};
  469. }
  470. this._updateGroup(group, groupId);
  471. this.groups[groupId].setItems(groupsContent[groupId]);
  472. }
  473. }
  474. }
  475. this.forceGraphUpdate = true;
  476. this.body.emitter.emit("_change",{queue: true});
  477. }
  478. };
  479. /**
  480. * Redraw the component, mandatory function
  481. * @return {boolean} Returns true if the component is resized
  482. */
  483. LineGraph.prototype.redraw = function () {
  484. var resized = false;
  485. // calculate actual size and position
  486. this.props.width = this.dom.frame.offsetWidth;
  487. this.props.height = this.body.domProps.centerContainer.height
  488. - this.body.domProps.border.top
  489. - this.body.domProps.border.bottom;
  490. // check if this component is resized
  491. resized = this._isResized() || resized;
  492. // check whether zoomed (in that case we need to re-stack everything)
  493. var visibleInterval = this.body.range.end - this.body.range.start;
  494. var zoomed = (visibleInterval != this.lastVisibleInterval);
  495. this.lastVisibleInterval = visibleInterval;
  496. // the svg element is three times as big as the width, this allows for fully dragging left and right
  497. // without reloading the graph. the controls for this are bound to events in the constructor
  498. if (resized == true) {
  499. this.svg.style.width = util.option.asSize(3 * this.props.width);
  500. this.svg.style.left = util.option.asSize(-this.props.width);
  501. // if the height of the graph is set as proportional, change the height of the svg
  502. if ((this.options.height + '').indexOf("%") != -1 || this.updateSVGheightOnResize == true) {
  503. this.updateSVGheight = true;
  504. }
  505. }
  506. // update the height of the graph on each redraw of the graph.
  507. if (this.updateSVGheight == true) {
  508. if (this.options.graphHeight != this.props.height + 'px') {
  509. this.options.graphHeight = this.props.height + 'px';
  510. this.svg.style.height = this.props.height + 'px';
  511. }
  512. this.updateSVGheight = false;
  513. }
  514. else {
  515. this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px';
  516. }
  517. // zoomed is here to ensure that animations are shown correctly.
  518. if (resized == true || zoomed == true || this.abortedGraphUpdate == true || this.forceGraphUpdate == true) {
  519. resized = this._updateGraph() || resized;
  520. this.forceGraphUpdate = false;
  521. }
  522. else {
  523. // move the whole svg while dragging
  524. if (this.lastStart != 0) {
  525. var offset = this.body.range.start - this.lastStart;
  526. var range = this.body.range.end - this.body.range.start;
  527. if (this.props.width != 0) {
  528. var rangePerPixelInv = this.props.width / range;
  529. var xOffset = offset * rangePerPixelInv;
  530. this.svg.style.left = (-this.props.width - xOffset) + 'px';
  531. }
  532. }
  533. }
  534. this.legendLeft.redraw();
  535. this.legendRight.redraw();
  536. return resized;
  537. };
  538. LineGraph.prototype._getSortedGroupIds = function(){
  539. // getting group Ids
  540. var grouplist = [];
  541. for (var groupId in this.groups) {
  542. if (this.groups.hasOwnProperty(groupId)) {
  543. var group = this.groups[groupId];
  544. if (group.visible == true && (this.options.groups.visibility[groupId] === undefined || this.options.groups.visibility[groupId] == true)) {
  545. grouplist.push({id:groupId,zIndex:group.options.zIndex});
  546. }
  547. }
  548. }
  549. util.insertSort(grouplist,function(a,b){
  550. var az = a.zIndex;
  551. var bz = b.zIndex;
  552. if (az === undefined) az=0;
  553. if (bz === undefined) bz=0;
  554. return az==bz? 0: (az<bz ? -1: 1);
  555. });
  556. var groupIds = new Array(grouplist.length);
  557. for (var i=0; i< grouplist.length; i++){
  558. groupIds[i] = grouplist[i].id;
  559. }
  560. return groupIds;
  561. };
  562. /**
  563. * Update and redraw the graph.
  564. *
  565. * @returns {boolean}
  566. * @private
  567. */
  568. LineGraph.prototype._updateGraph = function () {
  569. // reset the svg elements
  570. DOMutil.prepareElements(this.svgElements);
  571. if (this.props.width != 0 && this.itemsData != null) {
  572. var group, i;
  573. var groupRanges = {};
  574. var changeCalled = false;
  575. // this is the range of the SVG canvas
  576. var minDate = this.body.util.toGlobalTime(-this.body.domProps.root.width);
  577. var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width);
  578. // getting group Ids
  579. var groupIds = this._getSortedGroupIds();
  580. if (groupIds.length > 0) {
  581. var groupsData = {};
  582. // fill groups data, this only loads the data we require based on the timewindow
  583. this._getRelevantData(groupIds, groupsData, minDate, maxDate);
  584. // apply sampling, if disabled, it will pass through this function.
  585. this._applySampling(groupIds, groupsData);
  586. // we transform the X coordinates to detect collisions
  587. for (i = 0; i < groupIds.length; i++) {
  588. this._convertXcoordinates(groupsData[groupIds[i]]);
  589. }
  590. // now all needed data has been collected we start the processing.
  591. this._getYRanges(groupIds, groupsData, groupRanges);
  592. // update the Y axis first, we use this data to draw at the correct Y points
  593. changeCalled = this._updateYAxis(groupIds, groupRanges);
  594. // at changeCalled, abort this update cycle as the graph needs another update with new Width input from the Redraw container.
  595. // Cleanup SVG elements on abort.
  596. if (changeCalled == true) {
  597. DOMutil.cleanupElements(this.svgElements);
  598. this.abortedGraphUpdate = true;
  599. return true;
  600. }
  601. this.abortedGraphUpdate = false;
  602. // With the yAxis scaled correctly, use this to get the Y values of the points.
  603. var below = undefined;
  604. for (i = 0; i < groupIds.length; i++) {
  605. group = this.groups[groupIds[i]];
  606. if (this.options.stack === true && this.options.style === 'line') {
  607. if (group.options.excludeFromStacking == undefined || !group.options.excludeFromStacking) {
  608. if (below != undefined) {
  609. this._stack(groupsData[group.id], groupsData[below.id]);
  610. if (group.options.shaded.enabled == true && group.options.shaded.orientation !== "group"){
  611. if (group.options.shaded.orientation == "top" && below.options.shaded.orientation !== "group"){
  612. below.options.shaded.orientation="group";
  613. below.options.shaded.groupId=group.id;
  614. } else {
  615. group.options.shaded.orientation="group";
  616. group.options.shaded.groupId=below.id;
  617. }
  618. }
  619. }
  620. below = group;
  621. }
  622. }
  623. this._convertYcoordinates(groupsData[groupIds[i]], group);
  624. }
  625. //Precalculate paths and draw shading if appropriate. This will make sure the shading is always behind any lines.
  626. var paths = {};
  627. for (i = 0; i < groupIds.length; i++) {
  628. group = this.groups[groupIds[i]];
  629. if (group.options.style === 'line' && group.options.shaded.enabled == true) {
  630. var dataset = groupsData[groupIds[i]];
  631. if (dataset == null || dataset.length == 0) {
  632. continue;
  633. }
  634. if (!paths.hasOwnProperty(groupIds[i])) {
  635. paths[groupIds[i]] = Lines.calcPath(dataset, group);
  636. }
  637. if (group.options.shaded.orientation === "group") {
  638. var subGroupId = group.options.shaded.groupId;
  639. if (groupIds.indexOf(subGroupId) === -1) {
  640. console.log(group.id + ": Unknown shading group target given:" + subGroupId);
  641. continue;
  642. }
  643. if (!paths.hasOwnProperty(subGroupId)) {
  644. paths[subGroupId] = Lines.calcPath(groupsData[subGroupId], this.groups[subGroupId]);
  645. }
  646. Lines.drawShading(paths[groupIds[i]], group, paths[subGroupId], this.framework);
  647. }
  648. else {
  649. Lines.drawShading(paths[groupIds[i]], group, undefined, this.framework);
  650. }
  651. }
  652. }
  653. // draw the groups, calculating paths if still necessary.
  654. Bars.draw(groupIds, groupsData, this.framework);
  655. for (i = 0; i < groupIds.length; i++) {
  656. group = this.groups[groupIds[i]];
  657. if (groupsData[groupIds[i]].length > 0) {
  658. switch (group.options.style) {
  659. case "line":
  660. if (!paths.hasOwnProperty(groupIds[i])) {
  661. paths[groupIds[i]] = Lines.calcPath(groupsData[groupIds[i]], group);
  662. }
  663. Lines.draw(paths[groupIds[i]], group, this.framework);
  664. // eslint-disable-line no-fallthrough
  665. case "point":
  666. // eslint-disable-line no-fallthrough
  667. case "points":
  668. if (group.options.style == "point" || group.options.style == "points" || group.options.drawPoints.enabled == true) {
  669. Points.draw(groupsData[groupIds[i]], group, this.framework);
  670. }
  671. break;
  672. case "bar":
  673. // bar needs to be drawn enmasse
  674. // eslint-disable-line no-fallthrough
  675. default:
  676. //do nothing...
  677. }
  678. }
  679. }
  680. }
  681. }
  682. // cleanup unused svg elements
  683. DOMutil.cleanupElements(this.svgElements);
  684. return false;
  685. };
  686. LineGraph.prototype._stack = function (data, subData) {
  687. var index, dx, dy, subPrevPoint, subNextPoint;
  688. index = 0;
  689. // for each data point we look for a matching on in the set below
  690. for (var j = 0; j < data.length; j++) {
  691. subPrevPoint = undefined;
  692. subNextPoint = undefined;
  693. // we look for time matches or a before-after point
  694. for (var k = index; k < subData.length; k++) {
  695. // if times match exactly
  696. if (subData[k].x === data[j].x) {
  697. subPrevPoint = subData[k];
  698. subNextPoint = subData[k];
  699. index = k;
  700. break;
  701. }
  702. else if (subData[k].x > data[j].x) { // overshoot
  703. subNextPoint = subData[k];
  704. if (k == 0) {
  705. subPrevPoint = subNextPoint;
  706. }
  707. else {
  708. subPrevPoint = subData[k - 1];
  709. }
  710. index = k;
  711. break;
  712. }
  713. }
  714. // in case the last data point has been used, we assume it stays like this.
  715. if (subNextPoint === undefined) {
  716. subPrevPoint = subData[subData.length - 1];
  717. subNextPoint = subData[subData.length - 1];
  718. }
  719. // linear interpolation
  720. dx = subNextPoint.x - subPrevPoint.x;
  721. dy = subNextPoint.y - subPrevPoint.y;
  722. if (dx == 0) {
  723. data[j].y = data[j].orginalY + subNextPoint.y;
  724. }
  725. else {
  726. data[j].y = data[j].orginalY + (dy / dx) * (data[j].x - subPrevPoint.x) + subPrevPoint.y; // ax + b where b is data[j].y
  727. }
  728. }
  729. }
  730. /**
  731. * first select and preprocess the data from the datasets.
  732. * the groups have their preselection of data, we now loop over this data to see
  733. * what data we need to draw. Sorted data is much faster.
  734. * more optimization is possible by doing the sampling before and using the binary search
  735. * to find the end date to determine the increment.
  736. *
  737. * @param {array} groupIds
  738. * @param {object} groupsData
  739. * @param {date} minDate
  740. * @param {date} maxDate
  741. * @private
  742. */
  743. LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) {
  744. var group, i, j, item;
  745. if (groupIds.length > 0) {
  746. for (i = 0; i < groupIds.length; i++) {
  747. group = this.groups[groupIds[i]];
  748. var itemsData = group.getItems();
  749. // optimization for sorted data
  750. if (group.options.sort == true) {
  751. var dateComparator = function (a, b) {
  752. return a.getTime() == b.getTime() ? 0 : a < b ? -1 : 1
  753. };
  754. var first = Math.max(0, util.binarySearchValue(itemsData, minDate, 'x', 'before', dateComparator));
  755. var last = Math.min(itemsData.length, util.binarySearchValue(itemsData, maxDate, 'x', 'after', dateComparator) + 1);
  756. if (last <= 0) {
  757. last = itemsData.length;
  758. }
  759. var dataContainer = new Array(last-first);
  760. for (j = first; j < last; j++) {
  761. item = group.itemsData[j];
  762. dataContainer[j-first] = item;
  763. }
  764. groupsData[groupIds[i]] = dataContainer;
  765. }
  766. else {
  767. // If unsorted data, all data is relevant, just returning entire structure
  768. groupsData[groupIds[i]] = group.itemsData;
  769. }
  770. }
  771. }
  772. };
  773. /**
  774. *
  775. * @param {Array<vis.GraphGroup.id>} groupIds
  776. * @param {vis.DataSet} groupsData
  777. * @private
  778. */
  779. LineGraph.prototype._applySampling = function (groupIds, groupsData) {
  780. var group;
  781. if (groupIds.length > 0) {
  782. for (var i = 0; i < groupIds.length; i++) {
  783. group = this.groups[groupIds[i]];
  784. if (group.options.sampling == true) {
  785. var dataContainer = groupsData[groupIds[i]];
  786. if (dataContainer.length > 0) {
  787. var increment = 1;
  788. var amountOfPoints = dataContainer.length;
  789. // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
  790. // of width changing of the yAxis.
  791. //TODO: This assumes sorted data, but that's not guaranteed!
  792. var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x);
  793. var pointsPerPixel = amountOfPoints / xDistance;
  794. increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel)));
  795. var sampledData = new Array(amountOfPoints);
  796. for (var j = 0; j < amountOfPoints; j += increment) {
  797. var idx = Math.round(j/increment);
  798. sampledData[idx]=dataContainer[j];
  799. }
  800. groupsData[groupIds[i]] = sampledData.splice(0,Math.round(amountOfPoints/increment));
  801. }
  802. }
  803. }
  804. }
  805. };
  806. /**
  807. *
  808. * @param {Array<vis.GraphGroup.id>} groupIds
  809. * @param {vis.DataSet} groupsData
  810. * @param {object} groupRanges | this is being filled here
  811. * @private
  812. */
  813. LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) {
  814. var groupData, group, i;
  815. var combinedDataLeft = [];
  816. var combinedDataRight = [];
  817. var options;
  818. if (groupIds.length > 0) {
  819. for (i = 0; i < groupIds.length; i++) {
  820. groupData = groupsData[groupIds[i]];
  821. options = this.groups[groupIds[i]].options;
  822. if (groupData.length > 0) {
  823. group = this.groups[groupIds[i]];
  824. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  825. if (options.stack === true && options.style === 'bar') {
  826. if (options.yAxisOrientation === 'left') {
  827. combinedDataLeft = combinedDataLeft.concat(groupData);
  828. }
  829. else {
  830. combinedDataRight = combinedDataRight.concat(groupData);
  831. }
  832. }
  833. else {
  834. groupRanges[groupIds[i]] = group.getYRange(groupData, groupIds[i]);
  835. }
  836. }
  837. }
  838. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  839. Bars.getStackedYRange(combinedDataLeft, groupRanges, groupIds, '__barStackLeft', 'left');
  840. Bars.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__barStackRight', 'right');
  841. }
  842. };
  843. /**
  844. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  845. * @param {Array<vis.GraphGroup.id>} groupIds
  846. * @param {Object} groupRanges
  847. * @returns {boolean} resized
  848. * @private
  849. */
  850. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  851. var resized = false;
  852. var yAxisLeftUsed = false;
  853. var yAxisRightUsed = false;
  854. var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal;
  855. // if groups are present
  856. if (groupIds.length > 0) {
  857. // this is here to make sure that if there are no items in the axis but there are groups, that there is no infinite draw/redraw loop.
  858. for (var i = 0; i < groupIds.length; i++) {
  859. var group = this.groups[groupIds[i]];
  860. if (group && group.options.yAxisOrientation != 'right') {
  861. yAxisLeftUsed = true;
  862. minLeft = 1e9;
  863. maxLeft = -1e9;
  864. }
  865. else if (group && group.options.yAxisOrientation) {
  866. yAxisRightUsed = true;
  867. minRight = 1e9;
  868. maxRight = -1e9;
  869. }
  870. }
  871. // if there are items:
  872. for (i = 0; i < groupIds.length; i++) {
  873. if (groupRanges.hasOwnProperty(groupIds[i])) {
  874. if (groupRanges[groupIds[i]].ignore !== true) {
  875. minVal = groupRanges[groupIds[i]].min;
  876. maxVal = groupRanges[groupIds[i]].max;
  877. if (groupRanges[groupIds[i]].yAxisOrientation != 'right') {
  878. yAxisLeftUsed = true;
  879. minLeft = minLeft > minVal ? minVal : minLeft;
  880. maxLeft = maxLeft < maxVal ? maxVal : maxLeft;
  881. }
  882. else {
  883. yAxisRightUsed = true;
  884. minRight = minRight > minVal ? minVal : minRight;
  885. maxRight = maxRight < maxVal ? maxVal : maxRight;
  886. }
  887. }
  888. }
  889. }
  890. if (yAxisLeftUsed == true) {
  891. this.yAxisLeft.setRange(minLeft, maxLeft);
  892. }
  893. if (yAxisRightUsed == true) {
  894. this.yAxisRight.setRange(minRight, maxRight);
  895. }
  896. }
  897. resized = this._toggleAxisVisiblity(yAxisLeftUsed, this.yAxisLeft) || resized;
  898. resized = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || resized;
  899. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  900. this.yAxisLeft.drawIcons = true;
  901. this.yAxisRight.drawIcons = true;
  902. }
  903. else {
  904. this.yAxisLeft.drawIcons = false;
  905. this.yAxisRight.drawIcons = false;
  906. }
  907. this.yAxisRight.master = !yAxisLeftUsed;
  908. this.yAxisRight.masterAxis = this.yAxisLeft;
  909. if (this.yAxisRight.master == false) {
  910. if (yAxisRightUsed == true) {
  911. this.yAxisLeft.lineOffset = this.yAxisRight.width;
  912. }
  913. else {
  914. this.yAxisLeft.lineOffset = 0;
  915. }
  916. resized = this.yAxisLeft.redraw() || resized;
  917. resized = this.yAxisRight.redraw() || resized;
  918. }
  919. else {
  920. resized = this.yAxisRight.redraw() || resized;
  921. }
  922. // clean the accumulated lists
  923. var tempGroups = ['__barStackLeft', '__barStackRight', '__lineStackLeft', '__lineStackRight'];
  924. for (i = 0; i < tempGroups.length; i++) {
  925. if (groupIds.indexOf(tempGroups[i]) != -1) {
  926. groupIds.splice(groupIds.indexOf(tempGroups[i]), 1);
  927. }
  928. }
  929. return resized;
  930. };
  931. /**
  932. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  933. *
  934. * @param {boolean} axisUsed
  935. * @param {vis.DataAxis} axis
  936. * @returns {boolean}
  937. * @private
  938. */
  939. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  940. var changed = false;
  941. if (axisUsed == false) {
  942. if (axis.dom.frame.parentNode && axis.hidden == false) {
  943. axis.hide();
  944. changed = true;
  945. }
  946. }
  947. else {
  948. if (!axis.dom.frame.parentNode && axis.hidden == true) {
  949. axis.show();
  950. changed = true;
  951. }
  952. }
  953. return changed;
  954. };
  955. /**
  956. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  957. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  958. * the yAxis.
  959. *
  960. * @param {Array<Object>} datapoints
  961. * @private
  962. */
  963. LineGraph.prototype._convertXcoordinates = function (datapoints) {
  964. var toScreen = this.body.util.toScreen;
  965. for (var i = 0; i < datapoints.length; i++) {
  966. datapoints[i].screen_x = toScreen(datapoints[i].x) + this.props.width;
  967. datapoints[i].screen_y = datapoints[i].y; //starting point for range calculations
  968. if (datapoints[i].end != undefined) {
  969. datapoints[i].screen_end = toScreen(datapoints[i].end) + this.props.width;
  970. }
  971. else {
  972. datapoints[i].screen_end = undefined;
  973. }
  974. }
  975. };
  976. /**
  977. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  978. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  979. * the yAxis.
  980. *
  981. * @param {Array<Object>} datapoints
  982. * @param {vis.GraphGroup} group
  983. * @private
  984. */
  985. LineGraph.prototype._convertYcoordinates = function (datapoints, group) {
  986. var axis = this.yAxisLeft;
  987. var svgHeight = Number(this.svg.style.height.replace('px', ''));
  988. if (group.options.yAxisOrientation == 'right') {
  989. axis = this.yAxisRight;
  990. }
  991. for (var i = 0; i < datapoints.length; i++) {
  992. datapoints[i].screen_y = Math.round(axis.convertValue(datapoints[i].y));
  993. }
  994. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  995. };
  996. module.exports = LineGraph;