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.

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