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.

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