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.

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