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.

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