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.

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