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.

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