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.

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