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.

992 lines
31 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 BarFunctions = require('./graph2d_types/bar');
  10. var LineFunctions = require('./graph2d_types/line');
  11. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  12. /**
  13. * This is the constructor of the LineGraph. It requires a Timeline body and options.
  14. *
  15. * @param body
  16. * @param options
  17. * @constructor
  18. */
  19. function LineGraph(body, options) {
  20. this.id = util.randomUUID();
  21. this.body = body;
  22. this.defaultOptions = {
  23. yAxisOrientation: 'left',
  24. defaultGroup: 'default',
  25. sort: true,
  26. sampling: true,
  27. stack:false,
  28. graphHeight: '400px',
  29. shaded: {
  30. enabled: false,
  31. orientation: 'bottom' // top, bottom
  32. },
  33. style: 'line', // line, bar
  34. barChart: {
  35. width: 50,
  36. handleOverlap: 'overlap',
  37. align: 'center' // left, center, right
  38. },
  39. catmullRom: {
  40. enabled: true,
  41. parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
  42. alpha: 0.5
  43. },
  44. drawPoints: {
  45. enabled: true,
  46. size: 6,
  47. style: 'square' // square, circle
  48. },
  49. dataAxis: {
  50. showMinorLabels: true,
  51. showMajorLabels: true,
  52. icons: false,
  53. width: '40px',
  54. visible: true,
  55. alignZeros: true,
  56. left:{
  57. range: {min:undefined,max:undefined},
  58. format: {decimals:undefined},
  59. title: {text:undefined,style:undefined}
  60. },
  61. right:{
  62. range: {min:undefined,max:undefined},
  63. format: {decimals:undefined},
  64. title: {text:undefined,style:undefined}
  65. }
  66. },
  67. legend: {
  68. enabled: false,
  69. icons: true,
  70. left: {
  71. visible: true,
  72. position: 'top-left' // top/bottom - left,right
  73. },
  74. right: {
  75. visible: true,
  76. position: 'top-right' // top/bottom - left,right
  77. }
  78. },
  79. groups: {
  80. visibility: {}
  81. }
  82. };
  83. // options is shared by this ItemSet and all its items
  84. this.options = util.extend({}, this.defaultOptions);
  85. this.dom = {};
  86. this.props = {};
  87. this.hammer = null;
  88. this.groups = {};
  89. this.abortedGraphUpdate = false;
  90. this.updateSVGheight = false;
  91. this.updateSVGheightOnResize = false;
  92. var me = this;
  93. this.itemsData = null; // DataSet
  94. this.groupsData = null; // DataSet
  95. // listeners for the DataSet of the items
  96. this.itemListeners = {
  97. 'add': function (event, params, senderId) {
  98. me._onAdd(params.items);
  99. },
  100. 'update': function (event, params, senderId) {
  101. me._onUpdate(params.items);
  102. },
  103. 'remove': function (event, params, senderId) {
  104. me._onRemove(params.items);
  105. }
  106. };
  107. // listeners for the DataSet of the groups
  108. this.groupListeners = {
  109. 'add': function (event, params, senderId) {
  110. me._onAddGroups(params.items);
  111. },
  112. 'update': function (event, params, senderId) {
  113. me._onUpdateGroups(params.items);
  114. },
  115. 'remove': function (event, params, senderId) {
  116. me._onRemoveGroups(params.items);
  117. }
  118. };
  119. this.items = {}; // object with an Item for every data item
  120. this.selection = []; // list with the ids of all selected nodes
  121. this.lastStart = this.body.range.start;
  122. this.touchParams = {}; // stores properties while dragging
  123. this.svgElements = {};
  124. this.setOptions(options);
  125. this.groupsUsingDefaultStyles = [0];
  126. this.COUNTER = 0;
  127. this.body.emitter.on('rangechanged', function() {
  128. me.lastStart = me.body.range.start;
  129. me.svg.style.left = util.option.asSize(-me.props.width);
  130. me.redraw.call(me,true);
  131. });
  132. // create the HTML DOM
  133. this._create();
  134. this.framework = {svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups};
  135. this.body.emitter.emit('change');
  136. }
  137. LineGraph.prototype = new Component();
  138. /**
  139. * Create the HTML DOM for the ItemSet
  140. */
  141. LineGraph.prototype._create = function(){
  142. var frame = document.createElement('div');
  143. frame.className = 'vis-line-graph';
  144. this.dom.frame = frame;
  145. // create svg element for graph drawing.
  146. this.svg = document.createElementNS('http://www.w3.org/2000/svg','svg');
  147. this.svg.style.position = 'relative';
  148. this.svg.style.height = ('' + this.options.graphHeight).replace('px','') + 'px';
  149. this.svg.style.display = 'block';
  150. frame.appendChild(this.svg);
  151. // data axis
  152. this.options.dataAxis.orientation = 'left';
  153. this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  154. this.options.dataAxis.orientation = 'right';
  155. this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  156. delete this.options.dataAxis.orientation;
  157. // legends
  158. this.legendLeft = new Legend(this.body, this.options.legend, 'left', this.options.groups);
  159. this.legendRight = new Legend(this.body, this.options.legend, 'right', this.options.groups);
  160. this.show();
  161. };
  162. /**
  163. * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element.
  164. * @param {object} options
  165. */
  166. LineGraph.prototype.setOptions = function(options) {
  167. if (options) {
  168. var fields = ['sampling','defaultGroup','stack','height','graphHeight','yAxisOrientation','style','barChart','dataAxis','sort','groups'];
  169. if (options.graphHeight === undefined && options.height !== undefined && this.body.domProps.centerContainer.height !== undefined) {
  170. this.updateSVGheight = true;
  171. this.updateSVGheightOnResize = true;
  172. }
  173. else if (this.body.domProps.centerContainer.height !== undefined && options.graphHeight !== undefined) {
  174. if (parseInt((options.graphHeight + '').replace("px",'')) < this.body.domProps.centerContainer.height) {
  175. this.updateSVGheight = true;
  176. }
  177. }
  178. util.selectiveDeepExtend(fields, this.options, options);
  179. util.mergeOptions(this.options, options,'catmullRom');
  180. util.mergeOptions(this.options, options,'drawPoints');
  181. util.mergeOptions(this.options, options,'shaded');
  182. util.mergeOptions(this.options, options,'legend');
  183. if (options.catmullRom) {
  184. if (typeof options.catmullRom == 'object') {
  185. if (options.catmullRom.parametrization) {
  186. if (options.catmullRom.parametrization == 'uniform') {
  187. this.options.catmullRom.alpha = 0;
  188. }
  189. else if (options.catmullRom.parametrization == 'chordal') {
  190. this.options.catmullRom.alpha = 1.0;
  191. }
  192. else {
  193. this.options.catmullRom.parametrization = 'centripetal';
  194. this.options.catmullRom.alpha = 0.5;
  195. }
  196. }
  197. }
  198. }
  199. if (this.yAxisLeft) {
  200. if (options.dataAxis !== undefined) {
  201. this.yAxisLeft.setOptions(this.options.dataAxis);
  202. this.yAxisRight.setOptions(this.options.dataAxis);
  203. }
  204. }
  205. if (this.legendLeft) {
  206. if (options.legend !== undefined) {
  207. this.legendLeft.setOptions(this.options.legend);
  208. this.legendRight.setOptions(this.options.legend);
  209. }
  210. }
  211. if (this.groups.hasOwnProperty(UNGROUPED)) {
  212. this.groups[UNGROUPED].setOptions(options);
  213. }
  214. }
  215. // this is used to redraw the graph if the visibility of the groups is changed.
  216. if (this.dom.frame) {
  217. this.redraw(true);
  218. }
  219. };
  220. /**
  221. * Hide the component from the DOM
  222. */
  223. LineGraph.prototype.hide = function() {
  224. // remove the frame containing the items
  225. if (this.dom.frame.parentNode) {
  226. this.dom.frame.parentNode.removeChild(this.dom.frame);
  227. }
  228. };
  229. /**
  230. * Show the component in the DOM (when not already visible).
  231. * @return {Boolean} changed
  232. */
  233. LineGraph.prototype.show = function() {
  234. // show frame containing the items
  235. if (!this.dom.frame.parentNode) {
  236. this.body.dom.center.appendChild(this.dom.frame);
  237. }
  238. };
  239. /**
  240. * Set items
  241. * @param {vis.DataSet | null} items
  242. */
  243. LineGraph.prototype.setItems = function(items) {
  244. var me = this,
  245. ids,
  246. oldItemsData = this.itemsData;
  247. // replace the dataset
  248. if (!items) {
  249. this.itemsData = null;
  250. }
  251. else if (items instanceof DataSet || items instanceof DataView) {
  252. this.itemsData = items;
  253. }
  254. else {
  255. throw new TypeError('Data must be an instance of DataSet or DataView');
  256. }
  257. if (oldItemsData) {
  258. // unsubscribe from old dataset
  259. util.forEach(this.itemListeners, function (callback, event) {
  260. oldItemsData.off(event, callback);
  261. });
  262. // remove all drawn items
  263. ids = oldItemsData.getIds();
  264. this._onRemove(ids);
  265. }
  266. if (this.itemsData) {
  267. // subscribe to new dataset
  268. var id = this.id;
  269. util.forEach(this.itemListeners, function (callback, event) {
  270. me.itemsData.on(event, callback, id);
  271. });
  272. // add all new items
  273. ids = this.itemsData.getIds();
  274. this._onAdd(ids);
  275. }
  276. this._updateUngrouped();
  277. //this._updateGraph();
  278. this.redraw(true);
  279. };
  280. /**
  281. * Set groups
  282. * @param {vis.DataSet} groups
  283. */
  284. LineGraph.prototype.setGroups = function(groups) {
  285. var me = this;
  286. var ids;
  287. // unsubscribe from current dataset
  288. if (this.groupsData) {
  289. util.forEach(this.groupListeners, function (callback, event) {
  290. me.groupsData.unsubscribe(event, callback);
  291. });
  292. // remove all drawn groups
  293. ids = this.groupsData.getIds();
  294. this.groupsData = null;
  295. this._onRemoveGroups(ids); // note: this will cause a redraw
  296. }
  297. // replace the dataset
  298. if (!groups) {
  299. this.groupsData = null;
  300. }
  301. else if (groups instanceof DataSet || groups instanceof DataView) {
  302. this.groupsData = groups;
  303. }
  304. else {
  305. throw new TypeError('Data must be an instance of DataSet or DataView');
  306. }
  307. if (this.groupsData) {
  308. // subscribe to new dataset
  309. var id = this.id;
  310. util.forEach(this.groupListeners, function (callback, event) {
  311. me.groupsData.on(event, callback, id);
  312. });
  313. // draw all ms
  314. ids = this.groupsData.getIds();
  315. this._onAddGroups(ids);
  316. }
  317. this._onUpdate();
  318. };
  319. /**
  320. * Update the data
  321. * @param [ids]
  322. * @private
  323. */
  324. LineGraph.prototype._onUpdate = function(ids) {
  325. this._updateUngrouped();
  326. this._updateAllGroupData();
  327. //this._updateGraph();
  328. this.redraw(true);
  329. };
  330. LineGraph.prototype._onAdd = function (ids) {this._onUpdate(ids);};
  331. LineGraph.prototype._onRemove = function (ids) {this._onUpdate(ids);};
  332. LineGraph.prototype._onUpdateGroups = function (groupIds) {
  333. for (var i = 0; i < groupIds.length; i++) {
  334. var group = this.groupsData.get(groupIds[i]);
  335. this._updateGroup(group, groupIds[i]);
  336. }
  337. //this._updateGraph();
  338. this.redraw(true);
  339. };
  340. LineGraph.prototype._onAddGroups = function (groupIds) {this._onUpdateGroups(groupIds);};
  341. /**
  342. * this cleans the group out off the legends and the dataaxis, updates the ungrouped and updates the graph
  343. * @param {Array} groupIds
  344. * @private
  345. */
  346. LineGraph.prototype._onRemoveGroups = function (groupIds) {
  347. for (var i = 0; i < groupIds.length; i++) {
  348. if (this.groups.hasOwnProperty(groupIds[i])) {
  349. if (this.groups[groupIds[i]].options.yAxisOrientation == 'right') {
  350. this.yAxisRight.removeGroup(groupIds[i]);
  351. this.legendRight.removeGroup(groupIds[i]);
  352. this.legendRight.redraw();
  353. }
  354. else {
  355. this.yAxisLeft.removeGroup(groupIds[i]);
  356. this.legendLeft.removeGroup(groupIds[i]);
  357. this.legendLeft.redraw();
  358. }
  359. delete this.groups[groupIds[i]];
  360. }
  361. }
  362. this._updateUngrouped();
  363. //this._updateGraph();
  364. this.redraw(true);
  365. };
  366. /**
  367. * update a group object with the group dataset entree
  368. *
  369. * @param group
  370. * @param groupId
  371. * @private
  372. */
  373. LineGraph.prototype._updateGroup = function (group, groupId) {
  374. if (!this.groups.hasOwnProperty(groupId)) {
  375. this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles);
  376. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  377. this.yAxisRight.addGroup(groupId, this.groups[groupId]);
  378. this.legendRight.addGroup(groupId, this.groups[groupId]);
  379. }
  380. else {
  381. this.yAxisLeft.addGroup(groupId, this.groups[groupId]);
  382. this.legendLeft.addGroup(groupId, this.groups[groupId]);
  383. }
  384. }
  385. else {
  386. this.groups[groupId].update(group);
  387. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  388. this.yAxisRight.updateGroup(groupId, this.groups[groupId]);
  389. this.legendRight.updateGroup(groupId, this.groups[groupId]);
  390. }
  391. else {
  392. this.yAxisLeft.updateGroup(groupId, this.groups[groupId]);
  393. this.legendLeft.updateGroup(groupId, this.groups[groupId]);
  394. }
  395. }
  396. this.legendLeft.redraw();
  397. this.legendRight.redraw();
  398. };
  399. /**
  400. * this updates all groups, it is used when there is an update the the itemset.
  401. *
  402. * @private
  403. */
  404. LineGraph.prototype._updateAllGroupData = function () {
  405. if (this.itemsData != null) {
  406. var groupsContent = {};
  407. var groupId;
  408. for (groupId in this.groups) {
  409. if (this.groups.hasOwnProperty(groupId)) {
  410. groupsContent[groupId] = [];
  411. }
  412. }
  413. for (var itemId in this.itemsData._data) {
  414. if (this.itemsData._data.hasOwnProperty(itemId)) {
  415. var item = this.itemsData._data[itemId];
  416. if (groupsContent[item.group] === undefined) {
  417. 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.')
  418. }
  419. item.x = util.convert(item.x,'Date');
  420. groupsContent[item.group].push(item);
  421. }
  422. }
  423. for (groupId in this.groups) {
  424. if (this.groups.hasOwnProperty(groupId)) {
  425. this.groups[groupId].setItems(groupsContent[groupId]);
  426. }
  427. }
  428. }
  429. };
  430. /**
  431. * Create or delete the group holding all ungrouped items. This group is used when
  432. * there are no groups specified. This anonymous group is called 'graph'.
  433. * @protected
  434. */
  435. LineGraph.prototype._updateUngrouped = function() {
  436. if (this.itemsData && this.itemsData != null) {
  437. var ungroupedCounter = 0;
  438. for (var itemId in this.itemsData._data) {
  439. if (this.itemsData._data.hasOwnProperty(itemId)) {
  440. var item = this.itemsData._data[itemId];
  441. if (item != undefined) {
  442. if (item.hasOwnProperty('group')) {
  443. if (item.group === undefined) {
  444. item.group = UNGROUPED;
  445. }
  446. }
  447. else {
  448. item.group = UNGROUPED;
  449. }
  450. ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter;
  451. }
  452. }
  453. }
  454. if (ungroupedCounter == 0) {
  455. delete this.groups[UNGROUPED];
  456. this.legendLeft.removeGroup(UNGROUPED);
  457. this.legendRight.removeGroup(UNGROUPED);
  458. this.yAxisLeft.removeGroup(UNGROUPED);
  459. this.yAxisRight.removeGroup(UNGROUPED);
  460. }
  461. else {
  462. var group = {id: UNGROUPED, content: this.options.defaultGroup};
  463. this._updateGroup(group, UNGROUPED);
  464. }
  465. }
  466. else {
  467. delete this.groups[UNGROUPED];
  468. this.legendLeft.removeGroup(UNGROUPED);
  469. this.legendRight.removeGroup(UNGROUPED);
  470. this.yAxisLeft.removeGroup(UNGROUPED);
  471. this.yAxisRight.removeGroup(UNGROUPED);
  472. }
  473. this.legendLeft.redraw();
  474. this.legendRight.redraw();
  475. };
  476. /**
  477. * Redraw the component, mandatory function
  478. * @return {boolean} Returns true if the component is resized
  479. */
  480. LineGraph.prototype.redraw = function(forceGraphUpdate) {
  481. var resized = false;
  482. // calculate actual size and position
  483. this.props.width = this.dom.frame.offsetWidth;
  484. this.props.height = this.body.domProps.centerContainer.height;
  485. // update the graph if there is no lastWidth or with, used for the initial draw
  486. if (this.lastWidth === undefined && this.props.width) {
  487. forceGraphUpdate = true;
  488. }
  489. // check if this component is resized
  490. resized = this._isResized() || resized;
  491. // check whether zoomed (in that case we need to re-stack everything)
  492. var visibleInterval = this.body.range.end - this.body.range.start;
  493. var zoomed = (visibleInterval != this.lastVisibleInterval);
  494. this.lastVisibleInterval = visibleInterval;
  495. // the svg element is three times as big as the width, this allows for fully dragging left and right
  496. // without reloading the graph. the controls for this are bound to events in the constructor
  497. if (resized == true) {
  498. this.svg.style.width = util.option.asSize(3*this.props.width);
  499. this.svg.style.left = util.option.asSize(-this.props.width);
  500. // if the height of the graph is set as proportional, change the height of the svg
  501. if ((this.options.height + '').indexOf("%") != -1 || this.updateSVGheightOnResize == true) {
  502. this.updateSVGheight = true;
  503. }
  504. }
  505. // update the height of the graph on each redraw of the graph.
  506. if (this.updateSVGheight == true) {
  507. if (this.options.graphHeight != this.body.domProps.centerContainer.height + 'px') {
  508. this.options.graphHeight = this.body.domProps.centerContainer.height + 'px';
  509. this.svg.style.height = this.body.domProps.centerContainer.height + 'px';
  510. }
  511. this.updateSVGheight = false;
  512. }
  513. else {
  514. this.svg.style.height = ('' + this.options.graphHeight).replace('px','') + 'px';
  515. }
  516. // zoomed is here to ensure that animations are shown correctly.
  517. if (resized == true || zoomed == true || this.abortedGraphUpdate == true || forceGraphUpdate == true) {
  518. resized = this._updateGraph() || resized;
  519. }
  520. else {
  521. // move the whole svg while dragging
  522. if (this.lastStart != 0) {
  523. var offset = this.body.range.start - this.lastStart;
  524. var range = this.body.range.end - this.body.range.start;
  525. if (this.props.width != 0) {
  526. var rangePerPixelInv = this.props.width/range;
  527. var xOffset = offset * rangePerPixelInv;
  528. this.svg.style.left = (-this.props.width - xOffset) + 'px';
  529. }
  530. }
  531. }
  532. this.legendLeft.redraw();
  533. this.legendRight.redraw();
  534. return resized;
  535. };
  536. /**
  537. * Update and redraw the graph.
  538. *
  539. */
  540. LineGraph.prototype._updateGraph = function () {
  541. // reset the svg elements
  542. DOMutil.prepareElements(this.svgElements);
  543. if (this.props.width != 0 && this.itemsData != null) {
  544. var group, i;
  545. var preprocessedGroupData = {};
  546. var processedGroupData = {};
  547. var groupRanges = {};
  548. var changeCalled = false;
  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. BarFunctions.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 combinedDataLeft = [];
  702. var combinedDataRight = [];
  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.stack === true) {
  712. if (options.yAxisOrientation == 'left') {combinedDataLeft = combinedDataLeft .concat(group.getData(groupData));}
  713. else {combinedDataRight = combinedDataRight.concat(group.getData(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. BarFunctions.getStackedYRange(combinedDataLeft , groupRanges, groupIds, '__barStackLeft' , 'left' );
  722. BarFunctions.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__barStackRight', 'right');
  723. // if line graphs are stacked, their range need to be handled differently and accumulated over all groups.
  724. LineFunctions.getStackedYRange(combinedDataLeft , groupRanges, groupIds, '__lineStackLeft' , 'left' );
  725. LineFunctions.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__lineStackRight', 'right');
  726. }
  727. };
  728. /**
  729. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  730. * @param {Array} groupIds
  731. * @param {Object} groupRanges
  732. * @private
  733. */
  734. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  735. var resized = false;
  736. var yAxisLeftUsed = false;
  737. var yAxisRightUsed = false;
  738. var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal;
  739. // if groups are present
  740. if (groupIds.length > 0) {
  741. // 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.
  742. for (var i = 0; i < groupIds.length; i++) {
  743. var group = this.groups[groupIds[i]];
  744. if (group && group.options.yAxisOrientation != 'right') {
  745. yAxisLeftUsed = true;
  746. minLeft = 0;
  747. maxLeft = 0;
  748. }
  749. else if (group && group.options.yAxisOrientation) {
  750. yAxisRightUsed = true;
  751. minRight = 0;
  752. maxRight = 0;
  753. }
  754. }
  755. // if there are items:
  756. for (var i = 0; i < groupIds.length; i++) {
  757. if (groupRanges.hasOwnProperty(groupIds[i])) {
  758. if (groupRanges[groupIds[i]].ignore !== true) {
  759. minVal = groupRanges[groupIds[i]].min;
  760. maxVal = groupRanges[groupIds[i]].max;
  761. if (groupRanges[groupIds[i]].yAxisOrientation != 'right') {
  762. yAxisLeftUsed = true;
  763. minLeft = minLeft > minVal ? minVal : minLeft;
  764. maxLeft = maxLeft < maxVal ? maxVal : maxLeft;
  765. }
  766. else {
  767. yAxisRightUsed = true;
  768. minRight = minRight > minVal ? minVal : minRight;
  769. maxRight = maxRight < maxVal ? maxVal : maxRight;
  770. }
  771. }
  772. }
  773. }
  774. if (yAxisLeftUsed == true) {
  775. this.yAxisLeft.setRange(minLeft, maxLeft);
  776. }
  777. if (yAxisRightUsed == true) {
  778. this.yAxisRight.setRange(minRight, maxRight);
  779. }
  780. }
  781. resized = this._toggleAxisVisiblity(yAxisLeftUsed , this.yAxisLeft) || resized;
  782. resized = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || resized;
  783. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  784. this.yAxisLeft.drawIcons = true;
  785. this.yAxisRight.drawIcons = true;
  786. }
  787. else {
  788. this.yAxisLeft.drawIcons = false;
  789. this.yAxisRight.drawIcons = false;
  790. }
  791. this.yAxisRight.master = !yAxisLeftUsed;
  792. if (this.yAxisRight.master == false) {
  793. if (yAxisRightUsed == true) {this.yAxisLeft.lineOffset = this.yAxisRight.width;}
  794. else {this.yAxisLeft.lineOffset = 0;}
  795. resized = this.yAxisLeft.redraw() || resized;
  796. this.yAxisRight.stepPixels = this.yAxisLeft.stepPixels;
  797. this.yAxisRight.zeroCrossing = this.yAxisLeft.zeroCrossing;
  798. this.yAxisRight.amountOfSteps = this.yAxisLeft.amountOfSteps;
  799. resized = this.yAxisRight.redraw() || resized;
  800. }
  801. else {
  802. resized = this.yAxisRight.redraw() || resized;
  803. }
  804. // clean the accumulated lists
  805. var tempGroups = ['__barStackLeft','__barStackRight','__lineStackLeft','__lineStackRight'];
  806. for (var i = 0; i < tempGroups.length; i++) {
  807. if (groupIds.indexOf(tempGroups[i]) != -1) {groupIds.splice(groupIds.indexOf(tempGroups[i]),1);}
  808. }
  809. return resized;
  810. };
  811. /**
  812. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  813. *
  814. * @param {boolean} axisUsed
  815. * @returns {boolean}
  816. * @private
  817. * @param axis
  818. */
  819. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  820. var changed = false;
  821. if (axisUsed == false) {
  822. if (axis.dom.frame.parentNode && axis.hidden == false) {
  823. axis.hide()
  824. changed = true;
  825. }
  826. }
  827. else {
  828. if (!axis.dom.frame.parentNode && axis.hidden == true) {
  829. axis.show();
  830. changed = true;
  831. }
  832. }
  833. return changed;
  834. };
  835. /**
  836. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  837. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  838. * the yAxis.
  839. *
  840. * @param datapoints
  841. * @returns {Array}
  842. * @private
  843. */
  844. LineGraph.prototype._convertXcoordinates = function (datapoints) {
  845. var extractedData = [];
  846. var xValue, yValue;
  847. var toScreen = this.body.util.toScreen;
  848. for (var i = 0; i < datapoints.length; i++) {
  849. xValue = toScreen(datapoints[i].x) + this.props.width;
  850. yValue = datapoints[i].y;
  851. extractedData.push({x: xValue, y: yValue});
  852. }
  853. return extractedData;
  854. };
  855. /**
  856. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  857. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  858. * the yAxis.
  859. *
  860. * @param datapoints
  861. * @param group
  862. * @returns {Array}
  863. * @private
  864. */
  865. LineGraph.prototype._convertYcoordinates = function (datapoints, group) {
  866. var extractedData = [];
  867. var xValue, yValue;
  868. var toScreen = this.body.util.toScreen;
  869. var axis = this.yAxisLeft;
  870. var svgHeight = Number(this.svg.style.height.replace('px',''));
  871. if (group.options.yAxisOrientation == 'right') {
  872. axis = this.yAxisRight;
  873. }
  874. for (var i = 0; i < datapoints.length; i++) {
  875. var labelValue = datapoints[i].label ? datapoints[i].label : null;
  876. xValue = toScreen(datapoints[i].x) + this.props.width;
  877. yValue = Math.round(axis.convertValue(datapoints[i].y));
  878. extractedData.push({x: xValue, y: yValue, label:labelValue});
  879. }
  880. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  881. return extractedData;
  882. };
  883. module.exports = LineGraph;