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.

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