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.

994 lines
30 KiB

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