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.

993 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
  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.updateSVGheight = 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.props.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','height','graphHeight','yAxisOrientation','style','barChart','dataAxis','sort','groups'];
  175. if (options.graphHeight === undefined && options.height !== undefined && this.body.domProps.centerContainer.height !== undefined) {
  176. this.updateSVGheight = 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.updateSVGheight = 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. // calculate actual size and position
  488. this.props.width = this.dom.frame.offsetWidth;
  489. this.props.height = this.body.domProps.centerContainer.height;
  490. // update the graph if there is no lastWidth or with, used for the initial draw
  491. if (this.lastWidth === undefined && this.props.width) {
  492. forceGraphUpdate = true;
  493. }
  494. // check if this component is resized
  495. resized = this._isResized() || resized;
  496. // check whether zoomed (in that case we need to re-stack everything)
  497. var visibleInterval = this.body.range.end - this.body.range.start;
  498. var zoomed = (visibleInterval != this.lastVisibleInterval);
  499. this.lastVisibleInterval = visibleInterval;
  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.props.width);
  504. this.svg.style.left = util.option.asSize(-this.props.width);
  505. // if the height of the graph is set as proportional, change the height of the svg
  506. if ((this.options.height + '').indexOf("%") != -1) {
  507. this.updateSVGheight = true;
  508. }
  509. }
  510. // update the height of the graph on each redraw of the graph.
  511. if (this.updateSVGheight == true) {
  512. if (this.options.graphHeight != this.body.domProps.centerContainer.height + 'px') {
  513. this.options.graphHeight = this.body.domProps.centerContainer.height + 'px';
  514. this.svg.style.height = this.body.domProps.centerContainer.height + 'px';
  515. }
  516. this.updateSVGheight = false;
  517. }
  518. else {
  519. this.svg.style.height = ('' + this.options.graphHeight).replace('px','') + 'px';
  520. }
  521. // zoomed is here to ensure that animations are shown correctly.
  522. if (resized == true || zoomed == true || this.abortedGraphUpdate == true || forceGraphUpdate == true) {
  523. resized = this._updateGraph() || resized;
  524. }
  525. else {
  526. // move the whole svg while dragging
  527. if (this.lastStart != 0) {
  528. var offset = this.body.range.start - this.lastStart;
  529. var range = this.body.range.end - this.body.range.start;
  530. if (this.props.width != 0) {
  531. var rangePerPixelInv = this.props.width/range;
  532. var xOffset = offset * rangePerPixelInv;
  533. this.svg.style.left = (-this.props.width - xOffset) + 'px';
  534. }
  535. }
  536. }
  537. this.legendLeft.redraw();
  538. this.legendRight.redraw();
  539. return resized;
  540. };
  541. /**
  542. * Update and redraw the graph.
  543. *
  544. */
  545. LineGraph.prototype._updateGraph = function () {
  546. // reset the svg elements
  547. DOMutil.prepareElements(this.svgElements);
  548. if (this.props.width != 0 && this.itemsData != null) {
  549. var group, i;
  550. var preprocessedGroupData = {};
  551. var processedGroupData = {};
  552. var groupRanges = {};
  553. var changeCalled = false;
  554. // getting group Ids
  555. var groupIds = [];
  556. for (var groupId in this.groups) {
  557. if (this.groups.hasOwnProperty(groupId)) {
  558. group = this.groups[groupId];
  559. if (group.visible == true && (this.options.groups.visibility[groupId] === undefined || this.options.groups.visibility[groupId] == true)) {
  560. groupIds.push(groupId);
  561. }
  562. }
  563. }
  564. if (groupIds.length > 0) {
  565. // this is the range of the SVG canvas
  566. var minDate = this.body.util.toGlobalTime(-this.body.domProps.root.width);
  567. var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width);
  568. var groupsData = {};
  569. // fill groups data, this only loads the data we require based on the timewindow
  570. this._getRelevantData(groupIds, groupsData, minDate, maxDate);
  571. // apply sampling, if disabled, it will pass through this function.
  572. this._applySampling(groupIds, groupsData);
  573. // we transform the X coordinates to detect collisions
  574. for (i = 0; i < groupIds.length; i++) {
  575. preprocessedGroupData[groupIds[i]] = this._convertXcoordinates(groupsData[groupIds[i]]);
  576. }
  577. // now all needed data has been collected we start the processing.
  578. this._getYRanges(groupIds, preprocessedGroupData, groupRanges);
  579. // update the Y axis first, we use this data to draw at the correct Y points
  580. // changeCalled is required to clean the SVG on a change emit.
  581. changeCalled = this._updateYAxis(groupIds, groupRanges);
  582. var MAX_CYCLES = 5;
  583. if (changeCalled == true && this.COUNTER < MAX_CYCLES) {
  584. DOMutil.cleanupElements(this.svgElements);
  585. this.abortedGraphUpdate = true;
  586. this.COUNTER++;
  587. this.body.emitter.emit('change');
  588. return true;
  589. }
  590. else {
  591. if (this.COUNTER > MAX_CYCLES) {
  592. console.log("WARNING: there may be an infinite loop in the _updateGraph emitter cycle.")
  593. }
  594. this.COUNTER = 0;
  595. this.abortedGraphUpdate = false;
  596. // With the yAxis scaled correctly, use this to get the Y values of the points.
  597. for (i = 0; i < groupIds.length; i++) {
  598. group = this.groups[groupIds[i]];
  599. processedGroupData[groupIds[i]] = this._convertYcoordinates(groupsData[groupIds[i]], group);
  600. }
  601. // draw the groups
  602. for (i = 0; i < groupIds.length; i++) {
  603. group = this.groups[groupIds[i]];
  604. if (group.options.style != 'bar') { // bar needs to be drawn enmasse
  605. group.draw(processedGroupData[groupIds[i]], group, this.framework);
  606. }
  607. }
  608. BarGraphFunctions.draw(groupIds, processedGroupData, this.framework);
  609. }
  610. }
  611. }
  612. // cleanup unused svg elements
  613. DOMutil.cleanupElements(this.svgElements);
  614. return false;
  615. };
  616. /**
  617. * first select and preprocess the data from the datasets.
  618. * the groups have their preselection of data, we now loop over this data to see
  619. * what data we need to draw. Sorted data is much faster.
  620. * more optimization is possible by doing the sampling before and using the binary search
  621. * to find the end date to determine the increment.
  622. *
  623. * @param {array} groupIds
  624. * @param {object} groupsData
  625. * @param {date} minDate
  626. * @param {date} maxDate
  627. * @private
  628. */
  629. LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) {
  630. var group, i, j, item;
  631. if (groupIds.length > 0) {
  632. for (i = 0; i < groupIds.length; i++) {
  633. group = this.groups[groupIds[i]];
  634. groupsData[groupIds[i]] = [];
  635. var dataContainer = groupsData[groupIds[i]];
  636. // optimization for sorted data
  637. if (group.options.sort == true) {
  638. var guess = Math.max(0, util.binarySearchValue(group.itemsData, minDate, 'x', 'before'));
  639. for (j = guess; j < group.itemsData.length; j++) {
  640. item = group.itemsData[j];
  641. if (item !== undefined) {
  642. if (item.x > maxDate) {
  643. dataContainer.push(item);
  644. break;
  645. }
  646. else {
  647. dataContainer.push(item);
  648. }
  649. }
  650. }
  651. }
  652. else {
  653. for (j = 0; j < group.itemsData.length; j++) {
  654. item = group.itemsData[j];
  655. if (item !== undefined) {
  656. if (item.x > minDate && item.x < maxDate) {
  657. dataContainer.push(item);
  658. }
  659. }
  660. }
  661. }
  662. }
  663. }
  664. };
  665. /**
  666. *
  667. * @param groupIds
  668. * @param groupsData
  669. * @private
  670. */
  671. LineGraph.prototype._applySampling = function (groupIds, groupsData) {
  672. var group;
  673. if (groupIds.length > 0) {
  674. for (var i = 0; i < groupIds.length; i++) {
  675. group = this.groups[groupIds[i]];
  676. if (group.options.sampling == true) {
  677. var dataContainer = groupsData[groupIds[i]];
  678. if (dataContainer.length > 0) {
  679. var increment = 1;
  680. var amountOfPoints = dataContainer.length;
  681. // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
  682. // of width changing of the yAxis.
  683. var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x);
  684. var pointsPerPixel = amountOfPoints / xDistance;
  685. increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel)));
  686. var sampledData = [];
  687. for (var j = 0; j < amountOfPoints; j += increment) {
  688. sampledData.push(dataContainer[j]);
  689. }
  690. groupsData[groupIds[i]] = sampledData;
  691. }
  692. }
  693. }
  694. }
  695. };
  696. /**
  697. *
  698. *
  699. * @param {array} groupIds
  700. * @param {object} groupsData
  701. * @param {object} groupRanges | this is being filled here
  702. * @private
  703. */
  704. LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) {
  705. var groupData, group, i;
  706. var barCombinedDataLeft = [];
  707. var barCombinedDataRight = [];
  708. var options;
  709. if (groupIds.length > 0) {
  710. for (i = 0; i < groupIds.length; i++) {
  711. groupData = groupsData[groupIds[i]];
  712. options = this.groups[groupIds[i]].options;
  713. if (groupData.length > 0) {
  714. group = this.groups[groupIds[i]];
  715. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  716. if (options.barChart.handleOverlap == 'stack' && options.style == 'bar') {
  717. if (options.yAxisOrientation == 'left') {barCombinedDataLeft = barCombinedDataLeft.concat(group.getYRange(groupData)) ;}
  718. else {barCombinedDataRight = barCombinedDataRight.concat(group.getYRange(groupData));}
  719. }
  720. else {
  721. groupRanges[groupIds[i]] = group.getYRange(groupData,groupIds[i]);
  722. }
  723. }
  724. }
  725. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  726. BarGraphFunctions.getStackedBarYRange(barCombinedDataLeft , groupRanges, groupIds, '__barchartLeft' , 'left' );
  727. BarGraphFunctions.getStackedBarYRange(barCombinedDataRight, groupRanges, groupIds, '__barchartRight', 'right');
  728. }
  729. };
  730. /**
  731. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  732. * @param {Array} groupIds
  733. * @param {Object} groupRanges
  734. * @private
  735. */
  736. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  737. var resized = false;
  738. var yAxisLeftUsed = false;
  739. var yAxisRightUsed = false;
  740. var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal;
  741. // if groups are present
  742. if (groupIds.length > 0) {
  743. // 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.
  744. for (var i = 0; i < groupIds.length; i++) {
  745. var group = this.groups[groupIds[i]];
  746. if (group && group.options.yAxisOrientation == 'left') {
  747. yAxisLeftUsed = true;
  748. minLeft = 0;
  749. maxLeft = 0;
  750. }
  751. else {
  752. yAxisRightUsed = true;
  753. minRight = 0;
  754. maxRight = 0;
  755. }
  756. }
  757. // if there are items:
  758. for (var i = 0; i < groupIds.length; i++) {
  759. if (groupRanges.hasOwnProperty(groupIds[i])) {
  760. if (groupRanges[groupIds[i]].ignore !== true) {
  761. minVal = groupRanges[groupIds[i]].min;
  762. maxVal = groupRanges[groupIds[i]].max;
  763. if (groupRanges[groupIds[i]].yAxisOrientation == 'left') {
  764. yAxisLeftUsed = true;
  765. minLeft = minLeft > minVal ? minVal : minLeft;
  766. maxLeft = maxLeft < maxVal ? maxVal : maxLeft;
  767. }
  768. else {
  769. yAxisRightUsed = true;
  770. minRight = minRight > minVal ? minVal : minRight;
  771. maxRight = maxRight < maxVal ? maxVal : maxRight;
  772. }
  773. }
  774. }
  775. }
  776. if (yAxisLeftUsed == true) {
  777. this.yAxisLeft.setRange(minLeft, maxLeft);
  778. }
  779. if (yAxisRightUsed == true) {
  780. this.yAxisRight.setRange(minRight, maxRight);
  781. }
  782. }
  783. resized = this._toggleAxisVisiblity(yAxisLeftUsed , this.yAxisLeft) || resized;
  784. resized = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || resized;
  785. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  786. this.yAxisLeft.drawIcons = true;
  787. this.yAxisRight.drawIcons = true;
  788. }
  789. else {
  790. this.yAxisLeft.drawIcons = false;
  791. this.yAxisRight.drawIcons = false;
  792. }
  793. this.yAxisRight.master = !yAxisLeftUsed;
  794. if (this.yAxisRight.master == false) {
  795. if (yAxisRightUsed == true) {this.yAxisLeft.lineOffset = this.yAxisRight.width;}
  796. else {this.yAxisLeft.lineOffset = 0;}
  797. resized = this.yAxisLeft.redraw() || resized;
  798. this.yAxisRight.stepPixelsForced = this.yAxisLeft.stepPixels;
  799. this.yAxisRight.zeroCrossing = this.yAxisLeft.zeroCrossing;
  800. resized = this.yAxisRight.redraw() || resized;
  801. }
  802. else {
  803. resized = this.yAxisRight.redraw() || resized;
  804. }
  805. // clean the accumulated lists
  806. if (groupIds.indexOf('__barchartLeft') != -1) {
  807. groupIds.splice(groupIds.indexOf('__barchartLeft'),1);
  808. }
  809. if (groupIds.indexOf('__barchartRight') != -1) {
  810. groupIds.splice(groupIds.indexOf('__barchartRight'),1);
  811. }
  812. return resized;
  813. };
  814. /**
  815. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  816. *
  817. * @param {boolean} axisUsed
  818. * @returns {boolean}
  819. * @private
  820. * @param axis
  821. */
  822. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  823. var changed = false;
  824. if (axisUsed == false) {
  825. if (axis.dom.frame.parentNode && axis.hidden == false) {
  826. axis.hide()
  827. changed = true;
  828. }
  829. }
  830. else {
  831. if (!axis.dom.frame.parentNode && axis.hidden == true) {
  832. axis.show();
  833. changed = true;
  834. }
  835. }
  836. return changed;
  837. };
  838. /**
  839. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  840. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  841. * the yAxis.
  842. *
  843. * @param datapoints
  844. * @returns {Array}
  845. * @private
  846. */
  847. LineGraph.prototype._convertXcoordinates = function (datapoints) {
  848. var extractedData = [];
  849. var xValue, yValue;
  850. var toScreen = this.body.util.toScreen;
  851. for (var i = 0; i < datapoints.length; i++) {
  852. xValue = toScreen(datapoints[i].x) + this.props.width;
  853. yValue = datapoints[i].y;
  854. extractedData.push({x: xValue, y: yValue});
  855. }
  856. return extractedData;
  857. };
  858. /**
  859. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  860. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  861. * the yAxis.
  862. *
  863. * @param datapoints
  864. * @param group
  865. * @returns {Array}
  866. * @private
  867. */
  868. LineGraph.prototype._convertYcoordinates = function (datapoints, group) {
  869. var extractedData = [];
  870. var xValue, yValue;
  871. var toScreen = this.body.util.toScreen;
  872. var axis = this.yAxisLeft;
  873. var svgHeight = Number(this.svg.style.height.replace('px',''));
  874. if (group.options.yAxisOrientation == 'right') {
  875. axis = this.yAxisRight;
  876. }
  877. for (var i = 0; i < datapoints.length; i++) {
  878. xValue = toScreen(datapoints[i].x) + this.props.width;
  879. yValue = Math.round(axis.convertValue(datapoints[i].y));
  880. extractedData.push({x: xValue, y: yValue});
  881. }
  882. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  883. return extractedData;
  884. };
  885. module.exports = LineGraph;